Layr-Labs/mlx

diff: ignored:
+20128
-1997
+1107
-0

This is an overview of the changes in Layr-Labs/mlx, a fork of ml-explore/mlx.

The fork is the core of Layr-Labs’ Apple-silicon inference stack — mlx → mlx-c → mlx-swift → mlx-swift-lm — and carries the kernel, allocator and Metal-runtime work that serving production MoE models (Gemma 4, Qwen 3.5⁄3.6, GPT-OSS) needed before or beyond what upstream ships: sorted expert-tile quantized matmul routes, a masked-tail MXFP4 decode kernel, FP32-safe SDPA partials, coherent allocator accounting for admission control, declared-mutable custom-kernel inputs for paged KV, and a use-after-free fix in Metal eval. Every change is meant to be additive and rebasable; each is gated by shape, device or environment checks so the upstream path stays the default elsewhere.

The fork also changes JACCL, the RDMA-over-Thunderbolt backend that runs one model across two Macs: it zeroes the unused tail of every send frame, and a progress guard fails a call that gets no completion, closes its group and by default releases the GPU memory and exits the process with status 75. These two are not gated. The zeroing is always on, and the guard is on with a 30 s limit that JACCL_PROGRESS_TIMEOUT_MS=0 removes; JACCL_TIMEOUT_ACTION=throw keeps the process alive and throws instead.

gpu::eval captured the MTL::CommandBuffer* before eval_gpu ran and attached the input-buffer liveness handler to it afterwards. Any primitive that calls CommandEncoder::synchronize() mid-eval — the expert-tile route’s sortedness-retract check does — commits and replaces the encoder’s buffer, so the handler landed on a dangling pointer (latent on Gemma E=128, a deterministic SIGSEGV on Qwen E=256). The buffer is now fetched from the encoder after eval_gpu, so inputs outlive exactly the tail of the primitive’s work. (PR #5)

diff --git ml-explore/mlx/mlx/backend/metal/eval.cpp Layr-Labs/mlx/mlx/backend/metal/eval.cpp index 43a6fb993288a5ad2e1422ccea6357e89a921d33..b275e1ca76788551718e327c6ea17f101a3db949 100644 --- ml-explore/mlx/mlx/backend/metal/eval.cpp +++ Layr-Labs/mlx/mlx/backend/metal/eval.cpp @@ -30,7 +30,6 @@ void eval(array& arr) { auto pool = metal::new_scoped_memory_pool(); auto s = arr.primitive().stream(); auto& encoder = metal::get_command_encoder(s); - auto* command_buffer = encoder.get_command_buffer();   auto outputs = arr.outputs(); { @@ -41,30 +40,36 @@ if (arr.is_tracer()) { inputs = arr.inputs(); }   - debug_set_primitive_buffer_label(command_buffer, arr.primitive()); + debug_set_primitive_buffer_label( + encoder.get_command_buffer(), arr.primitive()); arr.primitive().eval_gpu(arr.inputs(), outputs); } - std::unordered_set<std::shared_ptr<array::Data>> buffers; + // Keep the inputs and siblings alive until the command buffer completes; + // the output is skipped when an input donated its buffer to it. Retention + // is batched per command buffer (`retain_until_completed`): a hash set plus + // a Metal completion handler per primitive dominated host-side encode time + // for decode-sized kernels. Retained AFTER eval_gpu, into the encoder's + // current buffer: a primitive that synchronizes mid-eval (e.g. the + // expert-tile route's descriptor retract check) commits and replaces the + // buffer, and the current one holds the tail of this primitive's work, + // which is exactly what the inputs must outlive. A duplicate input is + // retained twice, which only costs one more reference. + auto* out_data = arr.data_shared_ptr().get(); for (auto& in : arr.inputs()) { - buffers.insert(in.data_shared_ptr()); + if (in.data_shared_ptr().get() != out_data) { + encoder.retain_until_completed(in.data_shared_ptr()); + } } - for (auto& s : arr.siblings()) { - buffers.insert(s.data_shared_ptr()); - } - // Remove the output if it was donated to by an input - if (auto it = buffers.find(arr.data_shared_ptr()); it != buffers.end()) { - buffers.erase(it); + for (auto& sib : arr.siblings()) { + if (sib.data_shared_ptr().get() != out_data) { + encoder.retain_until_completed(sib.data_shared_ptr()); + } }   if (encoder.needs_commit()) { encoder.end_encoding(); scheduler::notify_new_task(s); - encoder.commit([s, buffers = std::move(buffers)]() { - scheduler::notify_task_completion(s); - }); - } else { - command_buffer->addCompletedHandler( - [buffers = std::move(buffers)](MTL::CommandBuffer* cbuf) {}); + encoder.commit([s]() { scheduler::notify_task_completion(s); }); } }

An opt-in route (MLX_GATHER_QMM_EXPERT_SLICES=1|trust) for gathered, affine-quantized MoE expert matmuls: a descriptor kernel builds sorted expert tiles on device (one instantiation per expert count) and a single expert-count-agnostic tile kernel consumes them. classify_gemma4_expert_qmm is a pure route table admitting exactly the shapes the kernel is built for; availability is all-or-nothing on a source-matched metallib so an older library fails the route closed; trust skips the descriptor-retract readback when the caller guarantees sorted indices. A retracted call runs the unsorted gather route, because the sorted gather_qmm_rhs kernels read per-expert offsets and give a correct result only for sorted indices (PR #27). Diagnostics counters (mlx_metal_gemma4_expert_qmm_diagnostics_*) are exposed through a C ABI so mlx-c / mlx-swift can arm, snapshot and reset them.

diff --git ml-explore/mlx/mlx/backend/common/gemma4_expert_qmm.h Layr-Labs/mlx/mlx/backend/common/gemma4_expert_qmm.h new file mode 100644 index 0000000000000000000000000000000000000000..1a1ce37542e0695eb006370d7901f3668e34126d --- /dev/null +++ Layr-Labs/mlx/mlx/backend/common/gemma4_expert_qmm.h @@ -0,0 +1,293 @@ +// Copyright © 2023-2024 Apple Inc. + +#pragma once + +#include <stdint.h> + +#include "mlx/api.h" + +#if defined(__APPLE__) +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct mlx_metal_gemma4_expert_qmm_diagnostics { + uint8_t requested; + uint8_t aot_available; + uint8_t nax_available; + uint8_t armed; + uint64_t attempts; + uint64_t hits; + uint64_t fallback_nax; + uint64_t fallback_outer_route; + uint64_t fallback_quantization; + uint64_t fallback_topology; + uint64_t fallback_assignment_count; + uint64_t fallback_geometry; + uint64_t fallback_metallib_unavailable; + uint64_t fallback_sortedness_retracted; +} mlx_metal_gemma4_expert_qmm_diagnostics; + +MLX_API void mlx_metal_gemma4_expert_qmm_diagnostics_snapshot( + mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics); +MLX_API void mlx_metal_gemma4_expert_qmm_diagnostics_reset(void); +MLX_API void mlx_metal_gemma4_expert_qmm_diagnostics_clear_and_arm(void); +MLX_API void mlx_metal_gemma4_expert_qmm_diagnostics_snapshot_and_disarm( + mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics); + +#ifdef __cplusplus +} +#endif +#endif + +#ifdef __cplusplus + +#include <atomic> + +namespace mlx::core::metal { + +enum class Gemma4ExpertQMMRoute : uint8_t { + not_requested, + hit, + fallback_nax, + fallback_outer_route, + fallback_quantization, + fallback_topology, + fallback_assignment_count, + fallback_geometry, + fallback_metallib_unavailable, + fallback_sortedness_retracted, +}; + +struct Gemma4ExpertQMMRouteInput { + bool requested{false}; + bool aot_available{false}; + bool nax_available{false}; + bool outer_route{false}; + + bool affine{false}; + bool transpose{false}; + bool has_bias{false}; + bool indices_uint32{false}; + bool indices_contiguous{false}; + bool x_bfloat16{false}; + bool x_contiguous{false}; + bool w_uint32{false}; + bool w_contiguous{false}; + bool scales_bfloat16{false}; + bool scales_contiguous{false}; + bool biases_bfloat16{false}; + bool biases_contiguous{false}; + + int group_size{0}; + int bits{0}; + int expert_count{0}; + int assignments{0}; + int index_count{0}; + int k{0}; + int n{0}; + + int x_rank{0}; + int x_dim0{0}; + int x_dim1{0}; + int x_dim2{0}; + int w_rank{0}; + int w_dim0{0}; + int w_dim1{0}; + int w_dim2{0}; + int scales_rank{0}; + int scales_dim0{0}; + int scales_dim1{0}; + int scales_dim2{0}; + int biases_rank{0}; + int biases_dim0{0}; + int biases_dim1{0}; + int biases_dim2{0}; +}; + +inline Gemma4ExpertQMMRoute classify_gemma4_expert_qmm( + const Gemma4ExpertQMMRouteInput& input) { + if (!input.requested) { + return Gemma4ExpertQMMRoute::not_requested; + } + if (!input.outer_route) { + return Gemma4ExpertQMMRoute::fallback_outer_route; + } + // The existing NAX route owns every supported BF16/transposed RHS call and + // must win before the Gemma 4 specialization or its AOT capability matters. + if (input.nax_available) { + return Gemma4ExpertQMMRoute::fallback_nax; + } + if (!input.affine || !input.transpose || !input.has_bias || + !input.indices_uint32 || !input.indices_contiguous || !input.x_bfloat16 || + !input.x_contiguous || !input.w_uint32 || !input.w_contiguous || + !input.scales_bfloat16 || !input.scales_contiguous || + !input.biases_bfloat16 || !input.biases_contiguous || + input.group_size != 64 || input.bits != 4) { + return Gemma4ExpertQMMRoute::fallback_quantization; + } + const bool gemma4 = input.expert_count == 128; + const bool qwen36 = input.expert_count == 256; + if ((!gemma4 && !qwen36) || input.x_rank != 3 || + input.x_dim0 != input.assignments || input.x_dim1 != 1 || + input.x_dim2 != input.k || input.w_rank != 3 || + input.w_dim0 != input.expert_count || input.scales_rank != 3 || + input.scales_dim0 != input.expert_count || input.biases_rank != 3 || + input.biases_dim0 != input.expert_count || + input.index_count != input.assignments) { + return Gemma4ExpertQMMRoute::fallback_topology; + } + if (input.assignments != 4096 && input.assignments != 8192 && + input.assignments != 16384) { + return Gemma4ExpertQMMRoute::fallback_assignment_count; + } + + // Whole-projection geometry for one expert matrix [E, n, k] at W4/g64: + // packed weight columns k/8 (eight 4-bit values per uint32) and one + // scale/bias per 64-wide group, k/64 columns. The quantization gate above + // guarantees bits==4 and group_size==64, so the divisions are exact. + auto projection = [&input](int k, int n) { + return input.k == k && input.n == n && input.w_dim1 == n && + input.w_dim2 == k / 8 && input.scales_dim1 == n && + input.scales_dim2 == k / 64 && input.biases_dim1 == n && + input.biases_dim2 == k / 64; + }; + // Gemma 4 26B-A4B (E=128): gate/up [128,1408,2816] and down [128,2816,704]. + // Qwen 3.5/3.6 35B-A3B (E=256): fused gate_up [256,1024,2048], split + // gate/up [256,512,2048], and down [256,2048,512]. The tile kernel itself + // is expert-count agnostic; only the descriptor builder instantiation + // differs (one thread per expert). + const bool hit_geometry = gemma4 + ? (projection(2816, 1408) || projection(704, 2816)) + : (projection(2048, 1024) || projection(2048, 512) || + projection(512, 2048)); + if (!hit_geometry) { + return Gemma4ExpertQMMRoute::fallback_geometry; + } + if (!input.aot_available) { + return Gemma4ExpertQMMRoute::fallback_metallib_unavailable; + } + return Gemma4ExpertQMMRoute::hit; +} + +struct Gemma4ExpertQMMCounterSnapshot { + uint64_t hits{0}; + uint64_t fallback_nax{0}; + uint64_t fallback_outer_route{0}; + uint64_t fallback_quantization{0}; + uint64_t fallback_topology{0}; + uint64_t fallback_assignment_count{0}; + uint64_t fallback_geometry{0}; + uint64_t fallback_metallib_unavailable{0}; + uint64_t fallback_sortedness_retracted{0}; + bool armed{false}; + + uint64_t attempts() const { + return hits + fallback_nax + fallback_outer_route + fallback_quantization + + fallback_topology + fallback_assignment_count + fallback_geometry + + fallback_metallib_unavailable + fallback_sortedness_retracted; + } +}; + +class Gemma4ExpertQMMCounters { + public: + bool armed() const { + return armed_.load(std::memory_order_relaxed); + } + + // Recording is called only after the caller's relaxed-atomic armed branch. + // Keeping the branch at that boundary makes the unarmed inference path free + // of counter atomic operations while the engine-idle arm/disarm contract + // makes access to armed_ well-defined. + void record(Gemma4ExpertQMMRoute route) { + std::atomic<uint64_t>* counter = nullptr; + switch (route) { + case Gemma4ExpertQMMRoute::not_requested: + return; + case Gemma4ExpertQMMRoute::hit: + counter = &hits_; + break; + case Gemma4ExpertQMMRoute::fallback_nax: + counter = &fallback_nax_; + break; + case Gemma4ExpertQMMRoute::fallback_outer_route: + counter = &fallback_outer_route_; + break; + case Gemma4ExpertQMMRoute::fallback_quantization: + counter = &fallback_quantization_; + break; + case Gemma4ExpertQMMRoute::fallback_topology: + counter = &fallback_topology_; + break; + case Gemma4ExpertQMMRoute::fallback_assignment_count: + counter = &fallback_assignment_count_; + break; + case Gemma4ExpertQMMRoute::fallback_geometry: + counter = &fallback_geometry_; + break; + case Gemma4ExpertQMMRoute::fallback_metallib_unavailable: + counter = &fallback_metallib_unavailable_; + break; + case Gemma4ExpertQMMRoute::fallback_sortedness_retracted: + counter = &fallback_sortedness_retracted_; + break; + } + counter->fetch_add(1, std::memory_order_relaxed); + } + + Gemma4ExpertQMMCounterSnapshot snapshot() const { + return { + hits_.load(std::memory_order_relaxed), + fallback_nax_.load(std::memory_order_relaxed), + fallback_outer_route_.load(std::memory_order_relaxed), + fallback_quantization_.load(std::memory_order_relaxed), + fallback_topology_.load(std::memory_order_relaxed), + fallback_assignment_count_.load(std::memory_order_relaxed), + fallback_geometry_.load(std::memory_order_relaxed), + fallback_metallib_unavailable_.load(std::memory_order_relaxed), + fallback_sortedness_retracted_.load(std::memory_order_relaxed), + armed_.load(std::memory_order_relaxed), + }; + } + + Gemma4ExpertQMMCounterSnapshot snapshot_and_disarm() { + const bool was_armed = armed_.load(std::memory_order_relaxed); + armed_.store(false, std::memory_order_relaxed); + auto result = snapshot(); + result.armed = was_armed; + return result; + } + + void reset() { + hits_.store(0, std::memory_order_relaxed); + fallback_nax_.store(0, std::memory_order_relaxed); + fallback_outer_route_.store(0, std::memory_order_relaxed); + fallback_quantization_.store(0, std::memory_order_relaxed); + fallback_topology_.store(0, std::memory_order_relaxed); + fallback_assignment_count_.store(0, std::memory_order_relaxed); + fallback_geometry_.store(0, std::memory_order_relaxed); + fallback_metallib_unavailable_.store(0, std::memory_order_relaxed); + fallback_sortedness_retracted_.store(0, std::memory_order_relaxed); + } + + void clear_and_arm() { + reset(); + armed_.store(true, std::memory_order_relaxed); + } + + private: + std::atomic<bool> armed_{false}; + std::atomic<uint64_t> hits_{0}; + std::atomic<uint64_t> fallback_nax_{0}; + std::atomic<uint64_t> fallback_outer_route_{0}; + std::atomic<uint64_t> fallback_quantization_{0}; + std::atomic<uint64_t> fallback_topology_{0}; + std::atomic<uint64_t> fallback_assignment_count_{0}; + std::atomic<uint64_t> fallback_geometry_{0}; + std::atomic<uint64_t> fallback_metallib_unavailable_{0}; + std::atomic<uint64_t> fallback_sortedness_retracted_{0}; +}; + +} // namespace mlx::core::metal + +#endif
diff --git ml-explore/mlx/mlx/backend/metal/device.cpp Layr-Labs/mlx/mlx/backend/metal/device.cpp index 493e8e3153cdd9b0bd370197dbeff808bcfbcfe3..66f599e35edf791ef60cce643dc26138ef181c75 100644 --- ml-explore/mlx/mlx/backend/metal/device.cpp +++ Layr-Labs/mlx/mlx/backend/metal/device.cpp @@ -1,5 +1,7 @@ // Copyright © 2023-2024 Apple Inc.   +#include <algorithm> +#include <cctype> #include <cstdlib> #include <sstream>   @@ -9,6 +11,7 @@ #define NS_PRIVATE_IMPLEMENTATION #define CA_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION   +#include "mlx/backend/common/command_buffer_limits.h" #include "mlx/backend/common/utils.h" #include "mlx/backend/metal/device.h" #include "mlx/backend/metal/event.h" @@ -362,13 +365,12 @@ void CommandEncoder::set_input_array( const array& a, int idx, int64_t offset /* = 0 */) { - if (all_inputs_.insert(a.buffer().ptr()).second) { + if (all_inputs_.insert(a.buffer().ptr())) { buffer_sizes_ += a.data_size(); } auto r_buf = static_cast<MTL::Resource*>(const_cast<void*>(a.buffer().ptr())); next_inputs_.insert(r_buf); - needs_barrier_ = - needs_barrier_ | (prev_outputs_.find(r_buf) != prev_outputs_.end()); + needs_barrier_ = needs_barrier_ | prev_outputs_.contains(r_buf); auto a_buf = static_cast<const MTL::Buffer*>(a.buffer().ptr()); get_command_encoder()->setBuffer(a_buf, a.offset() + offset, idx); } @@ -390,8 +392,7 @@ if (concurrent_) { concurrent_outputs_.insert(buf); } else { next_outputs_.insert(buf); - needs_barrier_ = - needs_barrier_ | (prev_inputs_.find(buf) != prev_inputs_.end()); + needs_barrier_ = needs_barrier_ | prev_inputs_.contains(buf); } }   @@ -410,7 +411,7 @@ void CommandEncoder::maybeInsertBarrier() { if (needs_barrier_) { get_command_encoder()->memoryBarrier(MTL::BarrierScopeBuffers); needs_barrier_ = false; - // Preserve the hash tables' buckets for reuse across barrier epochs. + // Keep the sets' memory for reuse across barrier epochs. prev_inputs_.swap(next_inputs_); prev_outputs_.swap(next_outputs_); } else { @@ -481,7 +482,7 @@ } // A spin wait must start after all earlier encoders, as it might block // earlier operations to be finished. // See https://github.com/ml-explore/mlx/pull/4689 - if (wait_in_flight) { + if (wait_in_flight || wait_all_pending_) { for (auto& [_, fence] : prev_ce_outputs_) { if (waiting_on.insert(fence).second) { encoder_->waitForFence(fence.get()); @@ -497,7 +498,8 @@ encoder_->updateFence(fence_.get()); buffer_->addCompletedHandler([this, fence = std::move(fence_), temporaries = std::move(temporaries_), - all_outputs = std::move(all_outputs_), + all_outputs = std::vector<const void*>( + all_outputs_.begin(), all_outputs_.end()), waiting_on = std::move(waiting_on)]( MTL::CommandBuffer*) mutable { std::lock_guard lk(outputs_mtx_); @@ -513,6 +515,7 @@ encoder_->endEncoding(); encoder_.reset(); needs_barrier_ = false; + wait_all_pending_ = false; concurrent_ = false; prev_inputs_.clear(); next_inputs_.clear(); @@ -520,6 +523,7 @@ prev_outputs_.clear(); next_outputs_.clear(); concurrent_outputs_.clear(); all_inputs_.clear(); + all_outputs_.clear(); }   void CommandEncoder::signal_event(Event event, uint64_t value) { @@ -534,6 +538,42 @@ buffer_->encodeWait(event.cast<EventImpl>().mtl_event(), value); wait_events_.push_back(std::move(event)); }   +namespace { +// Per-thread commit limits; zero selects the device default. +thread_local int thread_max_ops_per_buffer = 0; +thread_local int thread_max_mb_per_buffer = 0; +// Per-thread steel quantized-matmul output tile (32, 64, 6432, 3264 or 6464); +// zero selects MLX_QMM_STEEL_TILE (see `qmm` in quantized.cpp). +thread_local int thread_qmm_steel_tile_override = 0; + +void set_thread_command_buffer_limits( + int max_ops, + int max_mb, + int* previous_ops, + int* previous_mb) { + if (previous_ops != nullptr) { + *previous_ops = thread_max_ops_per_buffer; + } + if (previous_mb != nullptr) { + *previous_mb = thread_max_mb_per_buffer; + } + thread_max_ops_per_buffer = std::max(0, max_ops); + thread_max_mb_per_buffer = std::max(0, max_mb); +} +} // namespace + +int thread_qmm_steel_tile() { + return thread_qmm_steel_tile_override; +} + +std::tuple<int, int> Device::get_max_ops_mb_per_buffer() const { + return std::make_tuple( + thread_max_ops_per_buffer > 0 ? thread_max_ops_per_buffer + : max_ops_per_buffer_, + thread_max_mb_per_buffer > 0 ? thread_max_mb_per_buffer + : max_mb_per_buffer_); +} + bool CommandEncoder::needs_commit() const { auto [max_ops, max_mb] = device_.get_max_ops_mb_per_buffer(); return (buffer_ops_ > max_ops) || ((buffer_sizes_ >> 20) > max_mb); @@ -547,10 +587,13 @@ buffer_->addCompletedHandler( [&error_ = error_, wait_events = std::move(wait_events_), signal_events = std::move(signal_events_), + retained = std::move(retained_), completion = std::move(completion)](MTL::CommandBuffer* cbuf) mutable { if (completion) { completion(); } + // The buffer finished: release what its primitives kept alive. + retained.clear(); // If any of the waited event has error in it, poison the encoder. for (auto& event : wait_events) { if (error_.store_if_valid(event.load_error())) { @@ -585,6 +628,9 @@ buffer_->commit(); buffer_ = NS::RetainPtr(queue_->commandBufferWithUnretainedReferences()); buffer_ops_ = 0; buffer_sizes_ = 0; + // The moved-from vector is valid but unspecified: reset it explicitly. + retained_ = {}; + retained_.reserve(256); }   void CommandEncoder::synchronize() { @@ -612,6 +658,53 @@ Device::Device() : device_(load_device()), residency_sets_(device_.get()) { auto pool = new_scoped_memory_pool(); default_library_ = NS::TransferPtr(load_default_library(device_.get())); + + std::string expert_qmm_env = env::get_var("MLX_GATHER_QMM_EXPERT_SLICES", ""); + std::transform( + expert_qmm_env.begin(), + expert_qmm_env.end(), + expert_qmm_env.begin(), + [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); + gemma4_expert_qmm_requested_ = expert_qmm_env == "1" || + expert_qmm_env == "true" || expert_qmm_env == "on" || + expert_qmm_env == "yes" || expert_qmm_env == "trust"; + // "trust" additionally skips the descriptor-retract readback: the caller + // asserts its sorted-indices contract is machine-guaranteed (the Swift + // SwitchGLU path sorts on-device), so the host never drains the stream to + // observe a retracted build. Under trust, a genuinely mis-sorted input + // produces undefined tile output instead of the legacy fallback. + gemma4_expert_qmm_trust_sorted_ = expert_qmm_env == "trust"; + + constexpr const char* descriptor_kernel = + "build_gemma4_sorted_expert_tiles_bm32"; + constexpr const char* descriptor_kernel_e256 = + "build_sorted_expert_tiles_bm32_e256"; + constexpr const char* tile_kernel = + "affine_gather_qmm_gemma4_expert_tiles_bfloat16_t_gs_64_b_4_" + "alN_true_bm_32_bn_32_bk_32"; + auto has_default_function = [this](const char* name) { + auto ns_name = NS::String::string(name, NS::ASCIIStringEncoding); + auto function = NS::TransferPtr(default_library_->newFunction(ns_name)); + return function.get() != nullptr; + }; + // All expert-tile symbols ship from one source-matched metallib + // (scripts/fetch-metallib.sh completeness contract), so availability is + // all-or-nothing: a metallib missing any of them predates this revision + // and must fail the whole route closed. + gemma4_expert_qmm_aot_available_ = has_default_function(descriptor_kernel) && + has_default_function(descriptor_kernel_e256) && + has_default_function(tile_kernel); + if (gemma4_expert_qmm_requested_ && gemma4_expert_qmm_aot_available_) { + try { + // Resolve the pipelines once so missing or incompatible packaged AOT + // assets fail closed before an inference command encoder is touched. + get_kernel(descriptor_kernel); + get_kernel(descriptor_kernel_e256); + get_kernel(tile_kernel); + } catch (...) { + gemma4_expert_qmm_aot_available_ = false; + } + } arch_ = env::metal_gpu_arch(); if (arch_.empty()) { arch_ = std::string(device_->architecture()->name()->utf8String()); @@ -997,3 +1090,90 @@ #endif }   } // namespace mlx::core::metal + +#if defined(__APPLE__) +namespace { +void gemma4_expert_qmm_diagnostics_snapshot( + mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics, + bool disarm) { + if (diagnostics == nullptr) { + return; + } + *diagnostics = {}; + try { + auto& d = mlx::core::metal::device(mlx::core::Device::gpu); + const auto counters = disarm + ? d.gemma4_expert_qmm_counter_snapshot_and_disarm() + : d.gemma4_expert_qmm_counter_snapshot(); + diagnostics->requested = d.gemma4_expert_qmm_requested(); + diagnostics->aot_available = d.gemma4_expert_qmm_aot_available(); + diagnostics->nax_available = mlx::core::metal::is_nax_available(); + diagnostics->armed = counters.armed; + diagnostics->attempts = counters.attempts(); + diagnostics->hits = counters.hits; + diagnostics->fallback_nax = counters.fallback_nax; + diagnostics->fallback_outer_route = counters.fallback_outer_route; + diagnostics->fallback_quantization = counters.fallback_quantization; + diagnostics->fallback_topology = counters.fallback_topology; + diagnostics->fallback_assignment_count = counters.fallback_assignment_count; + diagnostics->fallback_geometry = counters.fallback_geometry; + diagnostics->fallback_metallib_unavailable = + counters.fallback_metallib_unavailable; + diagnostics->fallback_sortedness_retracted = + counters.fallback_sortedness_retracted; + } catch (...) { + // Diagnostics are optional. A missing Metal device must remain observable + // as an all-zero snapshot rather than escaping an exception through C ABI. + } +} +} // namespace + +extern "C" void mlx_metal_set_thread_command_buffer_limits( + int max_ops, + int max_mb, + int* previous_ops, + int* previous_mb) { + mlx::core::metal::set_thread_command_buffer_limits( + max_ops, max_mb, previous_ops, previous_mb); +} + +extern "C" void mlx_metal_set_thread_qmm_steel_tile( + int tile, + int* previous_tile) { + if (previous_tile != nullptr) { + *previous_tile = mlx::core::metal::thread_qmm_steel_tile_override; + } + mlx::core::metal::thread_qmm_steel_tile_override = + (tile == 32 || tile == 64 || tile == 6432 || tile == 3264 || tile == 6464) + ? tile + : 0; +} + +extern "C" void mlx_metal_gemma4_expert_qmm_diagnostics_snapshot( + mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics) { + gemma4_expert_qmm_diagnostics_snapshot(diagnostics, false); +} + +extern "C" void mlx_metal_gemma4_expert_qmm_diagnostics_reset(void) { + try { + mlx::core::metal::device(mlx::core::Device::gpu) + .reset_gemma4_expert_qmm_counters(); + } catch (...) { + // Reset is best-effort on hosts without an accessible Metal device. + } +} + +extern "C" void mlx_metal_gemma4_expert_qmm_diagnostics_clear_and_arm(void) { + try { + mlx::core::metal::device(mlx::core::Device::gpu) + .clear_and_arm_gemma4_expert_qmm_counters(); + } catch (...) { + // Arming is best-effort on hosts without an accessible Metal device. + } +} + +extern "C" void mlx_metal_gemma4_expert_qmm_diagnostics_snapshot_and_disarm( + mlx_metal_gemma4_expert_qmm_diagnostics* diagnostics) { + gemma4_expert_qmm_diagnostics_snapshot(diagnostics, true); +} +#endif
diff --git ml-explore/mlx/mlx/backend/metal/device.h Layr-Labs/mlx/mlx/backend/metal/device.h index 305a35a772534b4a94e3247890f1fcbbdd3d6154..92e6b4589bd50db5308771600b256ccd681713d4 100644 --- ml-explore/mlx/mlx/backend/metal/device.h +++ Layr-Labs/mlx/mlx/backend/metal/device.h @@ -3,13 +3,17 @@ #pragma once   #include <Metal/Metal.hpp> +#include <algorithm> +#include <cstdint> #include <functional> #include <mutex> #include <shared_mutex> #include <unordered_map> #include <unordered_set> +#include <vector>   #include "mlx/array.h" +#include "mlx/backend/common/gemma4_expert_qmm.h" #include "mlx/backend/common/metal_kernel.h" #include "mlx/backend/metal/resident.h" #include "mlx/device.h" @@ -21,6 +25,139 @@ std::vector<std::tuple<const void*, MTL::DataType, NS::UInteger>>;   class Device;   +// A set of buffer pointers for the encoder's hazard tracking. A small set is +// a vector with a linear search; a larger set also gets an open addressing +// index. clear() keeps the memory, so a warm encoder does not allocate. +class BufferSet { + public: + BufferSet() = default; + BufferSet(const BufferSet&) = delete; + BufferSet& operator=(const BufferSet&) = delete; + + // Returns true if `p` was not in the set. + bool insert(const void* p) { + if (!indexed_) { + if (std::find(items_.begin(), items_.end(), p) != items_.end()) { + return false; + } + items_.push_back(p); + if (items_.size() > kLinearMax) { + build_index(); + } + return true; + } + auto i = find_slot(key(p)); + if (slots_[i] != kEmpty) { + return false; + } + slots_[i] = key(p); + items_.push_back(p); + if (2 * items_.size() > slots_.size()) { + build_index(); + } + return true; + } + + template <typename It> + void insert(It first, It last) { + for (; first != last; ++first) { + insert(*first); + } + } + + bool contains(const void* p) const { + if (!indexed_) { + return std::find(items_.begin(), items_.end(), p) != items_.end(); + } + return slots_[find_slot(key(p))] != kEmpty; + } + + void erase(const void* p) { + auto it = std::find(items_.begin(), items_.end(), p); + if (it == items_.end()) { + return; + } + *it = items_.back(); + items_.pop_back(); + if (indexed_) { + erase_slot(find_slot(key(p))); + } + } + + // build_index() resets every slot, so the index needs no clearing here. + void clear() { + items_.clear(); + indexed_ = false; + } + + void swap(BufferSet& other) noexcept { + items_.swap(other.items_); + slots_.swap(other.slots_); + std::swap(indexed_, other.indexed_); + } + + size_t size() const { + return items_.size(); + } + std::vector<const void*>::const_iterator begin() const { + return items_.begin(); + } + std::vector<const void*>::const_iterator end() const { + return items_.end(); + } + + private: + static constexpr size_t kLinearMax = 16; + static constexpr uintptr_t kEmpty = ~uintptr_t(0); + + static uintptr_t key(const void* p) { + return reinterpret_cast<uintptr_t>(p); + } + static size_t hash(uintptr_t k) { + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + return static_cast<size_t>(k); + } + // The slot that holds `k`, or the empty slot where it would go. + size_t find_slot(uintptr_t k) const { + size_t mask = slots_.size() - 1; + size_t i = hash(k) & mask; + while (slots_[i] != kEmpty && slots_[i] != k) { + i = (i + 1) & mask; + } + return i; + } + // Remove slot i and move back later entries of its probe run. + void erase_slot(size_t i) { + size_t mask = slots_.size() - 1; + for (size_t j = (i + 1) & mask; slots_[j] != kEmpty; j = (j + 1) & mask) { + size_t home = hash(slots_[j]) & mask; + bool stays = (i <= j) ? (i < home && home <= j) : (i < home || home <= j); + if (!stays) { + slots_[i] = slots_[j]; + i = j; + } + } + slots_[i] = kEmpty; + } + void build_index() { + size_t capacity = 64; + while (capacity < 4 * items_.size()) { + capacity *= 2; + } + slots_.assign(capacity, kEmpty); + for (auto p : items_) { + slots_[find_slot(key(p))] = key(p); + } + indexed_ = true; + } + + std::vector<const void*> items_; + std::vector<uintptr_t> slots_; + bool indexed_{false}; +}; + class MLX_API CommandEncoder { public: CommandEncoder(Device& d, int index, ResidencySets& residency_sets); @@ -94,6 +231,15 @@ return ConcurrentContext(*this); }   void barrier(); + + // The current pass waits for every pass still in flight on this queue, not + // only those that wrote its inputs (see Fence::wait). + void wait_for_all_pending() { + wait_all_pending_ = true; + } + + // With wait_in_flight the pass that ends waits for every pass in flight, + // as wait_for_all_pending() does. void end_encoding(bool wait_in_flight = false); void wait_event(Event event, uint64_t value); void signal_event(Event event, uint64_t value); @@ -103,6 +249,17 @@ void synchronize();   MTL::CommandBuffer* get_command_buffer() const { return buffer_.get(); + } + + // Keep an object (array data, a fence) alive until the command buffer that + // is current now completes. Everything retained is released by the single + // completion handler commit() installs, instead of one Metal completion + // handler (an Objective-C block plus a hash set) per encoded primitive. + // A primitive that commits mid-eval (e.g. the expert-tile route's retract + // check) retains into the replacement buffer, which completes after the + // committed one on this queue, so the lifetime is never shorter. + void retain_until_completed(std::shared_ptr<void> object) { + retained_.push_back(std::move(object)); }   private: @@ -134,19 +291,24 @@ // reset after calling end_encoding(). NS::SharedPtr<MTL::ComputeCommandEncoder> encoder_; NS::SharedPtr<MTL::Fence> fence_; bool needs_barrier_{false}; + bool wait_all_pending_{false}; bool concurrent_{false}; std::vector<array> temporaries_; - std::unordered_set<MTL::Resource*> prev_inputs_; - std::unordered_set<MTL::Resource*> prev_outputs_; - std::unordered_set<MTL::Resource*> next_inputs_; - std::unordered_set<MTL::Resource*> next_outputs_; - std::unordered_set<MTL::Resource*> concurrent_outputs_; - std::unordered_set<const void*> all_inputs_; - std::unordered_set<const void*> all_outputs_; + BufferSet prev_inputs_; + BufferSet prev_outputs_; + BufferSet next_inputs_; + BufferSet next_outputs_; + BufferSet concurrent_outputs_; + BufferSet all_inputs_; + BufferSet all_outputs_;   // A map of prior command encoder outputs to their corresponding fence. std::unordered_map<const void*, NS::SharedPtr<MTL::Fence>> prev_ce_outputs_; std::mutex outputs_mtx_; + + // Objects kept alive until the current command buffer completes + // (`retain_until_completed`); moved into its completion handler at commit. + std::vector<std::shared_ptr<void>> retained_; };   class MLX_API Device { @@ -166,9 +328,9 @@ } int get_architecture_gen() const { return arch_gen_; } - std::tuple<int, int> get_max_ops_mb_per_buffer() const { - return std::make_tuple(max_ops_per_buffer_, max_mb_per_buffer_); - } + // The device defaults, or the calling thread's limits where set + // (mlx_metal_set_thread_command_buffer_limits). + std::tuple<int, int> get_max_ops_mb_per_buffer() const;   MTL::Library* get_library( const std::string& name, @@ -204,6 +366,46 @@ ResidencySets& residency_sets() { return residency_sets_; }   + bool gemma4_expert_qmm_requested() const { + return gemma4_expert_qmm_requested_; + } + + // MLX_GATHER_QMM_EXPERT_SLICES=trust: skip the descriptor-retract + // readback in the expert-tile route (no mid-eval stream drain). The + // caller asserts sorted indices are machine-guaranteed; a violation + // yields undefined tile output instead of the legacy fallback. + bool gemma4_expert_qmm_trust_sorted() const { + return gemma4_expert_qmm_trust_sorted_; + } + + bool gemma4_expert_qmm_aot_available() const { + return gemma4_expert_qmm_aot_available_; + } + bool gemma4_expert_qmm_diagnostics_armed() const { + return gemma4_expert_qmm_counters_.armed(); + } + + // Call only inside a route boundary guarded by + // gemma4_expert_qmm_diagnostics_armed(). + void record_armed_gemma4_expert_qmm(Gemma4ExpertQMMRoute route) { + gemma4_expert_qmm_counters_.record(route); + } + + Gemma4ExpertQMMCounterSnapshot gemma4_expert_qmm_counter_snapshot() const { + return gemma4_expert_qmm_counters_.snapshot(); + } + Gemma4ExpertQMMCounterSnapshot + gemma4_expert_qmm_counter_snapshot_and_disarm() { + return gemma4_expert_qmm_counters_.snapshot_and_disarm(); + } + + void reset_gemma4_expert_qmm_counters() { + gemma4_expert_qmm_counters_.reset(); + } + void clear_and_arm_gemma4_expert_qmm_counters() { + gemma4_expert_qmm_counters_.clear_and_arm(); + } + private: NS::SharedPtr<MTL::Library> build_library_( const std::string& source_string, @@ -243,6 +445,10 @@ std::shared_mutex kernel_mtx_; std::shared_mutex library_mtx_; std::unordered_map<std::string, NS::SharedPtr<MTL::Library>> library_map_; NS::SharedPtr<MTL::Library> default_library_; + bool gemma4_expert_qmm_requested_{false}; + bool gemma4_expert_qmm_trust_sorted_{false}; + bool gemma4_expert_qmm_aot_available_{false}; + Gemma4ExpertQMMCounters gemma4_expert_qmm_counters_; std::unordered_map< MTL::Library*, std::unordered_map<std::string, NS::SharedPtr<MTL::ComputePipelineState>>> @@ -254,6 +460,11 @@ int max_mb_per_buffer_; };   MLX_API Device& device(mlx::core::Device); + +// The calling thread's steel quantized-matmul output tile (32, 64, 6432, +// 3264 or 6464), or 0 +// for MLX_QMM_STEEL_TILE (mlx_metal_set_thread_qmm_steel_tile). +int thread_qmm_steel_tile(); MLX_API CommandEncoder& get_command_encoder(Stream s);   std::unordered_map<int, CommandEncoder>& get_command_encoders();
diff --git ml-explore/mlx/mlx/backend/metal/kernels/quantized.h Layr-Labs/mlx/mlx/backend/metal/kernels/quantized.h index 48fe55cd98b2c2bfc58463ab3bae32c67da81469..19c429dd54b5bff2c8227c3d0d77076b2ccdd034 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/quantized.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/quantized.h @@ -15,7 +15,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4;   template <int bits, int wsize = 8> -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); }   @@ -671,7 +671,7 @@ short reduction_dim, short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -683,7 +683,7 @@ bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}");   - MLX_MTL_CONST short pack_factor = get_pack_factor<bits, 8>(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor<bits, 8>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -710,7 +710,7 @@ const device uint8_t* src; const device T* scales; const device T* biases;   - QuantizedBlockLoader( + AffineQuantizedBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -751,7 +751,7 @@ if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; }   - if (bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -761,11 +761,17 @@ T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize<T, pack_factor, bits>( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize<T, pack_factor, bits>( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } }   @@ -863,7 +869,7 @@ constexpr int packs_per_thread = bits <= 2 ? 1 : 2; // 1-bit: 1 pack (vpt=32) for occupancy constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; - constexpr int pack_factor = get_pack_factor<bits, 32>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 32>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -976,7 +982,7 @@ uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor<bits, 32>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 32>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>();   constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -1234,7 +1240,7 @@ uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<bits, 32>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 32>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   constexpr int tn = 32 / pack_factor; @@ -1334,6 +1340,134 @@ typename T, const int group_size, const int bits, const bool aligned_N, + const int BM = 32, + const int BK = 32, + const int BN = 32> +METAL_FUNC void qmm_t_expert_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + threadgroup T* Xs, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const int M, + const constant int& K_eff, + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); + static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); + + (void)lid; + + constexpr int WM = 2; + constexpr int WN = 2; + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); + constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + + // Instantiate the appropriate BlockMMA and Loader + using mma_t = mlx::steel:: + BlockMMA<T, T, BM, BN, BK, WM, WN, false, true, BK_padded, BK_padded>; + using loader_x_t = + mlx::steel::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE>; + using loader_w_t = AffineQuantizedBlockLoader< + T, + BN, + BK, + BK_padded, + 1, + WM * WN * SIMD_SIZE, + group_size, + bits>; + + // Set the block + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + + auto wl = (const device uint8_t*)w; + + x += y_row * static_cast<int64_t>(K); + wl += y_col * K_w; + scales += y_col * K_g; + biases += y_col * K_g; + y += y_row * static_cast<int64_t>(N) + y_col; + + // Make the x loader and mma operation + const short num_els = min(BM, M - y_row); + const short num_outs = min(BN, N - y_col); + loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, biases, K, Ws, simd_gid, simd_lid); + mma_t mma_op(simd_gid, simd_lid); + + if (num_els < BM) { + if (!aligned_N && num_outs < BN) { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_safe(short2(BK, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } else { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } else { + if (!aligned_N && num_outs < BN) { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_safe(short2(BK, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } else { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } + + // Store results to device memory + threadgroup_barrier(mem_flags::mem_threadgroup); + if (num_els < BM || num_outs < BN) { + mma_op.store_result_safe(y, N, short2(num_outs, num_els)); + } else { + mma_op.store_result(y, N); + } +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, typename U = T, const int BM = 32, const int BK = 32, @@ -1361,7 +1495,7 @@ (void)lid;   constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1371,7 +1505,7 @@ using mma_t = mlx::steel:: BlockMMA<T, U, BM, BN, BK, WM, WN, false, true, BK_padded, BK_padded>; using loader_x_t = mlx::steel::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE>; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BN, BK, @@ -1487,7 +1621,7 @@ (void)lid;   constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1498,7 +1632,7 @@ using mma_t = mlx::steel:: BlockMMA<T, T, BM, BN, BK, WM, WN, false, false, BK_padded, BN_padded>; using loader_x_t = mlx::steel:: BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE, 1, 4>; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, BK, BN, @@ -2134,7 +2268,7 @@ uint simd_lid [[thread_index_in_simdgroup]]) { (void)lid;   constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   threadgroup T Xs[BM * BK_padded]; @@ -2567,6 +2701,230 @@ qmm_n_impl<T, group_size, bits, BM, BK, BN>( w, scales, biases, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); }   +// Descriptor builder for the sorted expert-tile route. One thread per expert +// (threadgroup size == NE); instantiated for NE=128 (Gemma 4) and NE=256 +// (Qwen 3.5/3.6 MoE) in quantized.metal. +template <int NE> +[[kernel]] void build_sorted_expert_tiles_bm32( + const device uint32_t* indices [[buffer(0)]], + device uint4* descriptors [[buffer(1)]], + device uint* count [[buffer(2)]], + const constant int& M [[buffer(3)]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr uint expert_count = uint(NE); + constexpr uint BM = 32; + constexpr uint simdgroup_count = expert_count / 32; + threadgroup uint segment_starts[expert_count + 1]; + threadgroup uint inclusive_tile_offsets[expert_count]; + threadgroup uint violation_votes[simdgroup_count]; + + // One thread finds each expert's first sorted row. The last thread also + // supplies the sentinel, so all NE+1 boundaries are ready after one barrier. + int lower = 0; + int upper = M; + while (lower < upper) { + const int midpoint = lower + (upper - lower) / 2; + if (indices[midpoint] < lid) { + lower = midpoint + 1; + } else { + upper = midpoint; + } + } + segment_starts[lid] = uint(lower); + if (lid == expert_count - 1) { + segment_starts[expert_count] = uint(M); + } + + // The binary search is only sound when `indices` is non-decreasing across + // the whole array; a mis-sorted input would silently mis-attribute rows to + // experts. The check is twofold. Each thread verifies its own segment + // boundary against the generalized invariant + // `indices[start - 1] < lid <= indices[start]` (edge threads have only one + // neighbor to check). Independently of that search, a strided adjacent-pair + // scan validates `indices[i - 1] <= indices[i]` for every i in [1, M): + // thread `lid` covers i = lid + 1, lid + NE + 1, ..., so the NE threads + // between them inspect every adjacent pair exactly once (for the reachable + // M in {4096, 8192, 16384} that is a bounded number of iterations each). + // Adjacent-pair monotonicity is transitive, so a clean scan is a sound and + // complete proof that the array is globally non-decreasing; no + // intra-segment inversion can escape it. The simdgroups vote with simd_or + // over the conjunction, and the votes fold threadgroup-wide through shared + // memory; the barrier below orders both loops' results before the fold. On + // any violation the kernel retracts the descriptor count below so the tile + // kernel early-returns and the host re-routes to the order-agnostic legacy + // path. + bool boundary_ok = true; + if (lower > 0) { + boundary_ok = boundary_ok && indices[lower - 1] < lid; + } + if (lower < M) { + boundary_ok = boundary_ok && indices[lower] >= lid; + } + bool adjacent_ok = true; + for (int i = int(lid) + 1; i < M; i += int(expert_count)) { + adjacent_ok = adjacent_ok && indices[i - 1] <= indices[i]; + } + const uint violation_vote = simd_or((boundary_ok && adjacent_ok) ? 0u : 1u); + if (simd_lid == 0) { + violation_votes[simd_gid] = violation_vote; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Every thread folds the per-simdgroup votes uniformly. + bool sorted_violation = false; + for (uint group = 0; group < simdgroup_count; ++group) { + sorted_violation = sorted_violation || violation_votes[group] != 0u; + } + // count[1] is the violation observability slot; count[0] is the descriptor + // count. + if (lid == 0) { + count[1] = sorted_violation ? 1u : 0u; + } + + const uint segment_rows = segment_starts[lid + 1] - segment_starts[lid]; + inclusive_tile_offsets[lid] = (segment_rows + BM - 1) / BM; + threadgroup_barrier(mem_flags::mem_threadgroup); + + // log2(NE) uniform Hillis-Steele strides form an inclusive scan over the + // experts. The read barrier precedes each in-place update and the write + // barrier makes that stride visible to the next one. + for (uint stride = 1; stride < expert_count; stride <<= 1) { + const uint addend = + lid >= stride ? inclusive_tile_offsets[lid - stride] : 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lid >= stride) { + inclusive_tile_offsets[lid] += addend; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + const uint descriptor_count = inclusive_tile_offsets[expert_count - 1]; + if (lid == expert_count - 1) { + // A retracted count keeps the tile kernel's capacity check memory-safe + // (every threadgroup early-returns) and unambiguously signals the host: + // the assignment-count route gate guarantees M is 4096/8192/16384, so a + // valid build always emits at least one tile. + count[0] = sorted_violation ? 0u : descriptor_count; + } + + // Every thread emits a strided share of the bounded descriptor array. + // upper_bound over the inclusive offsets maps each slot back to its expert. + for (uint slot = lid; slot < descriptor_count; slot += expert_count) { + uint expert_lower = 0; + uint expert_upper = expert_count; + while (expert_lower < expert_upper) { + const uint midpoint = expert_lower + (expert_upper - expert_lower) / 2; + if (inclusive_tile_offsets[midpoint] <= slot) { + expert_lower = midpoint + 1; + } else { + expert_upper = midpoint; + } + } + const uint expert = expert_lower; + const uint expert_tile_begin = + expert == 0 ? 0 : inclusive_tile_offsets[expert - 1]; + const uint row = segment_starts[expert] + (slot - expert_tile_begin) * BM; + const uint row_count = min(BM, segment_starts[expert + 1] - row); + descriptors[slot] = uint4(row, row_count, expert, 0); + } +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, + const int BM = 32, + const int BK = 32, + const int BN = 32> +[[kernel]] void affine_gather_qmm_gemma4_expert_tiles( + const device T* x [[buffer(0)]], + const device uint32_t* w [[buffer(1)]], + const device T* scales [[buffer(2)]], + const device T* biases [[buffer(3)]], + const device uint4* descriptors [[buffer(4)]], + const device uint* count [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& K [[buffer(7)]], + const constant int& N [[buffer(8)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BM == 32, "Gemma 4 expert tiles require BM=32"); + static_assert(BK == 32, "Gemma 4 expert tiles require BK=32"); + static_assert(BN == 32, "Gemma 4 expert tiles require BN=32"); + + // tid.y is uniform across the threadgroup. Empty capacity slots return + // before any threadgroup allocation is consumed by a microkernel barrier. + const uint descriptor_count = count[0]; + if (tid.y >= descriptor_count) { + return; + } + + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); + constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); + constexpr int BK_padded = BK + 16 / sizeof(T); + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BN * BK_padded]; + + const uint4 descriptor = descriptors[tid.y]; + const size_t row_start = size_t(descriptor.x); + const int row_count = int(descriptor.y); + const size_t expert = size_t(descriptor.z); + + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const size_t expert_w_stride = size_t(N) * size_t(K_w); + const size_t expert_sb_stride = size_t(N) * size_t(K_g); + + x += row_start * size_t(K); + y += row_start * size_t(N); + const device uint8_t* expert_w = + reinterpret_cast<const device uint8_t*>(w) + expert * expert_w_stride; + scales += expert * expert_sb_stride; + biases += expert * expert_sb_stride; + + const uint3 local_tid = uint3(tid.x, 0, 0); + if (row_count <= 16) { + qmm_t_expert_impl<T, group_size, bits, aligned_N, 16, BK, BN>( + reinterpret_cast<const device uint32_t*>(expert_w), + scales, + biases, + x, + y, + Xs, + Ws, + K, + N, + row_count, + K, + local_tid, + lid, + simd_gid, + simd_lid); + } else { + qmm_t_expert_impl<T, group_size, bits, aligned_N, BM, BK, BN>( + reinterpret_cast<const device uint32_t*>(expert_w), + scales, + biases, + x, + y, + Xs, + Ws, + K, + N, + row_count, + K, + local_tid, + lid, + simd_gid, + simd_lid); + } +} + template < typename T, int group_size, @@ -2591,7 +2949,7 @@ const constant int& num_groups [[buffer(9)]], uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2610,7 +2968,7 @@ BK_padded, transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE>; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, @@ -2728,7 +3086,7 @@ uint2 grid_dim [[threads_per_grid]]) { constexpr float eps = 1e-7; constexpr int simd_size = 32; constexpr float n_bins = (1 << bits) - 1; - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); constexpr int values_per_reduce = group_size / simd_size; constexpr int writes_per_reduce = pack_factor / values_per_reduce; @@ -2839,7 +3197,7 @@ const device T* biases [[buffer(2)]], device T* out [[buffer(3)]], uint2 index [[thread_position_in_grid]], uint2 grid_dim [[threads_per_grid]]) { - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   size_t offset = index.x + grid_dim.x * size_t(index.y);
diff --git ml-explore/mlx/mlx/backend/metal/kernels/quantized.metal Layr-Labs/mlx/mlx/backend/metal/kernels/quantized.metal index 263a41570cf677531851e6ea98803c563ecd8902..42d5e35ab6d76462fd95f79d38189d1428808e3e 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/quantized.metal +++ Layr-Labs/mlx/mlx/backend/metal/kernels/quantized.metal @@ -199,4 +199,31 @@ instantiate_quantized_groups(5) \ instantiate_quantized_groups(6) \ instantiate_quantized_groups(8)   -instantiate_quantized_all() // clang-format on +instantiate_quantized_all() + +instantiate_kernel( + "affine_gather_qmm_gemma4_expert_tiles_bfloat16_t_gs_64_b_4_alN_true_bm_32_bn_32_bk_32", + affine_gather_qmm_gemma4_expert_tiles, + bfloat16_t, + 64, + 4, + true, + 32, + 32, + 32) + +// Sorted expert-tile descriptor builders. The E=128 instantiation keeps the +// historical Gemma 4 host name; E=256 serves Qwen 3.5/3.6 MoE. The tile +// kernel instantiation above is expert-count agnostic (K/N are runtime +// arguments) and is shared by both routes. +instantiate_kernel( + "build_gemma4_sorted_expert_tiles_bm32", + build_sorted_expert_tiles_bm32, + 128) + +instantiate_kernel( + "build_sorted_expert_tiles_bm32_e256", + build_sorted_expert_tiles_bm32, + 256) + + // clang-format on
diff --git ml-explore/mlx/mlx/backend/metal/quantized.cpp Layr-Labs/mlx/mlx/backend/metal/quantized.cpp index 6fdff2fbedb6848120122e9c21e7ac08b4a2c1f2..a9ace92263a951747c7bdebd28e34e11570bf6c4 100644 --- ml-explore/mlx/mlx/backend/metal/quantized.cpp +++ Layr-Labs/mlx/mlx/backend/metal/quantized.cpp @@ -5,6 +5,7 @@ #include "mlx/backend/common/broadcasting.h" #include "mlx/backend/common/compiled.h" #include "mlx/backend/gpu/copy.h" #include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/gptoss_mxfp4_policy.h" #include "mlx/backend/metal/kernels.h" #include "mlx/backend/metal/matmul.h" #include "mlx/backend/metal/reduce.h" @@ -15,6 +16,10 @@ #include "mlx/primitives.h" #include "mlx/utils.h"   namespace mlx::core { + +using metal::classify_gemma4_expert_qmm; +using metal::Gemma4ExpertQMMRoute; +using metal::Gemma4ExpertQMMRouteInput;   namespace {   @@ -50,6 +55,26 @@ std::string fname = ((mode == "affine") ? "affine_" : "fp_") + func; template_def = get_template_definition( name, fname, type, group_size, bits, std::forward<Args>(args)...); return get_qmm_nax_kernel(d, name, template_def, mode); +} + +template <typename... Args> +auto get_qmm_nax_kernel_wrapped_fc( + metal::Device& d, + const std::string& name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const std::string& func, + const std::string& mode, + const std::string& type, + int group_size, + int bits, + Args... args) { + std::string template_def; + std::string fname = ((mode == "affine") ? "affine_" : "fp_") + func; + template_def = get_template_definition( + name, fname, type, group_size, bits, std::forward<Args>(args)...); + return get_qmm_nax_kernel( + d, name, template_def, mode, hash_name, func_consts); }   inline array @@ -927,6 +952,15 @@ return transpose && aligned_n && (mode == "affine") && (x.dtype() == float16 || x.dtype() == bfloat16) && (x.offset() % 8 == 0); }   +// Enable 4-way simdgroup K-split in staged NAX affine qmm/qmm_splitk when +// M <= 16. Suppressed whenever batch-invariant or prefill-row-invariant +// reduction order is required (with Layr-Labs/mlx#71, pass +// `allow_ksplit = (ref_rows <= 0)` from `qmm_splitk` -> `qmm` -> `qmm_nax` +// when `split_k <= 1`). +inline bool use_qmm_nax_ksplit(bool allow_ksplit = true) { + return allow_ksplit && env::nax_ksplit() && !env::qmv_batch_invariant(); +} + void qmm_nax( const array& x, const array& w, @@ -942,7 +976,8 @@ int N, int K, metal::Device& d, const Stream& s, - const std::string& mode) { + const std::string& mode, + bool allow_ksplit = true) { int B = out.size() / M / N;   int wm = 2; @@ -955,7 +990,8 @@ int bn = 64; int bk = 64;   bool aligned_n = (N % 64 == 0); - if (use_qmm_t_nax_staged(x, transpose, aligned_n, mode)) { + bool use_staged = use_qmm_t_nax_staged(x, transpose, aligned_n, mode); + if (use_staged) { wm = 4; wn = 1; bm = 64; @@ -991,22 +1027,47 @@ global_scale ? "_hgs" : ""); std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { - kernel = get_qmm_nax_kernel_wrapped( - d, - kname, - "qmm_t_nax", - mode, - type_string, - group_size, - bits, - aligned_n, - batched, - bm, - bk, - bn, - wm, - wn, - global_scale.has_value()); + if (use_staged) { + bool use_ksplit = use_qmm_nax_ksplit(allow_ksplit); + metal::MTLFCList func_consts = { + {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; + std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); + kernel = get_qmm_nax_kernel_wrapped_fc( + d, + kname, + hash_name, + func_consts, + "qmm_t_nax", + mode, + type_string, + group_size, + bits, + aligned_n, + batched, + bm, + bk, + bn, + wm, + wn, + global_scale.has_value()); + } else { + kernel = get_qmm_nax_kernel_wrapped( + d, + kname, + "qmm_t_nax", + mode, + type_string, + group_size, + bits, + aligned_n, + batched, + bm, + bk, + bn, + wm, + wn, + global_scale.has_value()); + } } else { kernel = get_qmm_nax_kernel_wrapped( d, @@ -1184,7 +1245,8 @@ int N, int K, metal::Device& d, const Stream& s, - const std::string& mode) { + const std::string& mode, + bool allow_ksplit = true) { assert( (!global_scale || (transpose && !biases)) && "qmm global scale requires transposed weights without biases"); @@ -1209,16 +1271,71 @@ /* int N = */ N, /* int K = */ K, /* metal::Device& d = */ d, /* const Stream& s = */ s, - /* const std::string& mode = */ mode); + /* const std::string& mode = */ mode, + /* bool allow_ksplit = */ allow_ksplit); }   int B = out.size() / M / N;   + // Prompt-sized products (256 rows or more) take a larger output tile than + // 32 x 32 on a GPU without neural accelerators (the NAX kernel above serves + // the rest): 64 rows x 32 columns for 16-bit inputs and 32 rows x 64 + // columns for FP32 by default (measured on the M3 Ultra, 512-row products of + // a 4-bit 27B: 64 x 32 is 4-6% faster than 32 x 32 for BF16; FP32's + // threadgroup tiles are twice as large, and its 64 x 64 tile is slower while + // 32 x 64 rereads the FP32 rows half as often). Every output element still + // accumulates the same 8-wide K slabs in the same order with the same + // simdgroup multiply-accumulates, from the same dequantized values, whatever + // the tile's rows, columns or K depth: no element's bits change, only which + // threadgroup computes it. MLX_QMM_STEEL_TILE (or the calling thread's + // mlx_metal_set_thread_qmm_steel_tile) picks another tile: 32 (32 x 32, as + // before), 64 (64 x 64), 6432 (64 rows x 32 columns), 3264, or 6464 (64 x 64, + // K depth 64 for 16-bit inputs in groups of 64 or more). + int requested = metal::thread_qmm_steel_tile(); + if (requested == 0) { + requested = env::qmm_steel_tile(); + int groups = + (N / 64) * ((M + 63) / 64) * std::max(1, int(out.size() / M / N)); + if (groups < env::qmm_steel_tile_min_groups()) { + requested = 32; + } else if (requested == 0) { + // Measured at prompt frames; fewer rows keep 32 x 32 (and their + // threadgroup count) unless a tile is chosen explicitly. + requested = M < 256 ? 32 : (x.itemsize() <= 2 ? 6432 : 3264); + } + } + int bm = 32, bn = 32, bk = 32; + // Only kernels compiled at run time take a tile other than 32 x 32: the + // precompiled library instantiates `affine_qmm_t` at 32 x 32 only, so a + // build without the JIT (CMake's default MLX_METAL_JIT=OFF) keeps it. + if (transpose && mode == "affine" && M >= 64 && N % 64 == 0 && + kernels_jit_compiled()) { + switch (requested) { + case 64: + bm = 64, bn = 64; + break; + case 6432: + bm = 64; + break; + case 3264: + bn = 64; + break; + case 6464: + // A K depth of 64 needs groups of 64 or more, and both padded + // tiles in 32 KiB of threadgroup memory: 16-bit inputs only (FP32 + // tiles would take 34 KiB), else 64 x 64 at a K depth of 32. + bm = 64, bn = 64; + if (group_size >= 64 && x.itemsize() <= 2) { + bk = 64; + } + break; + default: + break; + } + } + bool wide_tile = bm != 32 || bn != 32 || bk != 32; int wm = 2; int wn = 2; - int bm = 32; - int bk = 32; - int bn = 32;   // Tune for larger tile with Fp4HalfLoader. if (use_fp4_half_loader(x, mode, global_scale, bits) && transpose) { @@ -1251,8 +1368,11 @@ "_b_", bits, transpose ? (aligned ? "_alN_true" : "_alN_false") : "", batched ? "_batch_1" : "_batch_0", - (bm == 64 && bn == 64) ? "_bm_64_bn_64" : "", + (!wide_tile && bm == 64 && bn == 64) ? "_bm_64_bn_64" : "", global_scale ? "_hgs" : ""); + if (wide_tile) { + concatenate(kname, "_bm", bm, "_bk", bk, "_bn", bn); + } std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { @@ -1365,7 +1485,8 @@ int wm = 2; int wn = 2; MTL::Size group_dims(32, wn, wm);   - if (use_qmm_t_nax_staged(x, true, true, mode)) { + bool use_staged = use_qmm_t_nax_staged(x, true, true, mode); + if (use_staged) { bm = 64; wm = 4; wn = 1; @@ -1422,20 +1543,44 @@ wm, "_wn", wn, "_alN_true"); - auto kernel = get_qmm_nax_kernel_wrapped( - d, - kname, - "qmm_t_nax_splitk", - mode, - type_string, - group_size, - bits, - true, - bm, - bk, - bn, - wm, - wn); + MTL::ComputePipelineState* kernel; + if (use_staged) { + bool use_ksplit = use_qmm_nax_ksplit(); + metal::MTLFCList func_consts = { + {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; + std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); + kernel = get_qmm_nax_kernel_wrapped_fc( + d, + kname, + hash_name, + func_consts, + "qmm_t_nax_splitk", + mode, + type_string, + group_size, + bits, + true, + bm, + bk, + bn, + wm, + wn); + } else { + kernel = get_qmm_nax_kernel_wrapped( + d, + kname, + "qmm_t_nax_splitk", + mode, + type_string, + group_size, + bits, + true, + bm, + bk, + bn, + wm, + wn); + } compute_encoder.set_compute_pipeline_state(kernel);   int c = 0; @@ -1725,9 +1870,22 @@ std::string kname; kname.reserve(64); std::string type_string = get_type_string(x.dtype()); bool fast = N % bn == 0 && K % qmv_fast_k_alignment(bits) == 0; + bool fast_tail = false; + if (mode == "mxfp4" && group_size == 32 && bits == 4 && !global_scale && + w.ndim() == 3 && w.shape(0) == 32 && K == 2880 && + (N == 2880 || N == 5760) && + (x.dtype() == float32 || x.dtype() == bfloat16)) { + const char* option = std::getenv("MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL"); + const std::string_view physical_arch = + d.mtl_device()->architecture()->name()->utf8String(); + fast_tail = option ? std::string_view(option) == "1" + : physical_arch == "applegpu_g16s"; + } concatenate( kname, - mode + (fast ? "_gather_qmv_fast_" : "_gather_qmv_"), + mode + + (fast_tail ? "_gather_qmv_fast_tail_" + : (fast ? "_gather_qmv_fast_" : "_gather_qmv_")), type_string, "_gs_", group_size, @@ -1738,7 +1896,8 @@ auto kernel = get_quantized_kernel_wrapped( d, kname, - (fast ? "gather_qmv_fast" : "gather_qmv"), + (fast_tail ? "gather_qmv_fast_tail" + : (fast ? "gather_qmv_fast" : "gather_qmv")), mode, type_string, group_size, @@ -1982,7 +2141,118 @@ compute_encoder.dispatch_threadgroups(grid_dims, group_dims); }   -void gather_qmm_rhs( +Gemma4ExpertQMMRoute try_gemma4_expert_qmm( + const array& x, + const array& w, + const array& scales, + const array& biases, + const array& indices, + array& out, + int M, + int N, + int K, + metal::Device& d, + const Stream& s) { + // The classifier admits exactly E=128 (Gemma 4) and E=256 (Qwen 3.5/3.6 + // MoE); w is rank-3 [E, N_w, K_w] by the same gate. The tile kernel is + // expert-count agnostic — only the descriptor builder (one thread per + // expert) is instantiated per expert count. + const int expert_count = w.shape(0); + const char* descriptor_kernel_name = expert_count == 256 + ? "build_sorted_expert_tiles_bm32_e256" + : "build_gemma4_sorted_expert_tiles_bm32"; + constexpr const char* tile_kernel_name = + "affine_gather_qmm_gemma4_expert_tiles_bfloat16_t_gs_64_b_4_" + "alN_true_bm_32_bn_32_bk_32"; + + MTL::ComputePipelineState* descriptor_kernel = nullptr; + MTL::ComputePipelineState* tile_kernel = nullptr; + try { + descriptor_kernel = d.get_kernel(descriptor_kernel_name); + tile_kernel = d.get_kernel(tile_kernel_name); + } catch (...) { + return Gemma4ExpertQMMRoute::fallback_metallib_unavailable; + } + + constexpr int bm = 32; + constexpr int bn = 32; + constexpr int wm = 2; + constexpr int wn = 2; + // Upper bound on descriptors: sum over experts of ceil(rows_e / bm) with + // sum(rows_e) == M. With k experts carrying a nonzero remainder the total + // is at most (M - k) / bm + k <= M / bm + E - 1 for the reachable M/E. + const int max_tile_count = (M + bm - 1) / bm + expert_count - 1; + + array descriptors({max_tile_count, 4}, uint32, nullptr, {}); + descriptors.set_data(allocator::malloc(descriptors.nbytes())); + // count[0] is the descriptor count; count[1] is the builder's sortedness + // violation observability slot. + array tile_count({2}, uint32, nullptr, {}); + tile_count.set_data(allocator::malloc(tile_count.nbytes())); + + auto& compute_encoder = metal::get_command_encoder(s); + compute_encoder.add_temporary(descriptors); + compute_encoder.add_temporary(tile_count); + compute_encoder.set_compute_pipeline_state(descriptor_kernel); + compute_encoder.set_input_array(indices, 0); + compute_encoder.set_output_array(descriptors, 1); + compute_encoder.set_output_array(tile_count, 2); + compute_encoder.set_bytes(M, 3); + compute_encoder.dispatch_threads( + MTL::Size(expert_count, 1, 1), MTL::Size(expert_count, 1, 1)); + + // The descriptor builder fail-safes to count[0] == 0 when the purportedly + // sorted indices violate the non-decreasing invariant its binary search + // relies on. A zero count is unambiguous here: the selector's assignment + // gate guarantees M is one of 4096/8192/16384, so a valid build always + // emits at least one tile. Drain the stream and send retracted calls to + // the unsorted gather route rather than running the tile kernel. + // + // MLX_GATHER_QMM_EXPERT_SLICES=trust skips this drain entirely: the tile + // grid below is already over-dispatched (max_tile_count threadgroups; + // the kernel early-returns slots >= count[0]), so the readback exists + // ONLY to observe a retracted build. Under trust the caller asserts the + // sorted contract is machine-guaranteed (the Swift SwitchGLU prefill + // path sorts on-device just before this call); a genuine violation then + // yields undefined output for this matmul instead of the legacy result. + // Measured cost of the drain: ~120 stream drains per 512-token prefill + // chunk (3 gathers x 40 MoE layers) — it cancels the tile kernel's + // 12-23%/unit win end-to-end. A device-side legacy fallback (dispatch- + // diet item 1.3) would make trust the only behavior. + if (!d.gemma4_expert_qmm_trust_sorted()) { + compute_encoder.synchronize(); + const uint32_t* counts = tile_count.data<uint32_t>(); + if (counts[0] == 0) { + // count[1] flags a detected sortedness violation; attribute the + // retract to its own bucket. Any other unusable build keeps the + // metallib bucket. + return counts[1] == 1u + ? Gemma4ExpertQMMRoute::fallback_sortedness_retracted + : Gemma4ExpertQMMRoute::fallback_metallib_unavailable; + } + } + + compute_encoder.set_compute_pipeline_state(tile_kernel); + int c = 0; + compute_encoder.set_input_array(x, c++); + compute_encoder.set_input_array(w, c++); + compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(biases, c++); + compute_encoder.set_input_array(descriptors, c++); + compute_encoder.set_input_array(tile_count, c++); + compute_encoder.set_output_array(out, c++); + compute_encoder.set_bytes(K, c++); + compute_encoder.set_bytes(N, c++); + + compute_encoder.dispatch_threadgroups( + MTL::Size((N + bn - 1) / bn, max_tile_count, 1), MTL::Size(32, wn, wm)); + return Gemma4ExpertQMMRoute::hit; +} + +// Returns false when the indices are found to be unsorted. The row-tile +// kernels below read per-expert offsets and give a correct result only for +// sorted indices, so the caller must then use the unsorted gather route. +bool gather_qmm_rhs( const array& x_, const array& w_, const array& scales_, @@ -1999,9 +2269,18 @@ int K, metal::Device& d, const Stream& s, const std::string mode) { - if (metal::is_nax_available() && - (env::enable_tf32() || x_.dtype() != float32)) { - return gather_qmm_rhs_nax( + const bool nax_takes_call = metal::is_nax_available() && + (env::enable_tf32() || x_.dtype() != float32); + if (nax_takes_call) { + if (d.gemma4_expert_qmm_diagnostics_armed() && + d.gemma4_expert_qmm_requested()) { + Gemma4ExpertQMMRouteInput route_input; + route_input.requested = true; + route_input.outer_route = true; + route_input.nax_available = true; + d.record_armed_gemma4_expert_qmm(classify_gemma4_expert_qmm(route_input)); + } + gather_qmm_rhs_nax( /* const array& x_ = */ x_, /* const array& w_ = */ w_, /* const array& scales_ = */ scales_, @@ -2018,6 +2297,7 @@ /* int K = */ K, /* metal::Device& d = */ d, /* const Stream& s = */ s, /* const std::string mode = */ mode); + return true; }   // Start by normalizing the indices @@ -2053,11 +2333,102 @@ if (global_scale) { gs = ensure_row_contiguous(*global_scale, d, s); }   + if (d.gemma4_expert_qmm_requested()) { + auto shape_dim = [](const array& value, int axis) { + return value.ndim() > axis ? value.shape(axis) : 0; + }; + Gemma4ExpertQMMRouteInput route_input; + route_input.requested = true; + route_input.aot_available = d.gemma4_expert_qmm_aot_available(); + route_input.nax_available = false; + route_input.outer_route = true; + route_input.affine = mode == "affine"; + route_input.transpose = transpose; + route_input.has_bias = biases_.has_value(); + route_input.indices_uint32 = indices.dtype() == uint32; + route_input.indices_contiguous = indices.flags().row_contiguous; + route_input.x_bfloat16 = x.dtype() == bfloat16; + route_input.x_contiguous = x.flags().row_contiguous; + route_input.w_uint32 = w.dtype() == uint32; + route_input.w_contiguous = w.flags().row_contiguous; + route_input.scales_bfloat16 = scales.dtype() == bfloat16; + route_input.scales_contiguous = scales.flags().row_contiguous; + // Classification reads the raw bias tensor; normalization is spent only + // in the winning-route branch below. The legacy block at the end of this + // function retains its original normalization point and ordering. + route_input.biases_bfloat16 = biases_ && biases_->dtype() == bfloat16; + route_input.biases_contiguous = biases_ && biases_->flags().row_contiguous; + route_input.group_size = group_size; + route_input.bits = bits; + route_input.expert_count = w.size() / w.shape(-1) / w.shape(-2); + route_input.assignments = M; + route_input.index_count = indices.size(); + route_input.k = K; + route_input.n = N; + route_input.x_rank = x.ndim(); + route_input.x_dim0 = shape_dim(x, 0); + route_input.x_dim1 = shape_dim(x, 1); + route_input.x_dim2 = shape_dim(x, 2); + route_input.w_rank = w.ndim(); + route_input.w_dim0 = shape_dim(w, 0); + route_input.w_dim1 = shape_dim(w, 1); + route_input.w_dim2 = shape_dim(w, 2); + route_input.scales_rank = scales.ndim(); + route_input.scales_dim0 = shape_dim(scales, 0); + route_input.scales_dim1 = shape_dim(scales, 1); + route_input.scales_dim2 = shape_dim(scales, 2); + if (biases_) { + route_input.biases_rank = biases_->ndim(); + route_input.biases_dim0 = shape_dim(*biases_, 0); + route_input.biases_dim1 = shape_dim(*biases_, 1); + route_input.biases_dim2 = shape_dim(*biases_, 2); + } + + auto route = classify_gemma4_expert_qmm(route_input); + if (route == Gemma4ExpertQMMRoute::hit) { + // A hit requires has_bias, so dereferencing biases_ is safe. + array expert_biases = ensure_row_contiguous(*biases_, d, s); + route = try_gemma4_expert_qmm( + x, w, scales, expert_biases, indices, out, M, N, K, d, s); + if (route == Gemma4ExpertQMMRoute::hit) { + if (d.gemma4_expert_qmm_diagnostics_armed()) { + d.record_armed_gemma4_expert_qmm(route); + } + return true; + } + // A retracted build attributes to its own counter bucket + // (fallback_sortedness_retracted); missing AOT kernels keep the + // metallib bucket. + } + if (d.gemma4_expert_qmm_diagnostics_armed()) { + d.record_armed_gemma4_expert_qmm(route); + } + if (route == Gemma4ExpertQMMRoute::fallback_sortedness_retracted) { + return false; + } + } + + // Legacy gather path. Its normalization and dispatch order intentionally + // remain the global behavior for every non-exact call. + // TODO: Tune the block sizes int E = w.size() / w.shape(-1) / w.shape(-2); int bm = 16, bn = 32, bk = 32; int wm = 1, wn = 2;   + if (mode == "mxfp4" && transpose && group_size == 32 && bits == 4 && + w.ndim() == 3 && w.shape(0) == 32 && K == 2880 && + (N == 2880 || N == 5760) && M >= 64 && + (x.dtype() == float32 || x.dtype() == bfloat16)) { + const auto tile = metal::gptoss_mxfp4_prefill_tile( + std::getenv("MLX_GPTOSS_MXFP4_PREFILL_TILE")); + bm = tile.bm; + bn = tile.bn; + bk = tile.bk; + wm = tile.wm; + wn = tile.wn; + } + const bool align_N = (N % bn) == 0; const bool align_K = (K % bk) == 0;   @@ -2144,6 +2515,7 @@ compute_encoder.set_bytes(K, c++); compute_encoder.set_bytes(E, c++);   compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + return true; }   void dispatch_qmv( @@ -2215,16 +2587,22 @@ int vector_limit = transpose_ ? get_qmv_batch_limit(K, N, d) : 4; auto mode = quantization_mode_to_string(mode_);   + // With MLX_QMV_BATCH_INVARIANT=1, rows below the vector limit use only the + // vector kernels (dispatch_qmv), as before the qmv_mma and the mid-row NAX + // split-K routes. Then each row has the same bits at each row count from 2 + // to the limit - 1. + bool vector_rows = env::qmv_batch_invariant() && M < vector_limit; + // For few rows use qmv_mma when N/K is large enough. - if (transpose_ && non_batched && (M >= 6) && (M <= 16) && + if (!vector_rows && transpose_ && non_batched && (M >= 6) && (M <= 16) && use_qmv_mma(x, w, scales, mode_, M, N, K, d)) { qmv_mma(x, w, scales, out, group_size_, bits_, M, N, K, d, s, mode); return; }   // For mid rows use NAX qmm when output is large enough. - if (transpose_ && non_batched && (M >= 8) && (M < vector_limit) && - (M * N >= 16384) && + if (!vector_rows && transpose_ && non_batched && (M >= 8) && + (M < vector_limit) && (M * N >= 16384) && use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size_)) { qmm_splitk_nax( x, w, scales, biases, out, group_size_, bits_, M, N, K, d, s, mode); @@ -2303,6 +2681,15 @@ x, w, scales, biases, out, group_size_, bits_, M, N, K, d, s, mode); return; }   +// Single source for the sorted-RHS expert route gate. Both the diagnostics +// record below and the dispatch decision evaluate this one predicate so a +// future tuning change cannot desynchronize them. +// TODO: Tune 16 and 4 here a bit better. +static constexpr bool +takes_sorted_rhs_route(int M, int B, int E, bool right_sorted) { + return M == 1 && B >= 16 && right_sorted && B / E >= 4; +} + void GatherQMM::eval_gpu(const std::vector<array>& inputs, array& out) { auto& s = stream(); auto& d = metal::device(s.device); @@ -2331,28 +2718,36 @@ int E = w.size() / w.shape(-1) / w.shape(-2); int vector_limit = transpose_ ? get_qmv_batch_limit(K, N, d) : 4; auto mode = quantization_mode_to_string(mode_);   + if (d.gemma4_expert_qmm_diagnostics_armed() && + d.gemma4_expert_qmm_requested() && + !takes_sorted_rhs_route(M, B, E, right_sorted_)) { + Gemma4ExpertQMMRouteInput route_input; + route_input.requested = true; + route_input.outer_route = false; + d.record_armed_gemma4_expert_qmm(classify_gemma4_expert_qmm(route_input)); + } + // We are walking x in order and w is also in order so we can batch up the - // matmuls and reuse reading x and w. - // - // TODO: Tune 16 and 4 here a bit better. - if (M == 1 && B >= 16 && right_sorted_ == true && B / E >= 4) { - gather_qmm_rhs( - x, - w, - scales, - biases, - global_scale, - rhs_indices, - out, - transpose_, - group_size_, - bits_, - x.size() / K, - N, - K, - d, - s, - mode); + // matmuls and reuse reading x and w. When gather_qmm_rhs finds the indices + // unsorted, it returns false and the unsorted routes below run instead. + if (takes_sorted_rhs_route(M, B, E, right_sorted_) && + gather_qmm_rhs( + x, + w, + scales, + biases, + global_scale, + rhs_indices, + out, + transpose_, + group_size_, + bits_, + x.size() / K, + N, + K, + d, + s, + mode)) { return; }
diff --git ml-explore/mlx/tests/gpu_tests.cpp Layr-Labs/mlx/tests/gpu_tests.cpp index a49f9a704329db712a71dd752584ff89c8c0527a..9d577efd8a59123237321a3830bb5515f5a43dfd 100644 --- ml-explore/mlx/tests/gpu_tests.cpp +++ Layr-Labs/mlx/tests/gpu_tests.cpp @@ -6,6 +6,7 @@ #include <cmath> #include <future>   #include "doctest/doctest.h" +#include "mlx/backend/common/gemma4_expert_qmm.h" #include "mlx/mlx.h"   using namespace mlx::core; @@ -783,3 +784,396 @@ } } CHECK(worst <= 1e-5); } + +TEST_CASE("test Gemma 4 expert QMM pure route table") { + using metal::classify_gemma4_expert_qmm; + using metal::Gemma4ExpertQMMRoute; + using metal::Gemma4ExpertQMMRouteInput; + + auto gate_up = [](int assignments) { + Gemma4ExpertQMMRouteInput input; + input.requested = true; + input.aot_available = true; + input.outer_route = true; + input.affine = true; + input.transpose = true; + input.has_bias = true; + input.indices_uint32 = true; + input.indices_contiguous = true; + input.x_bfloat16 = true; + input.x_contiguous = true; + input.w_uint32 = true; + input.w_contiguous = true; + input.scales_bfloat16 = true; + input.scales_contiguous = true; + input.biases_bfloat16 = true; + input.biases_contiguous = true; + input.group_size = 64; + input.bits = 4; + input.expert_count = 128; + input.assignments = assignments; + input.index_count = assignments; + input.k = 2816; + input.n = 1408; + input.x_rank = 3; + input.x_dim0 = assignments; + input.x_dim1 = 1; + input.x_dim2 = 2816; + input.w_rank = 3; + input.w_dim0 = 128; + input.w_dim1 = 1408; + input.w_dim2 = 352; + input.scales_rank = 3; + input.scales_dim0 = 128; + input.scales_dim1 = 1408; + input.scales_dim2 = 44; + input.biases_rank = 3; + input.biases_dim0 = 128; + input.biases_dim1 = 1408; + input.biases_dim2 = 44; + return input; + }; + auto down = [&gate_up](int assignments) { + auto input = gate_up(assignments); + input.k = 704; + input.n = 2816; + input.x_dim2 = 704; + input.w_dim1 = 2816; + input.w_dim2 = 88; + input.scales_dim1 = 2816; + input.scales_dim2 = 11; + input.biases_dim1 = 2816; + input.biases_dim2 = 11; + return input; + }; + + for (int assignments : {4096, 8192, 16384}) { + CHECK( + classify_gemma4_expert_qmm(gate_up(assignments)) == + Gemma4ExpertQMMRoute::hit); + CHECK( + classify_gemma4_expert_qmm(down(assignments)) == + Gemma4ExpertQMMRoute::hit); + } + + auto exact = gate_up(4096); + auto check_miss = [&exact](auto mutate, Gemma4ExpertQMMRoute expected) { + auto input = exact; + mutate(input); + CHECK(classify_gemma4_expert_qmm(input) == expected); + }; + check_miss( + [](auto& x) { x.requested = false; }, + Gemma4ExpertQMMRoute::not_requested); + check_miss( + [](auto& x) { x.nax_available = true; }, + Gemma4ExpertQMMRoute::fallback_nax); + check_miss( + [](auto& x) { x.outer_route = false; }, + Gemma4ExpertQMMRoute::fallback_outer_route); + check_miss( + [](auto& x) { x.affine = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.transpose = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.has_bias = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.group_size = 32; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.bits = 8; }, Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.indices_uint32 = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.indices_contiguous = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.x_bfloat16 = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.x_contiguous = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.w_uint32 = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.w_contiguous = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.scales_bfloat16 = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.scales_contiguous = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.biases_bfloat16 = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.biases_contiguous = false; }, + Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.expert_count = 127; }, + Gemma4ExpertQMMRoute::fallback_topology); + check_miss( + [](auto& x) { x.x_rank = 4; }, Gemma4ExpertQMMRoute::fallback_topology); + check_miss( + [](auto& x) { x.w_rank = 2; }, Gemma4ExpertQMMRoute::fallback_topology); + check_miss( + [](auto& x) { x.scales_rank = 2; }, + Gemma4ExpertQMMRoute::fallback_topology); + check_miss( + [](auto& x) { x.biases_rank = 2; }, + Gemma4ExpertQMMRoute::fallback_topology); + check_miss( + [](auto& x) { x.index_count -= 1; }, + Gemma4ExpertQMMRoute::fallback_topology); + for (int assignments : {8, 16, 32, 4095, 4097}) { + check_miss( + [assignments](auto& x) { + x.assignments = assignments; + x.index_count = assignments; + x.x_dim0 = assignments; + }, + Gemma4ExpertQMMRoute::fallback_assignment_count); + } + check_miss( + [](auto& x) { x.w_dim2 = 176; }, Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { x.w_dim1 += 1; }, Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { + x.k += 32; + x.x_dim2 = x.k; + }, + Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { x.n -= 32; }, Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { x.aot_available = false; }, + Gemma4ExpertQMMRoute::fallback_metallib_unavailable); + + auto nax_without_aot = exact; + nax_without_aot.nax_available = true; + nax_without_aot.aot_available = false; + CHECK( + classify_gemma4_expert_qmm(nax_without_aot) == + Gemma4ExpertQMMRoute::fallback_nax); +} + +TEST_CASE("test Qwen 3.6 expert QMM pure route table") { + using metal::classify_gemma4_expert_qmm; + using metal::Gemma4ExpertQMMRoute; + using metal::Gemma4ExpertQMMRouteInput; + + // Base input: Qwen 3.5/3.6 35B-A3B expert projection at W4/g64, + // parametrized by whole-projection [E=256, n, k]. + auto qwen = [](int assignments, int k, int n) { + Gemma4ExpertQMMRouteInput input; + input.requested = true; + input.aot_available = true; + input.outer_route = true; + input.affine = true; + input.transpose = true; + input.has_bias = true; + input.indices_uint32 = true; + input.indices_contiguous = true; + input.x_bfloat16 = true; + input.x_contiguous = true; + input.w_uint32 = true; + input.w_contiguous = true; + input.scales_bfloat16 = true; + input.scales_contiguous = true; + input.biases_bfloat16 = true; + input.biases_contiguous = true; + input.group_size = 64; + input.bits = 4; + input.expert_count = 256; + input.assignments = assignments; + input.index_count = assignments; + input.k = k; + input.n = n; + input.x_rank = 3; + input.x_dim0 = assignments; + input.x_dim1 = 1; + input.x_dim2 = k; + input.w_rank = 3; + input.w_dim0 = 256; + input.w_dim1 = n; + input.w_dim2 = k / 8; + input.scales_rank = 3; + input.scales_dim0 = 256; + input.scales_dim1 = n; + input.scales_dim2 = k / 64; + input.biases_rank = 3; + input.biases_dim0 = 256; + input.biases_dim1 = n; + input.biases_dim2 = k / 64; + return input; + }; + + // Fused gate_up, split gate/up, and down projections hit at the chunked + // prefill assignment counts (T x top-8 for T in {512, 1024, 2048}). + for (int assignments : {4096, 8192, 16384}) { + CHECK( + classify_gemma4_expert_qmm(qwen(assignments, 2048, 1024)) == + Gemma4ExpertQMMRoute::hit); + CHECK( + classify_gemma4_expert_qmm(qwen(assignments, 2048, 512)) == + Gemma4ExpertQMMRoute::hit); + CHECK( + classify_gemma4_expert_qmm(qwen(assignments, 512, 2048)) == + Gemma4ExpertQMMRoute::hit); + } + + auto exact = qwen(4096, 2048, 1024); + auto check_miss = [&exact](auto mutate, Gemma4ExpertQMMRoute expected) { + auto input = exact; + mutate(input); + CHECK(classify_gemma4_expert_qmm(input) == expected); + }; + // Expert counts other than the two instantiated builders miss on topology. + check_miss( + [](auto& x) { + x.expert_count = 255; + x.w_dim0 = 255; + x.scales_dim0 = 255; + x.biases_dim0 = 255; + }, + Gemma4ExpertQMMRoute::fallback_topology); + // E=256 with Gemma geometry (and vice versa) must miss on geometry: the + // shape table is tied to the expert count, never mixed. + check_miss( + [](auto& x) { + x.k = 2816; + x.n = 1408; + x.x_dim2 = 2816; + x.w_dim1 = 1408; + x.w_dim2 = 352; + x.scales_dim1 = 1408; + x.scales_dim2 = 44; + x.biases_dim1 = 1408; + x.biases_dim2 = 44; + }, + Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { x.w_dim2 = 128; }, Gemma4ExpertQMMRoute::fallback_geometry); + check_miss( + [](auto& x) { x.n -= 32; }, Gemma4ExpertQMMRoute::fallback_geometry); + // T=128 chunks (1024 assignments) intentionally stay on the legacy path. + for (int assignments : {8, 1024, 4095, 4097}) { + check_miss( + [assignments](auto& x) { + x.assignments = assignments; + x.index_count = assignments; + x.x_dim0 = assignments; + }, + Gemma4ExpertQMMRoute::fallback_assignment_count); + } + check_miss( + [](auto& x) { x.bits = 8; }, Gemma4ExpertQMMRoute::fallback_quantization); + check_miss( + [](auto& x) { x.aot_available = false; }, + Gemma4ExpertQMMRoute::fallback_metallib_unavailable); + + // The Gemma table must also reject Qwen geometry under E=128. + auto gemma_with_qwen_geometry = exact; + gemma_with_qwen_geometry.expert_count = 128; + gemma_with_qwen_geometry.w_dim0 = 128; + gemma_with_qwen_geometry.scales_dim0 = 128; + gemma_with_qwen_geometry.biases_dim0 = 128; + CHECK( + classify_gemma4_expert_qmm(gemma_with_qwen_geometry) == + Gemma4ExpertQMMRoute::fallback_geometry); +} + +TEST_CASE("test Gemma 4 expert QMM counter invariant") { + metal::Gemma4ExpertQMMCounters counters; + using Route = metal::Gemma4ExpertQMMRoute; + counters.record(Route::not_requested); + counters.record(Route::hit); + counters.record(Route::fallback_nax); + counters.record(Route::fallback_outer_route); + counters.record(Route::fallback_quantization); + counters.record(Route::fallback_topology); + counters.record(Route::fallback_assignment_count); + counters.record(Route::fallback_geometry); + counters.record(Route::fallback_metallib_unavailable); + counters.record(Route::fallback_sortedness_retracted); + + auto snapshot = counters.snapshot(); + CHECK(snapshot.hits == 1); + CHECK(snapshot.fallback_nax == 1); + CHECK(snapshot.fallback_outer_route == 1); + CHECK(snapshot.fallback_quantization == 1); + CHECK(snapshot.fallback_topology == 1); + CHECK(snapshot.fallback_assignment_count == 1); + CHECK(snapshot.fallback_geometry == 1); + CHECK(snapshot.fallback_metallib_unavailable == 1); + CHECK(snapshot.fallback_sortedness_retracted == 1); + CHECK(snapshot.attempts() == 9); + + counters.reset(); + snapshot = counters.snapshot(); + CHECK(snapshot.attempts() == 0); + CHECK( + snapshot.attempts() == + snapshot.hits + snapshot.fallback_nax + snapshot.fallback_outer_route + + snapshot.fallback_quantization + snapshot.fallback_topology + + snapshot.fallback_assignment_count + snapshot.fallback_geometry + + snapshot.fallback_metallib_unavailable + + snapshot.fallback_sortedness_retracted); +} + +TEST_CASE("test Gemma 4 expert QMM arm disarm cycle") { + metal::Gemma4ExpertQMMCounters counters; + using Route = metal::Gemma4ExpertQMMRoute; + + // Counters start disarmed with an empty interval. + CHECK(!counters.armed()); + + // Arm: the interval opens with zeroed counters. + counters.clear_and_arm(); + CHECK(counters.armed()); + CHECK(counters.snapshot().attempts() == 0); + + // Record across the measured interval, including the retract class the + // sortedness fail-safe attributes mis-sorted indices to. + counters.record(Route::hit); + counters.record(Route::fallback_sortedness_retracted); + counters.record(Route::fallback_metallib_unavailable); + + // Disarm snapshots the interval and reports the previous armed state. + auto interval = counters.snapshot_and_disarm(); + CHECK(interval.armed); + CHECK(!counters.armed()); + + // The attempts == hits + sum(fallback classes) invariant holds across the + // cycle, with the sortedness-retract class included in the sum. + CHECK(interval.attempts() == 3); + CHECK(interval.hits == 1); + CHECK(interval.fallback_sortedness_retracted == 1); + CHECK(interval.fallback_metallib_unavailable == 1); + CHECK( + interval.attempts() == + interval.hits + interval.fallback_nax + interval.fallback_outer_route + + interval.fallback_quantization + interval.fallback_topology + + interval.fallback_assignment_count + interval.fallback_geometry + + interval.fallback_metallib_unavailable + + interval.fallback_sortedness_retracted); + + // The snapshot stays readable while disarmed. + CHECK(!counters.snapshot().armed); + CHECK(counters.snapshot().attempts() == 3); + + // Re-arming clears the interval again, and disarming it reports armed. + counters.clear_and_arm(); + CHECK(counters.armed()); + auto reopened = counters.snapshot_and_disarm(); + CHECK(reopened.armed); + CHECK(reopened.attempts() == 0); + CHECK(!counters.armed()); +} \ No newline at end of file

mlx_metal_set_thread_command_buffer_limits(max_ops, max_mb, ...) overrides, for the calling thread only, when its command buffers commit: after max_ops operations or max_mb megabytes of distinct inputs instead of the device defaults (zero keeps a default; the previous values are returned for restoring). Evaluation encodes on the thread that calls eval/async_eval, so a caller can give single-token decode steps larger buffers (the CPU encodes further ahead of the GPU) while prefill keeps the defaults and their memory bound. The Ultra defaults (50 ops / 50 MB) count weight inputs, so multi-GB expert banks commit after almost every MoE operation. Partitioning work into command buffers does not change results.

diff --git ml-explore/mlx/mlx/backend/common/command_buffer_limits.h Layr-Labs/mlx/mlx/backend/common/command_buffer_limits.h new file mode 100644 index 0000000000000000000000000000000000000000..e5ca795989f8a4cf320418c5d046311cc9268af9 --- /dev/null +++ Layr-Labs/mlx/mlx/backend/common/command_buffer_limits.h @@ -0,0 +1,39 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/api.h" + +#if defined(__APPLE__) +#ifdef __cplusplus +extern "C" { +#endif + +/// Commit limits for the Metal command buffers that the calling thread +/// encodes: a buffer is committed once it holds more than `max_ops` +/// operations or more than `max_mb` megabytes of distinct inputs. A value of +/// zero keeps the device default for that limit. Stores the thread's +/// previous values (zero for the default) in `previous_ops` and `previous_mb` +/// when they are not null. Partitioning work into command buffers does not +/// change results; larger buffers let the CPU encode further ahead of the +/// GPU and keep each buffer's temporaries alive until it completes. +MLX_API void mlx_metal_set_thread_command_buffer_limits( + int max_ops, + int max_mb, + int* previous_ops, + int* previous_mb); + +/// Output tile (32, 64, 6432, 3264 or 6464: rows x columns[, K depth]) of the +/// steel affine quantized matmul for the +/// products the calling thread encodes on a GPU without neural accelerators; +/// any other value restores MLX_QMM_STEEL_TILE. Stores the thread's previous +/// override (0 for none) in `previous_tile` when it is not null. The tile +/// changes which threadgroup computes an element, never its bits. Builds whose +/// kernels come only from the precompiled library (MLX_METAL_JIT=OFF) keep +/// 32 x 32 whatever the tile. +MLX_API void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile); + +#ifdef __cplusplus +} +#endif +#endif

On a GPU without neural accelerators the steel affine_qmm_t kernel computed every product in 32 x 32 output tiles (2 x 2 fragments a SIMD group). A product of at least 256 rows with a 64-aligned output width now takes a 64-row x 32-column tile for 16-bit inputs and a 32 x 64 tile for FP32 inputs by default (measured on the M3 Ultra at 512 rows: BF16 products 4-6% faster; FP32’s 64 x 64 tile was slower), JIT-instantiated from the same qmm_t_impl. Every output element still accumulates the same 8-wide K slabs in the same order with the same simdgroup multiply-accumulates over the same dequantized values, so no bit changes; the split-K decision (made from 32 x 32 tiles) and the NAX route are unchanged. MLX_QMM_STEEL_TILE picks 32 (as before), 64, 6432, 3264 or 6464 (64 x 64 with K depth 64 for 16-bit inputs in groups of 64 or more; FP32 tiles that deep would exceed 32 KiB of threadgroup memory); MLX_QMM_STEEL_TILE_MIN_GROUPS keeps 32 x 32 below a 64 x 64 threadgroup count; mlx_metal_set_thread_qmm_steel_tile overrides the tile for the calling thread (tests and benches compare the tiles’ bytes in one process). Both variables are documented in docs/src/usage/environment_variables.rst. Only builds that compile kernels at run time take these tiles: the precompiled library instantiates affine_qmm_t at 32 x 32 only, so CMake builds with the default MLX_METAL_JIT=OFF keep 32 x 32 (kernels_jit_compiled(), defined by jit_kernels.cpp and nojit_kernels.cpp). tests/quantized_tile_tests.cpp runs 512 x 1024 products (one qmm, no split-K) at K = 96 (no NAX route) and K = 192 in groups of 64 at every tile, checks the 32 x 32 result against the dequantized product, and every other tile against its bytes. A wide tile passes upstream’s template arguments in order (global scale, then BM, BK, BN); upstream’s own 64 x 64 FP4 tile (half-loader fp_qmm_t, precompiled) keeps its name and its selection.

diff --git ml-explore/mlx/docs/src/usage/environment_variables.rst Layr-Labs/mlx/docs/src/usage/environment_variables.rst index b43c053d528f474b3b4ad79e00bf57fe156fc3f5..b411152ab79122a894fc4d52e91baf92c4a77d84 100644 --- ml-explore/mlx/docs/src/usage/environment_variables.rst +++ Layr-Labs/mlx/docs/src/usage/environment_variables.rst @@ -63,6 +63,28 @@ Prefer a ring topology for JACCL. This variable is enabled by its presence. ``JACCL_RING`` is accepted as a higher-priority alias.   +.. envvar:: MLX_JACCL_PROGRESS_TIMEOUT_MS + + The longest time in milliseconds that a JACCL call waits for an RDMA + completion. The default is ``30000``. Set it to ``0`` or a negative value + to remove the limit. ``JACCL_PROGRESS_TIMEOUT_MS`` is accepted as a + higher-priority alias. When no completion arrives for this time, the call + fails and the group is closed: its queue pairs and completion queues are + destroyed and its buffers are deregistered. What follows is set by + :envvar:`MLX_JACCL_TIMEOUT_ACTION`. See the :ref:`JACCL section + <jaccl_section>`. + +.. envvar:: MLX_JACCL_TIMEOUT_ACTION + + What a JACCL call does after it failed (no completion within + :envvar:`MLX_JACCL_PROGRESS_TIMEOUT_MS`, a failed completion, or a failed + poll) and closed its group. ``teardown-exit``, the default, sets the wired + limit to zero, clears the buffer cache and exits the process with status 75 + without running static destructors. ``throw`` raises an error; each later + call on the group then raises an error immediately. Any other value keeps + the default. ``JACCL_TIMEOUT_ACTION`` is accepted as a higher-priority + alias. + .. envvar:: MLX_WORLD_SIZE   The total number of processes in an NCCL group. @@ -102,12 +124,50 @@ Enable the faster Metal CPU/GPU synchronization path. The default is ``0``. This requires Metal 3.2 or later (macOS 15 or later, or iOS 18 or later).   +.. envvar:: MLX_METAL_FUSED_FENCE_UPDATE + + With ``MLX_METAL_FAST_SYNCH=1``, make a GPU array visible to the CPU with + one dispatch instead of two: the coherent rewrite of the array and the + fence timestamp. The default is ``0``. + +.. envvar:: MLX_METAL_FENCED_INPUTS + + With ``MLX_METAL_FAST_SYNCH=1``, a custom kernel made with + ``metal_kernel_with_fenced_inputs`` waits itself for a fenced input that a + CPU stream makes in the same evaluation, and MLX does not encode a separate + fence wait for that input. The default is ``0``. + .. envvar:: MLX_CONV_WINOGRAD   Allow the Winograd algorithm for 3x3 ``conv2d``. The default is ``1``. Set it to ``0`` to use the GEMM convolution for all inputs. See :doc:`precision`.   +.. envvar:: MLX_QMV_BATCH_INVARIANT + + Set it to ``1`` to compute a quantized matrix product ``x @ w.T`` with + fewer rows than the vector limit only with the vector kernels: ``qmv`` for + one row and ``qmv_wide`` from two rows. Then each row gets the same bits at + each row count from 2 to the limit - 1, so the rows of different requests + can share one product. The default, ``0``, also uses faster kernels that + give a row different bits at some row counts: ``qmv_mma`` for 6 to 16 rows + of the floating-point modes, and the affine split-K kernel from 8 rows on + GPUs with neural accelerators. The vector limit is 6 to 33 rows; it + depends on the GPU and on the shape. A row alone (``qmv``) can get bits + that are different from the bits of the same row among two or more rows. + MLX reads this variable once in each process. + +.. envvar:: MLX_NAX_KSPLIT + + Enable K-split across all four simdgroups in the staged NAX affine + quantized matmul kernel (``qmm_t_nax_staged_ksplit_impl``) when + ``M <= 16`` (reachable at ``8 <= M <= 16`` on M5+ GPUs with neural + accelerators). The default is ``0`` (opt-in), because 4-way K-split + changes the FP32 K-reduction summation order relative to the unsplit + staged loop and to ``M > 16`` rows. Set it to ``1`` to opt in. Setting + ``MLX_QMV_BATCH_INVARIANT=1`` disables K-split even when ``MLX_NAX_KSPLIT=1`` + is set. MLX reads this variable once in each process. + Advanced tuning ---------------   @@ -143,6 +203,26 @@ Override the number of reduction blocks used by the Metal scaled dot-product attention kernel. Positive values are rounded up to a multiple of ``32``. + +.. envvar:: MLX_QMM_STEEL_TILE + + Output tile of the Metal steel affine quantized matmul (``x @ w.T`` with + at least 64 rows and a multiple of 64 outputs) where no neural-accelerator + kernel serves the product. The default, ``0``, takes 64 rows x 32 columns + for 16-bit inputs and 32 x 64 for FP32 inputs from 256 rows, and 32 x 32 + below. ``32`` (32 x 32, the previous tile), ``64`` (64 x 64), ``6432`` + (64 rows x 32 columns), ``3264`` (32 x 64) or ``6464`` (64 x 64 at a K + depth of 64 for 16-bit inputs in groups of 64 or more) choose one tile for + every product from 64 rows. Every tile gives the same bits; only the speed + changes. Only builds that compile kernels at run time (``MLX_METAL_JIT=ON``) + take a tile other than 32 x 32: the precompiled kernel library of the + default build holds the 32 x 32 kernels only, so there this variable has no + effect. + +.. envvar:: MLX_QMM_STEEL_TILE_MIN_GROUPS + + Fewest 64 x 64 threadgroups a product must fill to take a tile other than + 32 x 32; smaller products keep 32 x 32. The default is ``0``.   CUDA ----
diff --git ml-explore/mlx/mlx/backend/metal/jit_kernels.cpp Layr-Labs/mlx/mlx/backend/metal/jit_kernels.cpp index aad94eba1e1752c58b94de4c744b7c4f865888e9..5a1d565579459a28750539bed6029685c916a581 100644 --- ml-explore/mlx/mlx/backend/metal/jit_kernels.cpp +++ Layr-Labs/mlx/mlx/backend/metal/jit_kernels.cpp @@ -1069,6 +1069,10 @@ }); return d.get_kernel(kernel_name, lib); }   +bool kernels_jit_compiled() { + return true; +} + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, @@ -1289,7 +1293,9 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string& template_def, - const std::string& mode) { + const std::string& mode, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { std::string kernel_source; @@ -1302,7 +1308,14 @@ (mode == "affine") ? metal::quantized_nax() : metal::fp_quantized_nax(), template_def); return kernel_source; }); - return d.get_kernel(kernel_name, lib); + if (func_consts.empty()) { + return d.get_kernel(kernel_name, lib); + } + return d.get_kernel( + kernel_name, + lib, + hash_name.empty() ? kernel_name : hash_name, + func_consts); }   MTL::ComputePipelineState* get_gather_qmm_nax_kernel( @@ -1417,22 +1430,37 @@ const array& m, bool split_d) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { + // attention_nax_dsplit has no BV parameter (its value head dim is BD), so + // it takes the same arguments as its instantiation in + // steel_attention_nax.metal. Passing bv shifts every later argument and + // the library fails to compile. + auto template_def = split_d ? get_template_definition( + lib_name, + "attention_nax_dsplit", + get_type_string(q.dtype()), + bq, + bk, + bd, + wm, + wn, + get_type_string(m.dtype())) + : get_template_definition( + lib_name, + "attention_nax", + get_type_string(q.dtype()), + bq, + bk, + bd, + bv, + wm, + wn, + get_type_string(m.dtype())); std::string kernel_source; concatenate( kernel_source, metal::utils(), metal::steel_attention_nax(), - get_template_definition( - lib_name, - split_d ? "attention_nax_dsplit" : "attention_nax", - get_type_string(q.dtype()), - bq, - bk, - bd, - bv, - wm, - wn, - get_type_string(m.dtype()))); + template_def); return kernel_source; }); return d.get_kernel(kernel_name, lib, hash_name, func_consts);
diff --git ml-explore/mlx/mlx/backend/metal/kernels.h Layr-Labs/mlx/mlx/backend/metal/kernels.h index ded6c834abceca4e2cec94ca1b9c5efeaf594e36..b2bb739ae6ac9835f2afd1a55d27962939932b5c 100644 --- ml-explore/mlx/mlx/backend/metal/kernels.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels.h @@ -312,6 +312,12 @@ const std::string& kernel_name, const std::string& template_def, const std::string& mode);   +// Whether this build compiles kernels at run time (jit_kernels.cpp), so a +// kernel can take any template instantiation, rather than loading them only +// from the precompiled library (nojit_kernels.cpp), which holds just the +// instantiations its .metal sources list. +bool kernels_jit_compiled(); + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, @@ -397,7 +403,9 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string& template_def, - const std::string& mode); + const std::string& mode, + const std::string& hash_name = "", + const metal::MTLFCList& func_consts = {});   MTL::ComputePipelineState* get_gather_qmm_nax_kernel( metal::Device& d,
diff --git ml-explore/mlx/mlx/backend/metal/nojit_kernels.cpp Layr-Labs/mlx/mlx/backend/metal/nojit_kernels.cpp index 93f8cf311fceef7a206ad65cbf18580fbce1db42..7df7785baa3c969d3ac33ec143db62dd561917da 100644 --- ml-explore/mlx/mlx/backend/metal/nojit_kernels.cpp +++ Layr-Labs/mlx/mlx/backend/metal/nojit_kernels.cpp @@ -375,6 +375,10 @@ const std::string&) { return d.get_kernel(kernel_name); }   +bool kernels_jit_compiled() { + return false; +} + MTL::ComputePipelineState* get_gather_qmm_kernel( metal::Device& d, const std::string& kernel_name, @@ -472,8 +476,14 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string&, - const std::string&) { - return d.get_kernel(kernel_name); + const std::string&, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + if (func_consts.empty()) { + return d.get_kernel(kernel_name); + } + return d.get_kernel( + kernel_name, hash_name.empty() ? kernel_name : hash_name, func_consts); }   MTL::ComputePipelineState* get_gather_qmm_nax_kernel(
diff --git ml-explore/mlx/mlx/utils.h Layr-Labs/mlx/mlx/utils.h index 4b7e6d12d91bb2a5ede43959c6c16f3da6453795..1ef39d7b8ebe4c3a077ecd5e7466532fac16b2dc 100644 --- ml-explore/mlx/mlx/utils.h +++ Layr-Labs/mlx/mlx/utils.h @@ -217,9 +217,55 @@ static bool residency_debug_ = get_var("MLX_RESIDENCY_DEBUG", 0); return residency_debug_; }   +// Output tile of the steel affine quantized matmul on GPUs without neural +// accelerators (see `qmm` in backend/metal/quantized.cpp): 32, 64, 6432, +// 3264 or 6464, or 0 (default) for the input width's own tile. Builds whose +// kernels come only from the precompiled library keep 32 x 32. +inline int qmm_steel_tile() { + static int tile_ = get_var("MLX_QMM_STEEL_TILE", 0); + return tile_; +} + +// Fewest 64 x 64 threadgroups a product must fill to take a tile other than +// 32 x 32 (fewer keep 32 x 32 and their GPU occupancy). +inline int qmm_steel_tile_min_groups() { + static int groups_ = get_var("MLX_QMM_STEEL_TILE_MIN_GROUPS", 0); + return groups_; +} + +// Quantized matmuls (x @ w.T) with fewer rows than the vector limit use only +// the vector kernels (see `QuantizedMatmul::eval_gpu` in +// backend/metal/quantized.cpp). Then a row has the same bits at each row count +// from 2 to the limit - 1. +inline bool qmv_batch_invariant() { + static bool invariant_ = get_var("MLX_QMV_BATCH_INVARIANT", 0); + return invariant_; +} + +// Enable K-split across simdgroups in staged NAX affine qmm when M <= 16. +// Opt-in (default 0) because 4-way K-split changes FP32 K-reduction summation +// order at 8 <= M <= 16; disabled automatically when MLX_QMV_BATCH_INVARIANT=1 +// is set. +inline bool nax_ksplit() { + static bool enabled_ = get_var("MLX_NAX_KSPLIT", 0) != 0; + return enabled_; +} + inline bool metal_fast_synch() { static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0); return metal_fast_synch; +} + +// A cross-device fast fence update in one dispatch (fence_update_coherent). +inline bool metal_fused_fence_update() { + static bool fused = get_var("MLX_METAL_FUSED_FENCE_UPDATE", 0); + return fused; +} + +// Custom kernels wait for their fenced inputs from a CPU stream themselves. +inline bool metal_fenced_inputs() { + static bool fenced = get_var("MLX_METAL_FENCED_INPUTS", 0); + return fenced; }   inline bool enable_tf32() {
diff --git ml-explore/mlx/tests/quantized_tile_tests.cpp Layr-Labs/mlx/tests/quantized_tile_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d1374821f7710644f8484175859421c7f3c1df1 --- /dev/null +++ Layr-Labs/mlx/tests/quantized_tile_tests.cpp @@ -0,0 +1,112 @@ +// Copyright © 2026 Eigen Labs. +#include <cmath> + +#include "doctest/doctest.h" +#include "mlx/backend/common/command_buffer_limits.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { +// The calling thread's steel quantized-matmul tile for the scope; 0 is the +// default policy. +struct ScopedSteelTile { + int previous = 0; + explicit ScopedSteelTile(int tile) { + mlx_metal_set_thread_qmm_steel_tile(tile, &previous); + } + ~ScopedSteelTile() { + mlx_metal_set_thread_qmm_steel_tile(previous, nullptr); + } +}; +} // namespace + +TEST_CASE("prompt-sized affine qmm in every kernel build") { + // 512 rows and 1024 outputs take a tile wider than 32 x 32 by default where + // kernels are compiled at run time. A build whose kernels come only from the + // precompiled library must keep 32 x 32 rather than ask that library for a + // tile it never instantiated. The product fills 512 threadgroups at 32 x 32, + // so it runs as one qmm rather than split along K. K = 96 keeps the steel + // kernel on GPUs with neural accelerators too (theirs needs K % 64 == 0); + // K = 192 in groups of 64 adds the 64-deep tile where none serves it. + constexpr int M = 512, N = 1024, bits = 4; + for (auto [K, group_size] : {std::pair{96, 32}, std::pair{192, 64}}) { + auto x = reshape( + divide( + sin(arange(M * K, float32, Device::gpu) * array(0.007f), + Device::gpu), + array(std::sqrt(float(K))), + Device::gpu), + {M, K}); + auto w = reshape( + divide( + cos(arange(N * K, float32, Device::gpu) * array(0.013f), + Device::gpu), + array(std::sqrt(float(K))), + Device::gpu), + {N, K}); + for (auto dtype : {float16, bfloat16, float32}) { + CAPTURE(K); + CAPTURE(dtype); + auto xt = astype(x, dtype, Device::gpu); + auto q = quantize( + astype(w, dtype, Device::gpu), + group_size, + bits, + "affine", + std::nullopt, + Device::gpu); + auto product = [&]() { + auto out = quantized_matmul( + xt, + q[0], + q[1], + q[2], + true, + group_size, + bits, + "affine", + Device::gpu); + eval(out); + return out; + }; + array reference(0.0f); + { + ScopedSteelTile tile(32); + reference = product(); + } + auto w_hat = astype( + dequantize( + q[0], + q[1], + q[2], + group_size, + bits, + "affine", + {}, + {}, + Device::cpu), + float32, + Device::cpu); + auto expected = matmul( + astype(xt, float32, Device::cpu), + transpose(w_hat, Device::cpu), + Device::cpu); + CHECK(allclose( + astype(reference, float32, Device::cpu), + expected, + 1e-2, + 1e-2, + false, + Device::cpu) + .item<bool>()); + // Every tile computes each element from the same K slabs in the same + // order, so each gives the 32 x 32 bytes. + for (int t : {0, 64, 6432, 3264, 6464}) { + CAPTURE(t); + ScopedSteelTile tile(t); + CHECK(array_equal(product(), reference, Device::cpu).item<bool>()); + } + } + } +}

Opt-in (MLX_QMV_BATCH_INVARIANT=1, read once in each process). A quantized x @ w.T with fewer rows than the vector limit (get_qmv_batch_limit) then runs only the vector kernels, as upstream did before two of its routes: qmv for one row, and qmv_wide from two rows (qmv where qmv_wide does not serve the mode on the GPU). These routes do not run below the limit: qmv_mma/qmv_nax for 6 to 16 rows of the floating-point modes (ml-explore/mlx#4712) and the staged NAX split-K kernel for affine products from 8 rows (ml-explore/mlx#4682). Each row then has the same bits at each row count from 2 to the limit - 1, so the rows of several requests in one launch (for example their speculative verify windows) get the bits that each request gets alone. A row alone (qmv) can have other bits than the same row among two or more rows, as before. From the limit on, and without the switch, the routes do not change. tests/qmv_batch_invariant_tests.cpp compares each window of rows with the same rows in a larger launch at GLM and Qwen tensor-parallel shapes, for affine and NVFP4 weights with bfloat16 and float32 inputs. The tests binary runs it without the switch (up to 5 rows), and the qmv_batch_invariant ctest entry, which Fork Tests runs, runs it with the switch (every count below the limit).

diff --git ml-explore/mlx/.github/workflows/fork-tests.yml Layr-Labs/mlx/.github/workflows/fork-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..9850902cc33e90ff35df03f9f0c1d26aad2e1473 --- /dev/null +++ Layr-Labs/mlx/.github/workflows/fork-tests.yml @@ -0,0 +1,645 @@ +name: Fork Tests + +# Build the fork with Metal and run its C++ and Python tests on macOS +# runners. The steps use the actions in .github/actions. +# +# The jobs: +# build-wheel builds the Python wheel and uploads it. +# build-cpp builds the C++ library and tests, and runs the C++ tests +# with the GPU and then with the CPU as the default device, +# and the JACCL tests with simulated verbs (tests/jaccl). +# Then it runs the standalone allocation cap tests, one +# process for each case, and the bounded Metal fence chains. +# python-gpu runs the Python tests with the GPU as the default device. +# python-cpu runs the Python tests with the CPU as the default device. +# metal-build-and-test +# merges the coverage profiles of all jobs, writes the +# coverage report, and fails if one of the other jobs failed. +# The two build jobs run in parallel. The Python test jobs start when the +# wheel is ready. Each Python test job runs one shard of +# .github/scripts/fork-tests/python-shards.json, and +# .github/scripts/fork-tests/python_shards.py fails a job if a test file is +# in no shard or in two shards. +# +# A run uses 8 Darkbloom macOS jobs. They wait for compatible capacity and +# have no hosted fallback. A new push to a pull request cancels the older +# run and frees its runners. FORKDIFF.md describes the queue time bounds. + +on: + pull_request: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Cancel an older run of the same pull request. Let runs on main finish. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # Instrument the C and C++ code for line coverage. cmake reads these + # variables in the build jobs and in the extension examples. The Metal + # shaders are not instrumented. + CFLAGS: -fprofile-instr-generate -fcoverage-mapping + CXXFLAGS: -fprofile-instr-generate -fcoverage-mapping + +jobs: + build-wheel: + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] + timeout-minutes: 45 + env: + # The runners have macOS 26 or later. Version 26.2 is the lowest + # target that builds all Metal kernels. + MACOSX_DEPLOYMENT_TARGET: '26.2' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + + - name: Check the Python shard map + run: python3 .github/scripts/fork-tests/python_shards.py check + + - uses: ./.github/actions/fork-build-cache + id: cache + with: + phase: restore + kind: wheel + + - name: Build the wheel + env: + DEBUG: 1 + CMAKE_ARGS: ${{ steps.cache.outputs.cmake-args }} + run: | + uv pip install build setuptools + export PATH="$GITHUB_WORKSPACE/.github/scripts/fork-tests/metal-cache:$PATH" + python -m build -w + + - uses: ./.github/actions/fork-build-cache + with: + phase: save + kind: wheel + ccache-save-key: ${{ steps.cache.outputs.ccache-save-key }} + metal-save-key: ${{ steps.cache.outputs.metal-save-key }} + + - name: Upload the wheel + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: fork-tests-wheel + path: dist/*.whl + if-no-files-found: error + # A wheel is a zip file already. + compression-level: 0 + retention-days: 3 + overwrite: true + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + + build-cpp: + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] + timeout-minutes: 45 + env: + MACOSX_DEPLOYMENT_TARGET: '26.2' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + + - uses: ./.github/actions/fork-build-cache + id: cache + with: + phase: restore + kind: cpp + + - name: Build the C++ library and tests + id: build + env: + CMAKE_ARGS: ${{ steps.cache.outputs.cmake-args }} + run: | + export PATH="$GITHUB_WORKSPACE/.github/scripts/fork-tests/metal-cache:$PATH" + # The same commands as the "Build CPP only" step of + # .github/actions/build-macos. + cmake . -B build $CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug + cmake --build build -j $(sysctl -n hw.physicalcpu) + + - uses: ./.github/actions/fork-build-cache + with: + phase: save + kind: cpp + ccache-save-key: ${{ steps.cache.outputs.ccache-save-key }} + metal-save-key: ${{ steps.cache.outputs.metal-save-key }} + + - name: Run the C++ tests on the GPU + env: + METAL_DEBUG_ERROR_MODE: 0 + METAL_DEVICE_WRAPPER_TYPE: 1 + # Each test process writes one profile for each instrumented binary. + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + run: ./build/tests/tests + + - name: Run the C++ tests on the CPU + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + DEVICE: cpu + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/cpu-%p-%m.profraw + run: ./build/tests/tests + + - name: Run the JACCL tests with simulated verbs + # tests/jaccl is its own CMake project, which the build above does + # not build: the real mesh, ring and RDMA headers against fake verbs, + # with ASan and UBSan. The step clears the coverage flags. + if: ${{ !cancelled() }} + env: + CFLAGS: '' + CXXFLAGS: '' + run: | + cmake -S tests/jaccl -B build-jaccl -DCMAKE_BUILD_TYPE=Debug + cmake --build build-jaccl -j $(sysctl -n hw.physicalcpu) + ctest --test-dir build-jaccl --output-on-failure --no-tests=error + + - name: Run the standalone allocation cap tests + # The process allocation cap is install-once in each process. ctest + # runs each entry in a fresh process, and the Metal test runs one case + # in each entry (tests/CMakeLists.txt). The build step built them. + # -V prints the output of every case, so the log shows why a case + # was skipped (a few lines for each case). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/cap-%p-%m.profraw + run: | + ctest --test-dir build -R '^process_allocation_cap' -V \ + --no-tests=error + + - name: Run the bounded Metal fence chains + # metal_fence_chain runs exact GPU -> CPU -> GPU chains with fast + # synchronization at three command buffer sizes, one ctest entry for + # each, each with a 60 s timeout (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/fence-%p-%m.profraw + run: | + ctest --test-dir build -R '^metal_fence_chain_' --output-on-failure \ + --no-tests=error + + - name: Run the quantized matmul rows with MLX_QMV_BATCH_INVARIANT=1 + # MLX reads the switch once in each process. The C++ test steps above + # run the case with the switch off; this ctest entry runs it again + # with the switch on (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/qmv-%p-%m.profraw + run: | + ctest --test-dir build -R '^qmv_batch_invariant$' \ + --output-on-failure --no-tests=error + + - name: Run the NAX quantized kernel tests with MLX_NAX_KSPLIT=1 + # MLX reads the switch once in each process. The C++ test steps above + # run the case with the default (MLX_NAX_KSPLIT=0); this ctest entry + # runs it again with K-split enabled (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/nax-ksplit-%p-%m.profraw + run: | + ctest --test-dir build -R '^nax_ksplit_enabled$' \ + --output-on-failure --no-tests=error + + - name: Merge the coverage profiles + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/cpp.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: profdata-cpp + path: ${{ runner.temp }}/profdata/cpp.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Upload the C++ test binary + # The coverage report reads the coverage mapping in this binary. + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: fork-tests-cpp-binary + path: build/tests/tests + if-no-files-found: error + compression-level: 1 + retention-days: 3 + overwrite: true + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + + python-gpu: + needs: build-wheel + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x24] + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # One job for each "gpu" shard in python-shards.json. The script + # fails if the two counts are not equal. + shard: [0, 1] + env: + METAL_DEBUG_ERROR_MODE: 0 + METAL_DEVICE_WRAPPER_TYPE: 1 + # The job-level env cannot read the runner context, so the steps set + # LLVM_PROFILE_FILE. + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + + - uses: ./.github/actions/setup + with: + toolkit: metal + use-ccache: 'false' + # Shard 0 runs the distributed test. It gets the same Homebrew + # packages (openmpi) as the build jobs. + install-macos-deps: ${{ matrix.shard == 0 }} + + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-wheel + path: dist + + - name: Install the wheel and the test dependencies + run: | + uv pip install build setuptools tensorflow + uv pip install dist/*.whl + + - name: Run the Python tests + id: tests + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + run: | + python .github/scripts/fork-tests/python_shards.py run gpu \ + ${{ matrix.shard }} ${{ strategy.job-total }} \ + --jobs 1 --logs "$RUNNER_TEMP/logs" + + - name: Run the distributed tests + if: ${{ !cancelled() && matrix.shard == 0 }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + # The same commands as the "Run distributed tests" group of + # .github/actions/test-macos for the metal toolkit. + run: | + # TODO: Re-enable for GPU after openmpi updating their libprrte + # dependency: https://github.com/openpmix/prrte/issues/2416 + mlx.launch --verbose -n 8 uv run python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2) + if $(grep "\[WARN\]" stderr.log); then + echo "Distributed ring test failed" + exit 1 + fi + + - name: Build and test the extension examples + if: ${{ !cancelled() && matrix.shard == 0 }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + # The same commands as the extension groups of + # .github/actions/test-macos for the metal toolkit. + run: | + echo "::group::Build example extension" + pushd examples/cmake_extension + uv pip install -r requirements.txt + uv run setup.py build_ext --inplace + uv run test.py + popd + echo "::endgroup::" + + echo "::group::Build Metal extension example" + pushd examples/metal_extension + uv pip install -r requirements.txt + uv run setup.py build_ext --inplace + uv run test.py + popd + echo "::endgroup::" + + - name: Merge the coverage profiles + if: ${{ !cancelled() }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/gpu-${{ matrix.shard }}.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: profdata-gpu-${{ matrix.shard }} + path: ${{ runner.temp }}/profdata/gpu-${{ matrix.shard }}.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Upload the list of tests that ran + if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: testids-gpu-${{ matrix.shard }} + path: ${{ runner.temp }}/logs/testids-gpu-${{ matrix.shard }}.json + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + + python-cpu: + # Run the CPU code of ops that also have a Metal implementation. + needs: build-wheel + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-12x32] + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # One job for each "cpu" shard in python-shards.json. + shard: [0, 1, 2] + env: + DEVICE: cpu + # Tests that take more than 5 minutes on the CPU. The GPU pass + # still runs them. + # test_sdpa_long_masked_sequence: 21 min 36 s on the CPU. + # test_sdpa_full_head_dim_256: 6 min 46 s on the CPU. + CPU_EXCLUDE: >- + test_fast_sdpa.TestFastSDPA.test_sdpa_long_masked_sequence + test_fast_sdpa.TestFastSDPA.test_sdpa_full_head_dim_256 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + + - uses: ./.github/actions/setup + with: + toolkit: metal + use-ccache: 'false' + install-macos-deps: 'false' + + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-wheel + path: dist + + - name: Install the wheel and the test dependencies + run: | + uv pip install build setuptools tensorflow + uv pip install dist/*.whl + + - name: Run the Python tests on the CPU + id: tests + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/cpu-%p-%m.profraw + # Each entry runs in a child process that writes its own log, so a + # crash stops only that entry. Three entries run at a time. + run: | + python .github/scripts/fork-tests/python_shards.py run cpu \ + ${{ matrix.shard }} ${{ strategy.job-total }} \ + --jobs 3 --logs "$RUNNER_TEMP/logs" + + - name: Merge the coverage profiles + if: ${{ !cancelled() }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/cpu-${{ matrix.shard }}.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: profdata-cpu-${{ matrix.shard }} + path: ${{ runner.temp }}/profdata/cpu-${{ matrix.shard }}.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Upload the list of tests that ran + if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: testids-cpu-${{ matrix.shard }} + path: ${{ runner.temp }}/logs/testids-cpu-${{ matrix.shard }}.json + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + + metal-build-and-test: + needs: [build-wheel, build-cpp, python-gpu, python-cpu] + if: ${{ !cancelled() }} + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + + - name: Download the lists of tests that ran + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: testids-* + path: ${{ runner.temp }}/testids + merge-multiple: true + + - name: Check that each Python test ran in one shard only + run: python3 .github/scripts/fork-tests/python_shards.py verify "$RUNNER_TEMP/testids" + + - name: Download the coverage profiles + id: profiles + if: ${{ !cancelled() && needs.build-wheel.result == 'success' && needs.build-cpp.result == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: profdata-* + path: ${{ runner.temp }}/profdata + merge-multiple: true + + - name: Download the wheel + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-wheel + path: ${{ runner.temp }}/wheel + + - name: Download the C++ test binary + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-cpp-binary + path: build/tests + + - name: Report C++ line coverage + id: coverage + # Report also after a test failure, so that a red run shows the + # coverage of the tests that ran. + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} + env: + CPP_RESULT: ${{ needs.build-cpp.result }} + GPU_RESULT: ${{ needs.python-gpu.result }} + CPU_RESULT: ${{ needs.python-cpu.result }} + run: | + shopt -s nullglob + out="$RUNNER_TEMP/coverage" + mkdir -p "$out" + # Each test job merged its raw profiles into one .profdata file. + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profdata/*.profdata \ + -o "$out/coverage.profdata" + # The Python tests run the code in the installed wheel: the + # extension module and the libraries in mlx/lib. The test jobs + # installed this same wheel. + unzip -q "$RUNNER_TEMP"/wheel/*.whl -d "$RUNNER_TEMP/wheel-files" + core=$(echo "$RUNNER_TEMP"/wheel-files/mlx/core.*.so) + objects=(./build/tests/tests -object "$core") + for lib in "$(dirname "$core")"/lib/*.dylib; do + objects+=(-object "$lib") + done + # Drop the tests, the dependencies, the Python headers, the + # generated files in the build folders, the vendored pocketfft + # header and the CUDA backend. The Metal shader source + # needs no pattern: the host compiler never builds it, so it has no + # coverage records. The few headers in mlx/backend/metal/kernels/ + # that host C++ includes, such as steel/conv/params.h, stay counted. + options=( + -instr-profile="$out/coverage.profdata" + -ignore-filename-regex='/build/|/tests/|/\.venv/|/site-packages/|/uv-python-dir/|/mlx/3rdparty/|/mlx/backend/cuda/' + ) + # report FILE DIR... writes the llvm-cov report for the files under + # each DIR. llvm-cov ignores a path that does not exist and then + # reports every file, so the function checks each path first. + report() { + local file=$1 dir paths=() + shift + for dir in "$@"; do + if [ ! -d "$GITHUB_WORKSPACE/$dir" ]; then + echo "::error::The directory $dir does not exist." + return 1 + fi + paths+=("$GITHUB_WORKSPACE/$dir") + done + xcrun llvm-cov report "${objects[@]}" "${options[@]}" \ + "${paths[@]}" > "$file" + } + # value_of FILE NAME prints the value of the column NAME in the + # TOTAL row, for example "Lines" (a count) or "Lines Cover" (a + # percentage). It finds the column by its name in the header row, + # and it fails when the value is missing. It also rejects the "-" + # that llvm-cov prints for a Cover column with no counters, so a + # future row without branches fails the step. + value_of() { + awk -v want="$2" ' + NR == 1 { + field = 1 + for (i = 2; i <= NF; i++) { + if ($i == "Missed") { missed = 1; continue } + field++ + if (missed) { missed = 0; continue } + if ($i == "Cover" || $i == "Executed") { + if (group " Cover" == want) col = field + continue + } + group = $i + if (group == want) col = field + } + } + $1 == "TOTAL" && col { value = $col } + END { + if (want ~ / Cover$/ && value !~ /^[0-9.]+%$/) exit 1 + if (want !~ / Cover$/ && value !~ /^[0-9]+$/) exit 1 + print value + } + ' "$1" || { echo "::error::$1 has no $2 value in the TOTAL row." >&2; return 1; } + } + # row NAME FILE DIR... adds one table row. + row() { + report "${@:2}" + grep '^TOTAL' "$2" + lines=$(value_of "$2" "Lines Cover") + branches=$(value_of "$2" "Branches Cover") + functions=$(value_of "$2" "Functions Cover") + echo "| $1 | $lines | $branches | $functions | 80% |" >> "$out/rows.md" + } + : > "$out/rows.md" + row "Total" "$out/report.txt" mlx python/src + row "All of \`mlx/\`" "$out/report-mlx.txt" mlx + for dir in backend/metal backend/cpu backend/common distributed io; do + row "\`mlx/$dir\`" "$out/report-${dir//\//-}.txt" "mlx/$dir" + done + row "\`python/src\`" "$out/report-python-src.txt" python/src + lines_total=$(value_of "$out/report.txt" Lines) + { + echo "### C++ line coverage" + echo + echo "C++ build and C++ tests (GPU and CPU default device): $CPP_RESULT" + echo + echo "Python tests (GPU default device): $GPU_RESULT" + echo + echo "Python tests (CPU default device): $CPU_RESULT" + echo + echo "| Component | Lines | Branches | Functions | Target |" + echo "|---|---|---|---|---|" + cat "$out/rows.md" + echo + echo "The denominator is the host C++ code under \`mlx/\` and the Python bindings in \`python/src\`, which the C++ tests and the Python wheel link: $lines_total lines. It leaves out the tests, the build folders with their dependencies and generated files, the vendored \`mlx/3rdparty/pocketfft.h\`, and the CUDA backend in \`mlx/backend/cuda/\`, which macOS builds only as a stub." + echo "The C++ and Python tests run two times: one pass with the GPU and one pass with the CPU as the default device. The passes run in parallel jobs. The report merges the profiles of all jobs." + echo "The Metal shader source in \`mlx/backend/metal/kernels/\` is not in the denominator: the kernels run on the GPU and are outside every coverage tool. The host code that encodes and dispatches them is counted, and so are the few headers in that folder that host C++ includes." + echo "The Branches column is real C++ branch coverage. The 80% target is reported only. The job does not fail below it." + } >> "$GITHUB_STEP_SUMMARY" + + + - name: Upload the coverage report + if: ${{ !cancelled() && steps.coverage.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: coverage-report + path: ${{ runner.temp }}/coverage/report.txt + overwrite: true + + - name: Check the results of the other jobs + if: ${{ !cancelled() }} + env: + RESULTS: ${{ toJSON(needs) }} + run: | + echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' + bad=$(echo "$RESULTS" | jq -r '[to_entries[] | select(.value.result != "success") | .key] | join(" ")') + if [ -n "$bad" ]; then + echo "::error::Jobs that did not succeed: $bad" + exit 1 + fi + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true
diff --git ml-explore/mlx/tests/CMakeLists.txt Layr-Labs/mlx/tests/CMakeLists.txt index aa0d90105a7f6bd0a59cc14bcbe4eb244f601638..cc1c8cdcd6fad4affed8408d25c7465e39ef9675 100644 --- ml-explore/mlx/tests/CMakeLists.txt +++ Layr-Labs/mlx/tests/CMakeLists.txt @@ -16,7 +16,44 @@ target_link_libraries(tests PRIVATE CUDA::cudart) endif()   if(MLX_BUILD_METAL) - list(APPEND GPU_TEST_SOURCES residency_tests.cpp) + add_executable(metal_fence_chain metal_fence_chain.cpp) + target_link_libraries(metal_fence_chain PRIVATE mlx) + foreach(ops IN ITEMS 8 50 1024) + add_test(NAME metal_fence_chain_${ops} COMMAND metal_fence_chain) + set_tests_properties( + metal_fence_chain_${ops} + PROPERTIES TIMEOUT 60 ENVIRONMENT + "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") + endforeach() + list( + APPEND + GPU_TEST_SOURCES + residency_tests.cpp + gptoss_mxfp4_tests.cpp + quantized_tile_tests.cpp + qmv_batch_invariant_tests.cpp + nax_quantized_kernel_tests.cpp) + # MLX reads MLX_QMV_BATCH_INVARIANT once in each process, so this entry runs + # the case again in a new process with the switch on. The tests entries run it + # with the switch off. The entry fails also if no test case has this name. + add_test( + NAME qmv_batch_invariant + COMMAND + tests + "--test-case=quantized matmul rows keep their bits below the vector limit" + ) + set_tests_properties( + qmv_batch_invariant + PROPERTIES ENVIRONMENT "MLX_QMV_BATCH_INVARIANT=1" PASS_REGULAR_EXPRESSION + "test cases: +1 \\| +1 passed \\| +0 failed") + add_test( + NAME nax_ksplit_enabled + COMMAND tests + "--test-case=NAX affine K-split split-K and direct staged routes") + set_tests_properties( + nax_ksplit_enabled + PROPERTIES ENVIRONMENT "MLX_NAX_KSPLIT=1" PASS_REGULAR_EXPRESSION + "test cases: +1 \\| +1 passed \\| +0 failed") endif()   include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) @@ -32,6 +69,7 @@ compile_tests.cpp custom_vjp_tests.cpp creations_tests.cpp device_tests.cpp + distributed_sealed_stream_tests.cpp einsum_tests.cpp export_import_tests.cpp eval_tests.cpp @@ -51,3 +89,47 @@ target_link_options(tests PRIVATE ${SANITIZER_LINK_FLAGS})   doctest_discover_tests(tests) add_test(NAME tests COMMAND tests) + +# The standalone tests of the process allocation cap. The cap is install-once in +# each process, so these tests are not in the tests binary. Each ctest entry +# runs in a fresh process, and the Metal test runs one case in each process. +if(MLX_BUILD_METAL) + add_executable( + process_allocation_cap + ${PROJECT_SOURCE_DIR}/tests/standalone/process_allocation_cap.cpp) + target_link_libraries(process_allocation_cap PRIVATE mlx) + # The test checks its results with assert(). + target_compile_options(process_allocation_cap PRIVATE -UNDEBUG) + add_test(NAME process_allocation_cap COMMAND process_allocation_cap) + + add_executable( + process_allocation_cap_metal + ${PROJECT_SOURCE_DIR}/tests/standalone/process_allocation_cap_metal.cpp) + # The test replaces Metal device methods with the Objective-C runtime. + target_link_libraries(process_allocation_cap_metal PRIVATE mlx objc) + foreach( + case + install + retained + churn + foreign + gpu + late + concurrent + footprint-delta + gpu-footprint + nil-foreign + registration-capped + registration-foreign + registration-ordinary + registration-ordinary-foreign) + add_test(NAME process_allocation_cap_metal.${case} + COMMAND process_allocation_cap_metal ${case}) + # The registration cases exit with 77 when the device has no residency sets, + # so ctest reports them as skipped. + if(case MATCHES "^registration-") + set_tests_properties(process_allocation_cap_metal.${case} + PROPERTIES SKIP_RETURN_CODE 77) + endif() + endforeach() +endif()
diff --git ml-explore/mlx/tests/qmv_batch_invariant_tests.cpp Layr-Labs/mlx/tests/qmv_batch_invariant_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57047120f97016e0d07b3d45bd692d5076f0054c --- /dev/null +++ Layr-Labs/mlx/tests/qmv_batch_invariant_tests.cpp @@ -0,0 +1,170 @@ +// Copyright © 2026 Eigen Labs. +#include <algorithm> +#include <cstdlib> +#include <optional> +#include <string> +#include <utility> +#include <vector> + +#include "doctest/doctest.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" +#include "mlx/utils.h" + +using namespace mlx::core; + +namespace { + +// A copy of get_qmv_batch_limit (backend/metal/quantized.cpp): the first row +// count of x @ w.T (K inputs, N outputs) that takes a matrix kernel. +int qmv_batch_limit(int K, int N) { + auto& d = metal::device(Device::gpu); + char size = d.get_architecture().back(); + int gen = d.get_architecture_gen(); + bool small = K <= 2048 && N <= 2048; + bool medium = K <= 4096 && N <= 4096; + if (size != 'd' && gen >= 17) { + return small ? 33 : (medium ? 25 : 13); + } + if (size != 'd' && gen >= 15) { + return small ? 13 : (medium ? 15 : 13); + } + if (size == 'd') { + return small ? 32 : (medium ? 18 : 12); + } + if (gen >= 13) { + return small ? 14 : (medium ? 10 : ((gen == 13 && size == 's') ? 7 : 6)); + } + return small ? 18 : (medium ? 12 : 10); +} + +struct Weights { + std::string mode; + int group_size; + array w; + array scales; + std::optional<array> biases; +}; + +// Synthetic 4-bit weights with N outputs and K inputs: random packed values, +// affine in groups of 64 with bfloat16 scales and biases, or nvfp4 with +// positive e4m3 scales (bytes 0x20 to 0x4f). +Weights weights(const std::string& mode, int N, int K, uint64_t seed) { + auto key = [&](int i) { return random::key(4 * seed + i); }; + auto w = random::bits({N, K / 8}, 4, key(0), Device::gpu); + if (mode == "affine") { + auto values = [&](int i, float scale) { + return astype( + random::normal( + {N, K / 64}, float32, 0.0f, scale, key(i), Device::gpu), + bfloat16, + Device::gpu); + }; + return {mode, 64, w, values(1, 0.02f), values(2, 0.05f)}; + } + auto scales = random::randint( + array(0x20), array(0x50), {N, K / 16}, uint8, key(1), Device::gpu); + return {mode, 16, w, scales, std::nullopt}; +} + +array product(const Weights& q, const array& x) { + return quantized_matmul( + x, q.w, q.scales, q.biases, true, q.group_size, 4, q.mode, Device::gpu); +} + +// Each row of x [R, K] as its own product in one launch: x [R, 1, K] and the +// weights broadcast to [R, N, K / 8], so M = 1 and the batch is R (the +// decode rows of a batch of requests). +array single_rows(const Weights& q, const array& x) { + auto lead = [](const array& a) { return expand_dims(a, 0, Device::gpu); }; + auto y = quantized_matmul( + expand_dims(x, 1, Device::gpu), + lead(q.w), + lead(q.scales), + q.biases ? std::optional<array>(lead(*q.biases)) : std::nullopt, + true, + q.group_size, + 4, + q.mode, + Device::gpu); + return squeeze(y, 1, Device::gpu); +} + +array rows(const array& a, int start, int stop) { + return slice(a, {start, 0}, {stop, a.shape(1)}, Device::gpu); +} + +// Compares the bytes, so that 0 and -0 differ and two NaNs can be equal. +bool same_bytes(const array& a, const array& b) { + auto bytes = [](const array& x) { + auto type = x.dtype() == float32 ? uint32 : uint16; + return view(contiguous(x, false, Device::gpu), type, Device::gpu); + }; + return array_equal(bytes(a), bytes(b), Device::cpu).item<bool>(); +} + +} // namespace + +TEST_CASE("quantized matmul rows keep their bits below the vector limit") { + // MLX reads MLX_QMV_BATCH_INVARIANT once in each process. The tests binary + // runs this case without it, and the qmv_batch_invariant ctest entry runs + // it again with MLX_QMV_BATCH_INVARIANT=1 (tests/CMakeLists.txt). + const char* value = std::getenv("MLX_QMV_BATCH_INVARIANT"); + bool invariant = value != nullptr && std::atoi(value) != 0; + REQUIRE(env::qmv_batch_invariant() == invariant); + + // Tensor-parallel shard shapes (N outputs, K inputs) of GLM and Qwen + // projections. + std::vector<std::pair<int, int>> shapes = { + {4096, 4096}, + {6144, 4096}, + {4096, 6144}, + {8704, 5120}, + {5120, 8704}, + {3072, 5120}, + {2048, 4096}, + {1024, 4096}}; + for (auto [N, K] : shapes) { + // With the switch, every row count below the vector limit. Without it, + // up to 5 rows: from 6 rows other kernels can serve some shapes + // (qmv_mma from 6 rows, the NAX split-K from 8 rows). + int limit = qmv_batch_limit(K, N); + int count = invariant ? limit - 1 : std::min(5, limit - 1); + for (auto mode : {"affine", "nvfp4"}) { + auto q = weights(mode, N, K, N + K); + for (auto dtype : {bfloat16, float32}) { + CAPTURE(N); + CAPTURE(K); + CAPTURE(mode); + CAPTURE(dtype); + CAPTURE(count); + auto x = astype( + random::normal( + {count, K}, float32, 0.0f, 1.0f, random::key(K), Device::gpu), + dtype, + Device::gpu); + auto all = product(q, x); + eval(all); + // A window of m rows alone (one request) has the bits of the same + // rows among all the rows (several requests in one launch), at the + // start and at the end. From 2 rows the vector kernel is qmv_wide + // (or qmv where qmv_wide does not serve the mode on this GPU). + for (int m = 2; m <= count; ++m) { + CAPTURE(m); + CHECK(same_bytes(product(q, rows(x, 0, m)), rows(all, 0, m))); + CHECK(same_bytes( + product(q, rows(x, count - m, count)), + rows(all, count - m, count))); + } + // One row is qmv: alone, it has the bits that it has in a batch of + // single rows. It can have other bits among more rows. + auto singles = single_rows(q, x); + for (int i = 0; i < count; ++i) { + CAPTURE(i); + CHECK(same_bytes( + product(q, rows(x, i, i + 1)), rows(singles, i, i + 1))); + } + } + } + } +}

GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel’s 512-element alignment and fell to the general path. fp_gather_qmv_fast_tail runs five full blocks plus a 320-value tail read only by the participating lanes, preserving FP32 accumulation and the gathered indices/strides. It is enabled automatically only on the physical M4 Max architecture (applegpu_g16s) for the exact MXFP4/group-32⁄4-bit, E=32, K=2880, N=2880|5760, FP32/BF16 shape; MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL=0 restores the original route and MLX_GPTOSS_MXFP4_PREFILL_TILE=m32n32k32 opts into a separately measured prefill tile (gptoss_mxfp4_policy.h). (PR #14) fp_quantized.metal also builds the two m32n32k32 prefill-tile kernels (float and bfloat16) ahead of time, so CMake builds with the default MLX_METAL_JIT=OFF can load them. (PR #24)

diff --git ml-explore/mlx/mlx/backend/metal/gptoss_mxfp4_policy.h Layr-Labs/mlx/mlx/backend/metal/gptoss_mxfp4_policy.h new file mode 100644 index 0000000000000000000000000000000000000000..f0eaf66349c6952584059b25c4e622c436b1413f --- /dev/null +++ Layr-Labs/mlx/mlx/backend/metal/gptoss_mxfp4_policy.h @@ -0,0 +1,24 @@ +// Copyright © 2026 Eigen Labs. +#pragma once + +#include <cstdlib> +#include <string_view> + +namespace mlx::core::metal { + +struct GPTOSSMXFP4PrefillTile { + int bm = 16; + int bn = 32; + int bk = 32; + int wm = 1; + int wn = 2; +}; + +inline GPTOSSMXFP4PrefillTile gptoss_mxfp4_prefill_tile(const char* option) { + const std::string_view value = option ? option : ""; + if (value == "m32n32k32") + return {32, 32, 32, 2, 2}; + return {}; +} + +} // namespace mlx::core::metal
diff --git ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized.h Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized.h index 93162a7fd2ad2690f93848d48346aab78cb6b6d7..136e14999ff9adc6232f99785e4f24bfd94c1307 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4;   template <int wsize = 8, int bits = 4> -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; }   @@ -155,8 +155,8 @@ short tgp_size, short group_size, short bits, bool has_global_scale = false> -struct QuantizedBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); +struct FPQuantizedBlockLoader { + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -189,7 +189,7 @@ // nvfp4 tensor scale, folded into the group scale as fp_dequantize does. // Kept in float: it is ~1e-5, so in fp16 small scales lose most bits. float inv_scale_enc = 1.0f;   - QuantizedBlockLoader( + FPQuantizedBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -235,7 +235,7 @@ if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; }   - if (bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -245,8 +245,14 @@ float scale = float(dequantize_scale<T, group_size>(*scales)) * inv_scale_enc; for (int i = 0; i < n_reads; i++) { - dequantize<T, bits>( - src[i * bytes_per_pack], scale, dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize<T, bits>( + src[i * bytes_per_pack], scale, dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } }   @@ -369,7 +375,7 @@ uint3 tid [[threadgroup_position_in_grid]], uint quad_gid [[quadgroup_index_in_threadgroup]], uint quad_lid [[thread_index_in_quadgroup]]) { constexpr int quads_per_simd = SIMD_SIZE / QUAD_SIZE; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int values_per_thread = D / QUAD_SIZE; constexpr int steps_per_thread = values_per_thread < group_size ? 1 : values_per_thread / group_size; @@ -425,7 +431,8 @@ int group_size, int bits, bool partial_rows = false, bool has_global_scale = false, - int results_per_simdgroup = 4> + int results_per_simdgroup = 4, + bool allow_aligned_tail = false> METAL_FUNC void fp_qmv_fast_impl( const device uint32_t* w, const device uint8_t* scales, @@ -439,7 +446,7 @@ uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int packs_per_thread = 2; constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int values_per_thread = pack_factor * packs_per_thread; constexpr int block_size = values_per_thread * SIMD_SIZE; @@ -471,7 +478,10 @@ scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; y += tid.x * out_vec_size + out_row;   - for (int k = 0; k < in_vec_size; k += block_size) { + const int full_size = allow_aligned_tail + ? (in_vec_size / block_size) * block_size + : in_vec_size; + for (int k = 0; k < full_size; k += block_size) { load_vector<T, U, values_per_thread>(x, x_thread);   for (int row = 0; row < results_per_simdgroup; row++) { @@ -491,6 +501,24 @@ scales += block_size / group_size; x += block_size; }   + if constexpr (allow_aligned_tail) { + // K is group-aligned: every active lane owns a complete packed vector. + const int tail_values = in_vec_size - full_size; + if (int(simd_lid) * values_per_thread < tail_values) { + load_vector<T, U, values_per_thread>(x, x_thread); + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + const device uint8_t* wl = ws + src * in_vec_size_w; + const device uint8_t* sl = scales + src * in_vec_size_g; + U scale = dequantize_scale<U, group_size>(sl[0]); + result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, scale); + } + } + } + float inv_scale_enc = 1.0f; if constexpr (has_global_scale) { inv_scale_enc = *global_scale / (F8E4M3_MAX * F4E2M1_MAX); @@ -523,7 +551,7 @@ uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int packs_per_thread = 1; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>();   constexpr int values_per_thread = pack_factor * packs_per_thread; @@ -683,7 +711,7 @@ uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = SIMD_SIZE / k_lanes; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack<32>(); constexpr int nf4 = group_size / 4; // float4 lanes per quant group   @@ -798,7 +826,7 @@ uint3 tid [[threadgroup_position_in_grid]], uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int num_simdgroups = 2; - constexpr int pack_factor = get_pack_factor<32, bits>(); + constexpr int pack_factor = get_fp_pack_factor<32, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack();   constexpr int tn = group_size / pack_factor; @@ -928,7 +956,7 @@ (void)lid;   constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack();   constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -942,7 +970,7 @@ // Use shortcut when loading fp4 quants to half weights using loader_w_t = metal::conditional_t< metal::is_same_v<TW, half> && (bits == 4) && !has_global_scale, Fp4HalfLoader<BN, BK, BK_padded, WM * WN * SIMD_SIZE, group_size>, - QuantizedBlockLoader< + FPQuantizedBlockLoader< T, BN, BK, @@ -1080,7 +1108,7 @@ (void)lid;   constexpr int WM = 2; constexpr int WN = 2; - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack();   constexpr int BK_padded = (BK + 16 / sizeof(T)); @@ -1091,7 +1119,7 @@ using mma_t = mlx::steel:: BlockMMA<T, T, BM, BN, BK, WM, WN, false, false, BK_padded, BN_padded>; using loader_x_t = mlx::steel:: BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE, 1, 4>; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, BK, BN, @@ -2018,6 +2046,66 @@ simd_lid); }   template <typename T, int group_size, int bits, bool has_global_scale = false> +[[kernel]] void fp_gather_qmv_fast_tail( + const device uint32_t* w, + const device uint8_t* scales, + const device float* global_scale, + const device T* x, + const device uint32_t* lhs_indices, + const device uint32_t* rhs_indices, + device T* y, + const constant int& in_vec_size, + const constant int& out_vec_size, + const constant int& x_batch_ndims, + const constant int* x_shape, + const constant int64_t* x_strides, + const constant int& w_batch_ndims, + const constant int* w_shape, + const constant int64_t* w_strides, + const constant int64_t* s_strides, + const constant int& batch_ndims, + const constant int* batch_shape, + const constant int64_t* lhs_strides, + const constant int64_t* rhs_strides, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets<has_global_scale>( + x, + w, + scales, + global_scale, + lhs_indices, + rhs_indices, + y, + out_vec_size * M, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + tid); + fp_qmv_fast_impl<T, group_size, bits, false, has_global_scale, 4, true>( + w, + scales, + global_scale, + x, + y, + in_vec_size, + out_vec_size, + tid, + simd_gid, + simd_lid); +} + +template <typename T, int group_size, int bits, bool has_global_scale = false> [[kernel]] void fp_gather_qmv( const device uint32_t* w, const device uint8_t* scales, @@ -2253,7 +2341,7 @@ uint simd_lid [[thread_index_in_simdgroup]]) { (void)lid;   constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); using TW = metal::conditional_t< use_fp4_half_loader<T, group_size, bits, /* has_global_scale */ false>(), @@ -2394,7 +2482,7 @@ const constant int& num_groups, uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T)); @@ -2413,7 +2501,7 @@ BK_padded, transpose ? BK_padded : BN_padded>; using loader_x_t = mlx::steel::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * SIMD_SIZE>; - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN,
diff --git ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized.metal Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized.metal index e2e896e68ac9006c28798750cb150632ceaf2724..c9ca81e20c58c39f367caebf27f6c6af4a449a0b 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized.metal +++ Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized.metal @@ -308,3 +308,11 @@ instantiate_qmv_mma_types(float) instantiate_qmv_mma_types(bfloat16_t) instantiate_qmv_mma_types(float16_t) // clang-format on + +// Exact GPT-OSS MXFP4 gathered-vector tail experiment. +instantiate_quantized(mxfp4, gather_qmv_fast_tail, float, 32, 4) +instantiate_quantized(mxfp4, gather_qmv_fast_tail, bfloat16_t, 32, 4) + +// GPT-OSS MXFP4 prefill tile m32n32k32, selected by MLX_GPTOSS_MXFP4_PREFILL_TILE. +instantiate_gather_qmm_rhs(fp_gather_qmm_rhs, gather_qmm_rhs_nt, float, 32, 32, 32, 2, 2, true, mxfp4, 32, 4) +instantiate_gather_qmm_rhs(fp_gather_qmm_rhs, gather_qmm_rhs_nt, bfloat16_t, 32, 32, 32, 2, 2, true, mxfp4, 32, 4)
diff --git ml-explore/mlx/tests/gptoss_mxfp4_tests.cpp Layr-Labs/mlx/tests/gptoss_mxfp4_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..472d1e35b6a67d665b74cca9c578346870089de9 --- /dev/null +++ Layr-Labs/mlx/tests/gptoss_mxfp4_tests.cpp @@ -0,0 +1,218 @@ +// Copyright © 2026 Eigen Labs. +#include <algorithm> +#include <cmath> +#include <cstdint> +#include <cstdlib> +#include <optional> +#include <string> +#include <vector> + +#include "doctest/doctest.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { +struct ScopedPrefillTile { + std::optional<std::string> previous; + explicit ScopedPrefillTile(const char* value) { + if (const auto* old = std::getenv("MLX_GPTOSS_MXFP4_PREFILL_TILE")) + previous = old; + setenv("MLX_GPTOSS_MXFP4_PREFILL_TILE", value, 1); + } + ~ScopedPrefillTile() { + if (previous) + setenv("MLX_GPTOSS_MXFP4_PREFILL_TILE", previous->c_str(), 1); + else + unsetenv("MLX_GPTOSS_MXFP4_PREFILL_TILE"); + } +}; +} // namespace + +TEST_CASE( + "gptoss mxfp4 prefill tiles preserve expert boundaries and partial rows") { + constexpr int E = 32, N = 2880, K = 2880; + auto packed = reshape( + multiply( + arange(E * N * K / 8, uint32, Device::gpu), + array(uint32_t{2654435761}), + Device::gpu), + {E, N, K / 8}); + auto scales = full({E, N, K / 32}, array(uint8_t{126}), Device::gpu); + eval(packed, scales); + + for (const auto dtype : {float32, bfloat16}) { + for (int rows : {128, 131, 257}) { + std::vector<uint32_t> ids(rows); + for (int i = 0; i < rows; ++i) + ids[i] = (i * E) / rows; + const array indices(ids.data(), {rows}); + auto x = astype( + reshape( + sin(arange(rows * K, float32, Device::gpu) * array(0.017f), + Device::gpu), + {rows, 1, K}), + dtype, + Device::gpu); + array reference(0.0f); + { + ScopedPrefillTile tile("legacy"); + reference = gather_qmm( + x, + packed, + scales, + std::nullopt, + std::nullopt, + indices, + true, + 32, + 4, + "mxfp4", + std::nullopt, + true, + Device::gpu); + eval(reference); + } + for (const auto* name : {"m32n32k32"}) { + ScopedPrefillTile tile(name); + const auto actual = gather_qmm( + x, + packed, + scales, + std::nullopt, + std::nullopt, + indices, + true, + 32, + 4, + "mxfp4", + std::nullopt, + true, + Device::gpu); + eval(actual); + INFO("tile=", name, " rows=", rows, " dtype=", dtype); + const auto delta = + abs(astype(actual, float32) - astype(reference, float32)); + const float worst = max(delta).item<float>(); + const float magnitude = + max(abs(astype(reference, float32))).item<float>(); + CHECK(std::isfinite(worst)); + CHECK( + worst <= + (dtype == float32 ? 1e-4f : 0.016f) * std::max(1.0f, magnitude)); + } + } + } +} + +namespace { +struct ScopedDecodeFastTail { + std::optional<std::string> previous; + explicit ScopedDecodeFastTail(const char* value) { + if (const auto* old = std::getenv("MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL")) + previous = old; + setenv("MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL", value, 1); + } + ~ScopedDecodeFastTail() { + if (previous) + setenv("MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL", previous->c_str(), 1); + else + unsetenv("MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL"); + } +}; +} // namespace + +TEST_CASE("gptoss mxfp4 fast gather covers the final 320 input values") { + constexpr int E = 32, N = 2880, K = 2880; + auto packed = reshape( + multiply( + arange(E * N * K / 8, uint32, Device::gpu), + array(uint32_t{2654435761}), + Device::gpu), + {E, N, K / 8}); + auto scales = full({E, N, K / 32}, array(uint8_t{126}), Device::gpu); + eval(packed, scales); + for (const auto dtype : {float32, bfloat16}) { + for (int batch : {1, 2, 4, 8}) { + std::vector<uint32_t> lhs_ids(batch * 4), rhs_ids(batch * 4); + for (int row = 0; row < batch; ++row) { + for (int expert = 0; expert < 4; ++expert) { + lhs_ids[row * 4 + expert] = row; + rhs_ids[row * 4 + expert] = (row * 7 + expert * 5) % E; + } + } + const array lhs(lhs_ids.data(), {batch, 4}); + const array rhs(rhs_ids.data(), {batch, 4}); + for (bool tail_edges_only : {true, false}) { + std::vector<float> values(batch * K, 0.0f); + for (int row = 0; row < batch; ++row) { + if (tail_edges_only) { + values[row * K + 2559] = 0.75f; + values[row * K + 2560] = 0.25f; + values[row * K + 2879] = -0.5f; + } else { + for (int k = 0; k < K; ++k) + values[row * K + k] = std::sin((row * K + k) * 0.017f); + } + } + auto x = + astype(array(values.data(), {batch, 1, K}), dtype, Device::gpu); + array reference(0.0f); + { + ScopedDecodeFastTail flag("0"); + reference = gather_qmm( + x, + packed, + scales, + std::nullopt, + lhs, + rhs, + true, + 32, + 4, + "mxfp4", + std::nullopt, + false, + Device::gpu); + eval(reference); + } + ScopedDecodeFastTail flag("1"); + const auto actual = gather_qmm( + x, + packed, + scales, + std::nullopt, + lhs, + rhs, + true, + 32, + 4, + "mxfp4", + std::nullopt, + false, + Device::gpu); + eval(actual); + INFO( + "batch=", + batch, + " dtype=", + dtype, + " tail_edges_only=", + tail_edges_only); + if (tail_edges_only) { + CHECK(array_equal(actual, reference).item<bool>()); + } else { + const auto delta = + abs(astype(actual, float32) - astype(reference, float32)); + const float worst = max(delta).item<float>(); + const float magnitude = + max(abs(astype(reference, float32))).item<float>(); + CHECK(std::isfinite(worst)); + CHECK( + worst <= + (dtype == float32 ? 1e-4f : 0.016f) * std::max(1.0f, magnitude)); + } + } + } + } +}

Admission accounting used to combine independent reads of the allocator counters with logical buffer sizes, so concurrent allocator activity could produce an incoherent snapshot and alignment / cache reuse could make the real backing larger than the request. get_memory_snapshot() reads active / cache / peak under one lock; get_allocation_size_upper_bound() and the detached, lock-free AllocationFootprintPolicy bound a buffer including alignment and the (now inclusive, overflow-checked) cache-reuse limit shared with BufferCache. Metal, CPU and CUDA allocators implement the same interface; the allocator’s own behaviour stays the authority. These describe allocator accounting, not process RSS. (PR #15) The public process-allocation cap API adds install-once Metal backing enforcement. Reservations include pending allocations and the fixed heap. Owned page-aligned VM regions use Metal no-copy buffers; credit returns after the deallocator unmaps them. Foreign wrappers retain caller ownership. CPU/CUDA reject this optional API; soft memory limits are unchanged. Residency insertion rolls back failed registration before callers release buffers, including ordinary uncapped allocations. Standalone CPU and real-Metal tests cover delayed release, churn, and injected construction failures. tests/CMakeLists.txt builds them as their own executables, because the cap is install-once in each process, and gives one ctest entry to each case of the Metal test. The Metal test uses allocator().malloc / allocator().free, which return and free a plain Buffer, because upstream #4634 made allocator::malloc return an owning Data. The allocator makes no fixed heap on a virtual GPU (the GitHub-hosted runner), so the cases check the heap charge and heap use that match the device. The registration cases fill one residency set with a page first, so that the injected failure of a new set is reached with or without the heap in set 0. When the device has no residency sets (ResidencySets::enabled() is false: no Metal 3 GPU family or macOS before 15, as on the virtual GPU of the hosted runner), the path these cases test does not exist. They then print the reason and exit with 77, which ctest reports as skipped (SKIP_RETURN_CODE). David ruled on 2026-10-24 to skip by capability, like the 4 GiB capability skip below. Capped no-copy pages are first touched on the CPU so process physical footprint accounts for pages later written by the GPU. The native footprint contract is documented in docs/src/usage/unified_memory.rst.

diff --git ml-explore/mlx/docs/src/usage/unified_memory.rst Layr-Labs/mlx/docs/src/usage/unified_memory.rst index 57f54bc23b41a3f207a82f89dec8d0f6c284b047..2430806e2c9cc2086d5fda83f85d2c93e82ff41f 100644 --- ml-explore/mlx/docs/src/usage/unified_memory.rst +++ Layr-Labs/mlx/docs/src/usage/unified_memory.rst @@ -76,3 +76,17 @@ If we time the computation fully on the GPU, we get 2.8 milliseconds. But if we run the computation with ``d1=mx.gpu`` and ``d2=mx.cpu``, then the time is only about 1.4 milliseconds, about twice as fast. These times were measured on an M1 Max. + +Native allocation footprint bounds +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The C++ ``get_allocation_footprint_policy()`` returns a detached value that +bounds one allocator buffer, including alignment and permitted cache reuse. +Zero bytes has a zero bound; arithmetic overflow is refused. The bound does +not apply a one-page minimum to requests smaller than one page. + +Capped no-copy backing is touched once per VM page from the CPU before it is +wrapped as a Metal buffer. This makes the process physical footprint include +pages first written by GPU work. It preserves the allocator cap and does not +replace load admission or operating-system memory headroom. The fresh-process +``gpu-footprint`` regression checks GPU-written backing; it requires Metal.
diff --git ml-explore/mlx/mlx/backend/common/allocation_footprint.h Layr-Labs/mlx/mlx/backend/common/allocation_footprint.h new file mode 100644 index 0000000000000000000000000000000000000000..c7ec23de6a33ba32426df48c458116a773d17f4b --- /dev/null +++ Layr-Labs/mlx/mlx/backend/common/allocation_footprint.h @@ -0,0 +1,39 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include <algorithm> +#include <cstddef> +#include <limits> +#include <stdexcept> + +namespace mlx::core::allocator { + +inline size_t checked_allocation_add(size_t size, size_t extra) { + if (extra > std::numeric_limits<size_t>::max() - size) { + throw std::overflow_error("allocation footprint overflow"); + } + return size + extra; +} + +inline size_t round_allocation_size(size_t size, size_t alignment) { + if (alignment == 0) { + throw std::invalid_argument("allocation alignment is zero"); + } + auto remainder = size % alignment; + return checked_allocation_add(size, remainder ? alignment - remainder : 0); +} + +// Inclusive cache-reuse bound. A fresh buffer never exceeds this bound. +inline size_t maximum_reuse_size(size_t size, size_t page_size) { + if (size == 0) { + return 0; + } + auto two_pages = checked_allocation_add(page_size, page_size); + if (two_pages == 0) { + throw std::invalid_argument("cache page size is zero"); + } + return checked_allocation_add(size, std::min(size - 1, two_pages - 1)); +} + +} // namespace mlx::core::allocator
diff --git ml-explore/mlx/mlx/backend/common/buffer_cache.h Layr-Labs/mlx/mlx/backend/common/buffer_cache.h index 27648b2fbc0736331fbe3d71d5b82e212848f606..177dbc11ac7dcc09f1472871e4b99ee8b58b1f75 100644 --- ml-explore/mlx/mlx/backend/common/buffer_cache.h +++ Layr-Labs/mlx/mlx/backend/common/buffer_cache.h @@ -7,6 +7,8 @@ #include <cassert> #include <functional> #include <map>   +#include "mlx/backend/common/allocation_footprint.h" + namespace mlx::core {   template <typename T> @@ -28,10 +30,13 @@ BufferCache(const BufferCache&) = delete; BufferCache& operator=(const BufferCache&) = delete;   T* reuse_from_cache(size_t size) { + if (size == 0) { + return nullptr; + } // Find the closest buffer in pool. auto it = buffer_pool_.lower_bound(size); if (it == buffer_pool_.end() || - it->first >= std::min(2 * size, size + 2 * page_size_)) { + it->first > allocator::maximum_reuse_size(size, page_size_)) { return nullptr; }
diff --git ml-explore/mlx/mlx/backend/common/process_allocation_cap.h Layr-Labs/mlx/mlx/backend/common/process_allocation_cap.h new file mode 100644 index 0000000000000000000000000000000000000000..d92723b73efc53eab9875ded3741485da5dd6276 --- /dev/null +++ Layr-Labs/mlx/mlx/backend/common/process_allocation_cap.h @@ -0,0 +1,192 @@ +// Copyright © 2026 Eigen Labs. +#pragma once + +#include <cstddef> +#include <limits> +#include <memory> +#include <mutex> +#include <stdexcept> + +namespace mlx::core::allocator { + +struct ProcessAllocationCapSnapshot { + bool installed{false}; + size_t limit_bytes{0}; + size_t heap_bytes{0}; + size_t live_bytes{0}; + size_t cached_bytes{0}; + size_t pending_bytes{0}; + size_t unreclaimed_bytes{0}; + size_t charged_bytes{0}; + size_t peak_bytes{0}; +}; + +// Reference release alone cannot refund backing credit. +class ProcessAllocationCap { + public: + void install(size_t limit, size_t heap) { + std::lock_guard lock(mutex_); + if (state_.installed || !limit || heap > limit) { + throw std::invalid_argument("allocation cap install refused"); + } + state_.installed = true; + state_.limit_bytes = limit; + state_.heap_bytes = heap; + state_.charged_bytes = state_.peak_bytes = heap; + } + + void reserve(size_t bytes) { + std::lock_guard lock(mutex_); + if (!state_.installed || + bytes > state_.limit_bytes - state_.charged_bytes) { + throw std::runtime_error("native allocation cap exceeded"); + } + state_.pending_bytes += bytes; + state_.charged_bytes += bytes; + if (state_.charged_bytes > state_.peak_bytes) { + state_.peak_bytes = state_.charged_bytes; + } + } + + // Only a reservation for which no backing was acquired can be rolled back. + void failed_before_acquisition(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.pending_bytes, bytes); + state_.pending_bytes -= bytes; + state_.charged_bytes -= bytes; + } + void acquired(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.pending_bytes, state_.live_bytes, bytes); + } + void cache(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.live_bytes, state_.cached_bytes, bytes); + } + void reuse(size_t bytes) { + std::lock_guard lock(mutex_); + transfer(state_.cached_bytes, state_.live_bytes, bytes); + } + void relinquish(size_t bytes, bool cached = false) { + std::lock_guard lock(mutex_); + transfer( + cached ? state_.cached_bytes : state_.live_bytes, + state_.unreclaimed_bytes, + bytes); + } + void destroyed(size_t bytes) { + std::lock_guard lock(mutex_); + require(state_.unreclaimed_bytes, bytes); + state_.unreclaimed_bytes -= bytes; + state_.charged_bytes -= bytes; + } + ProcessAllocationCapSnapshot snapshot() const { + std::lock_guard lock(mutex_); + return state_; + } + + private: + static void require(size_t available, size_t bytes) { + if (bytes > available) { + throw std::logic_error("allocation cap ledger mismatch"); + } + } + static void transfer(size_t& from, size_t& to, size_t bytes) { + require(from, bytes); + if (bytes > std::numeric_limits<size_t>::max() - to) { + throw std::overflow_error("allocation cap ledger overflow"); + } + from -= bytes; + to += bytes; + } + mutable std::mutex mutex_; + ProcessAllocationCapSnapshot state_; +}; + +// Shared by allocator bookkeeping and the Metal deallocator block. The callback +// never takes the allocator mutex. Release must finish before credit is +// returned. +class ProcessBackingLease { + public: + using Release = bool (*)(void*, size_t); + ProcessBackingLease(std::shared_ptr<ProcessAllocationCap> cap, size_t bytes) + : cap_(std::move(cap)), bytes_(bytes) { + cap_->reserve(bytes_); + } + ~ProcessBackingLease() { + finish(); + } + void attach(void* pointer, Release release) noexcept { + std::lock_guard lock(mutex_); + pointer_ = pointer; + release_ = release; + } + void acquired() { + std::lock_guard lock(mutex_); + if (state_ != State::pending) { + throw std::logic_error("backing already retired"); + } + cap_->acquired(bytes_); + state_ = State::live; + } + void cache() { + std::lock_guard lock(mutex_); + if (state_ != State::live) { + throw std::logic_error("backing cache mismatch"); + } + cap_->cache(bytes_); + state_ = State::cached; + } + void reuse() { + std::lock_guard lock(mutex_); + if (state_ != State::cached) { + throw std::logic_error("backing reuse mismatch"); + } + cap_->reuse(bytes_); + state_ = State::live; + } + void retire() { + std::lock_guard lock(mutex_); + if (state_ != State::live && state_ != State::cached) { + throw std::logic_error("backing retirement mismatch"); + } + cap_->relinquish(bytes_, state_ == State::cached); + state_ = State::retired; + } + void finish() noexcept { + std::lock_guard lock(mutex_); + if (state_ == State::finished) { + return; + } + // Foreign wrappers have no release function: their caller retains + // ownership. + const bool released = !release_ || release_(pointer_, bytes_); + if (state_ == State::pending && released) { + cap_->failed_before_acquisition(bytes_); + } else { + if (state_ == State::pending) { + cap_->acquired(bytes_); + } + if (state_ != State::retired) { + cap_->relinquish(bytes_, state_ == State::cached); + } + if (released) { + cap_->destroyed(bytes_); + } + } + // A failed backing release is permanently charged; it cannot be retried + // after ownership has been relinquished to a deallocator callback. + state_ = State::finished; + } + + private: + enum class State { pending, live, cached, retired, finished }; + std::shared_ptr<ProcessAllocationCap> cap_; + size_t bytes_; + void* pointer_{nullptr}; + Release release_{nullptr}; + State state_{State::pending}; + std::mutex mutex_; +}; + +} // namespace mlx::core::allocator
diff --git ml-explore/mlx/mlx/backend/cuda/allocator.cpp Layr-Labs/mlx/mlx/backend/cuda/allocator.cpp index bb262d0e63b4ce116a879902cbc53051ed129706..2aac8780ecd0cfd915d947e86f9e23beea412f82 100644 --- ml-explore/mlx/mlx/backend/cuda/allocator.cpp +++ Layr-Labs/mlx/mlx/backend/cuda/allocator.cpp @@ -29,6 +29,19 @@ // Any allocations smaller than this will try to use the small pool constexpr int small_block_size = 8;   +size_t normalized_allocation_size(size_t size) { + if (size == 0) { + return 0; + } + if (size <= small_block_size) { + return 8; + } + if (size < page_size) { + return next_power_of_2(size); + } + return allocator::round_allocation_size(size, page_size); +} + // The small pool size in bytes. This should be a multiple of the host page // size and small_block_size. constexpr int small_pool_size = 4 * page_size; @@ -173,13 +186,7 @@ if (size == 0) { return Buffer{new CudaBuffer{nullptr, 0, -1}}; }   - if (size <= small_block_size) { - size = 8; - } else if (size < page_size) { - size = next_power_of_2(size); - } else { - size = page_size * ((size + page_size - 1) / page_size); - } + size = normalized_allocation_size(size);   if (size <= small_block_size || stream == nullptr) { device = -1; @@ -344,6 +351,11 @@ std::lock_guard lock(mutex_); peak_memory_ = 0; }   +MemorySnapshot CudaAllocator::get_memory_snapshot() { + std::lock_guard lock(mutex_); + return {active_memory_, buffer_cache_.cache_size(), peak_memory_}; +} + size_t CudaAllocator::get_memory_limit() { #ifdef _WIN32 int device = default_device().index; @@ -425,6 +437,21 @@ }   } // namespace allocator   +AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { + return {cu::page_size, 0, cu::small_block_size, cu::page_size, cu::page_size}; +} + +size_t get_allocation_size_upper_bound(size_t size) { + size_t result; + if (!get_allocation_footprint_policy().upper_bound(size, result)) { + throw std::overflow_error("allocation footprint overflow"); + } + return result; +} + +MemorySnapshot get_memory_snapshot() { + return cu::allocator().get_memory_snapshot(); +} size_t get_active_memory() { return cu::allocator().get_active_memory(); } @@ -434,6 +461,15 @@ } void reset_peak_memory() { return cu::allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return cu::allocator().set_memory_limit(limit); } @@ -442,6 +478,13 @@ return cu::allocator().get_memory_limit(); } size_t get_cache_memory() { return cu::allocator().get_cache_memory(); +} +size_t get_num_resources() { + // CUDA allocator does not track a Metal-style resource count; report 0. + return 0; +} +size_t get_resource_limit() { + return 0; } size_t set_cache_limit(size_t limit) { return cu::allocator().set_cache_limit(limit);
diff --git ml-explore/mlx/mlx/backend/cuda/allocator.h Layr-Labs/mlx/mlx/backend/cuda/allocator.h index f0416c08392c7bcd99dd9626dd0cd65b2b889505..e851ce6f7f3b845e415258791883fdc00a02438c 100644 --- ml-explore/mlx/mlx/backend/cuda/allocator.h +++ Layr-Labs/mlx/mlx/backend/cuda/allocator.h @@ -5,6 +5,7 @@ #include "mlx/allocator.h" #include "mlx/backend/common/buffer_cache.h" #include "mlx/backend/cuda/cuda_utils.h" +#include "mlx/memory.h"   #include <cuda_runtime.h> #include <mutex> @@ -58,6 +59,7 @@ // Replace the memory of |buf| with unified memory (managed memory or pinned // host memory), and copy the data over. Pass |stream| to copy asynchronously. void move_to_unified_memory(CudaBuffer& buf, cudaStream_t stream = nullptr);   + MemorySnapshot get_memory_snapshot(); size_t get_active_memory() const; size_t get_peak_memory() const; void reset_peak_memory();
diff --git ml-explore/mlx/mlx/backend/metal/allocator.cpp Layr-Labs/mlx/mlx/backend/metal/allocator.cpp index 903cce21879a94de36929c0e5568e9f3d6e09ca7..962ce2951c2d633370907eb84f360f8852e39502 100644 --- ml-explore/mlx/mlx/backend/metal/allocator.cpp +++ Layr-Labs/mlx/mlx/backend/metal/allocator.cpp @@ -6,9 +6,13 @@ #include "mlx/backend/metal/resident.h" #include "mlx/memory.h"   #include <mach/vm_page_size.h> +#include <sys/mman.h> #include <unistd.h> +#include <algorithm> #include <cassert> +#include <cerrno> #include <cstdlib> +#include <limits>   namespace mlx::core {   @@ -49,6 +53,7 @@ buffer_cache_( vm_page_size, [](MTL::Buffer* buf) { return buf->length(); }, [this](MTL::Buffer* buf) { + relinquish_capped(buf, true); if (!buf->heap()) { residency_sets_.erase(buf); } @@ -60,6 +65,30 @@ auto memsize = std::get<size_t>(info.at("memory_size")); auto max_rec_size = std::get<size_t>(info.at("max_recommended_working_set_size")); resource_limit_ = std::get<size_t>(info.at("resource_limit")); + // Optional override (Darkbloom): MLX_RESOURCE_LIMIT lets an operator/test pin + // the Metal resource-COUNT ceiling below the OS default (~499000). Used to + // deterministically exercise the count-aware high-water trim, and as a safety + // valve to force earlier cache reclamation on a box seeing the resource-limit + // crash. The value may only LOWER the ceiling (it is clamped to the OS limit) + // — raising it above what the hardware/OS reports would invite the very crash + // this guards against. Strictly validated: a plain unsigned decimal that + // consumes the whole string, is non-zero, and does not overflow; anything + // else (empty, sign, junk, range error) is ignored and the OS limit stands. + if (const char* rl = std::getenv("MLX_RESOURCE_LIMIT")) { + while (*rl == ' ' || *rl == '\t') { + ++rl; + } + if (*rl >= '0' && *rl <= '9') { // unsigned decimal only (reject sign/junk) + errno = 0; + char* end = nullptr; + unsigned long long v = std::strtoull(rl, &end, 10); + bool consumed_all = end != rl && *end == '\0'; + if (consumed_all && errno != ERANGE && v > 0 && + v <= std::numeric_limits<size_t>::max()) { + resource_limit_ = std::min(static_cast<size_t>(v), resource_limit_); + } + } + } block_limit_ = std::min(1.5 * max_rec_size, 0.95 * memsize); gc_limit_ = std::min(static_cast<size_t>(0.95 * max_rec_size), block_limit_); max_pool_size_ = block_limit_; @@ -93,6 +122,11 @@ static_cast<size_t>(0.95 * device_->recommendedMaxWorkingSetSize())); return limit; };   +MemorySnapshot MetalAllocator::get_memory_snapshot() { + std::lock_guard lock(mutex_); + return {active_memory_, buffer_cache_.cache_size(), peak_memory_}; +} + size_t MetalAllocator::get_memory_limit() { return block_limit_; } @@ -104,14 +138,142 @@ residency_sets_.resize(wired_limit_); return limit; };   +void MetalAllocator::install_process_allocation_cap(size_t bytes) { + std::unique_lock lock(mutex_); + if (buffer_allocation_attempted_) { + throw std::invalid_argument( + "allocation cap requires a pristine buffer allocator"); + } + cap_->install(bytes, heap_ ? heap_->size() : 0); + cap_installed_ = true; +} + +ProcessAllocationCapSnapshot +MetalAllocator::get_process_allocation_cap_snapshot() { + return cap_->snapshot(); +} + +void MetalAllocator::relinquish_capped(MTL::Buffer* buffer, bool cached) { + if (!cap_installed_) { + return; + } + auto entry = capped_buffers_.find(buffer); + if (entry == capped_buffers_.end()) { + throw std::logic_error("untracked capped buffer"); + } + if (entry->second) { + entry->second->retire(); + } + capped_buffers_.erase(entry); +} + +Buffer MetalAllocator::malloc_capped( + size_t size, + std::unique_lock<std::mutex>& lock) { + if (auto* cached = buffer_cache_.reuse_from_cache(size)) { + if (auto lease = capped_buffers_.at(cached)) { + lease->reuse(); + } + active_memory_ += cached->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{cached}; + } + // Trim idle backing before refusing a new shape. Actual callbacks, not cache + // eviction, return credit; externally retained buffers remain charged. + auto snapshot = cap_->snapshot(); + const auto charge = allocator::round_allocation_size(size, vm_page_size); + if (charge > device_->maxBufferLength()) { + throw std::invalid_argument( + "page-aligned backing exceeds Metal buffer limit"); + } + if (charge > snapshot.limit_bytes - snapshot.charged_bytes || + num_resources_ >= resource_limit_ || + buffer_cache_.cache_size() > max_pool_size_) { + num_resources_ -= buffer_cache_.clear(); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + MTL::Buffer* buffer = nullptr; + std::shared_ptr<allocator::ProcessBackingLease> lease; + if (size < small_size_ && heap_) { + buffer = heap_->newBuffer(size, resource_options); + } + if (!buffer) { + // Reserve before releasing allocator lock, including in-flight allocations. + lease = std::make_shared<allocator::ProcessBackingLease>(cap_, charge); + ++num_resources_; + lock.unlock(); + try { + void* pages = mmap( + nullptr, + charge, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + if (pages == MAP_FAILED) { + throw std::bad_alloc(); + } + lease->attach(pages, [](void* p, size_t n) { return munmap(p, n) == 0; }); + // Fault every page from the CPU before wrapping it. Pages a no-copy + // buffer first receives through the GPU are not charged to this + // process's physical footprint, which hides the model from the OS + // memory-pressure accounting and from Activity Monitor. + for (size_t offset = 0; offset < charge; offset += vm_page_size) { + static_cast<volatile char*>(pages)[offset] = 0; + } + buffer = device_->newBuffer( + pages, charge, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + if (!buffer) { + throw std::runtime_error("Metal no-copy allocation failed"); + } + lease->acquired(); + } catch (...) { + if (buffer) { + buffer->release(); + } else { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); + } else { + ++num_resources_; + } + try { + capped_buffers_.emplace(buffer, lease); + if (!buffer->heap()) { + residency_sets_.insert(buffer); + } + } catch (...) { + capped_buffers_.erase(buffer); + if (lease) { + lease->retire(); + } + --num_resources_; + buffer->release(); + throw; + } + active_memory_ += buffer->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + return Buffer{buffer}; +} + Buffer MetalAllocator::malloc(size_t size) { // Metal doesn't like empty buffers if (size == 0) { return Buffer{nullptr}; }   - // More helpful message if maximum buffer length is exceeded - if (size > device_->maxBufferLength()) { + // More helpful message if maximum buffer length is exceeded. The limit is + // fixed for the device: read it once, not with a Metal call per buffer. + static const size_t max_buffer_length = device_->maxBufferLength(); + if (size > max_buffer_length) { std::ostringstream msg; msg << "[metal::malloc] Attempting to allocate " << size << " bytes which is greater than" @@ -122,21 +284,47 @@ }   // Align up memory if (size > vm_page_size) { - size = vm_page_size * ((size + vm_page_size - 1) / vm_page_size); + size = allocator::round_allocation_size(size, vm_page_size); }   // Try the cache std::unique_lock lk(mutex_); + buffer_allocation_attempted_ = true; + if (cap_installed_) { + return malloc_capped(size, lk); + } MTL::Buffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { size_t mem_required = get_active_memory() + get_cache_memory() + size;   - // If we have a lot of memory pressure try to reclaim memory from the cache + // If we have a lot of memory pressure try to reclaim memory from the cache. + // NOTE: release_cached_buffers takes a BYTES-to-free target; when the + // buffers are tiny this frees only a few entries even though the COUNT is + // the binding constraint, so the byte path alone cannot bound + // num_resources_ (see the count-aware reclaim below). if (mem_required >= gc_limit_ || num_resources_ >= resource_limit_) { num_resources_ -= buffer_cache_.release_cached_buffers(mem_required - gc_limit_); }   + // Count-aware reclaim (Darkbloom): the Metal resource COUNT limit + // (resource_limit_, ~iogpu.rsrc_limit/499000) is independent of byte usage. + // Under churn with many distinct buffer shapes (varied prompt lengths, + // growing KV caches, multiple co-resident models) freed buffers are + // recycled into the size-keyed cache and never reused at that exact size, + // so the cache ENTRY COUNT creeps toward the limit while byte usage stays + // modest — the byte-driven trim above never fires (its threshold is + // ~physical RAM). Once the count crosses a high-water mark, proactively + // clear the cache (pure reuse pool — clearing only costs re-allocation, + // never correctness) so the count drops back to the live working set. This + // makes the count limit unreachable by any request mix / batching method, + // while the existing byte limits keep total memory below physical RAM. + if (resource_limit_ > 0 && + num_resources_ >= (resource_limit_ * resource_high_water_num_) / + resource_high_water_den_) { + num_resources_ -= buffer_cache_.clear(); + } + // Allocate new buffer if needed if (num_resources_ >= resource_limit_) { std::ostringstream msg; @@ -157,10 +345,16 @@ msg << "[malloc] Unable to allocate " << size << " bytes."; throw std::runtime_error(msg.str()); } lk.lock(); - num_resources_++; - if (!buf->heap()) { - residency_sets_.insert(buf); + try { + if (!buf->heap()) { + residency_sets_.insert(buf); + } + } catch (...) { + lk.unlock(); + buf->release(); + throw; } + num_resources_++; }   active_memory_ += buf->length(); @@ -189,7 +383,13 @@ std::unique_lock lk(mutex_); active_memory_ -= buf->length(); if (get_cache_memory() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); + if (cap_installed_) { + if (auto lease = capped_buffers_.at(buf)) { + lease->cache(); + } + } } else { + relinquish_capped(buf, false); num_resources_--; if (!buf->heap()) { residency_sets_.erase(buf); @@ -205,15 +405,91 @@ return static_cast<MTL::Buffer*>(buffer.ptr())->length(); }   Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { - auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + std::unique_lock lock(mutex_); + buffer_allocation_attempted_ = true; + if (!cap_installed_) { + lock.unlock(); + auto buf = device_->newBuffer(ptr, size, resource_options, nullptr); + if (!buf) { + return Buffer{nullptr}; + } + lock.lock(); + try { + residency_sets_.insert(buf); + } catch (...) { + lock.unlock(); + buf->release(); + throw; + } + active_memory_ += buf->length(); + peak_memory_ = std::max(peak_memory_, active_memory_); + num_resources_++; + return Buffer{static_cast<void*>(buf)}; + } + std::shared_ptr<allocator::ProcessBackingLease> lease; + if (cap_installed_) { + if (!size || size % vm_page_size || + reinterpret_cast<uintptr_t>(ptr) % vm_page_size || !ptr || + size > device_->maxBufferLength()) { + throw std::invalid_argument( + "capped foreign backing must be page aligned"); + } + if (num_resources_ >= resource_limit_) { + throw std::runtime_error("Metal resource limit exceeded"); + } + lease = std::make_shared<allocator::ProcessBackingLease>(cap_, size); + } + ++num_resources_; + lock.unlock(); + MTL::Buffer* buf = nullptr; + try { + if (lease) { + // Charge wrapper lifetime; never free or assume ownership of caller + // pages. + buf = device_->newBuffer( + ptr, size, resource_options, ^(void*, NS::UInteger) { + lease->finish(); + }); + } else { + buf = device_->newBuffer(ptr, size, resource_options, nullptr); + } + if (buf && lease) { + lease->acquired(); + } + } catch (...) { + if (buf) { + buf->release(); + } else if (lease) { + lease->finish(); + } + lock.lock(); + --num_resources_; + throw; + } + lock.lock(); if (!buf) { - return Buffer{nullptr}; + if (lease) { + lease->finish(); + } + --num_resources_; + throw std::runtime_error("capped Metal no-copy wrapper allocation failed"); } - std::unique_lock lk(mutex_); - residency_sets_.insert(buf); + try { + if (lease) { + capped_buffers_.emplace(buf, lease); + } + residency_sets_.insert(buf); + } catch (...) { + if (lease) { + capped_buffers_.erase(buf); + lease->retire(); + } + --num_resources_; + buf->release(); + throw; + } active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); - num_resources_++; return Buffer{static_cast<void*>(buf)}; }   @@ -224,6 +500,7 @@ return; } std::unique_lock lk(mutex_); active_memory_ -= buf->length(); + relinquish_capped(buf, false); num_resources_--; residency_sets_.erase(buf); lk.unlock(); @@ -242,6 +519,25 @@ }   } // namespace metal   +AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { + return {vm_page_size, vm_page_size, 0, 0, vm_page_size}; +} + +size_t get_allocation_size_upper_bound(size_t size) { + size_t result; + if (!get_allocation_footprint_policy().upper_bound(size, result)) { + throw std::overflow_error("allocation footprint overflow"); + } + return result; +} + +void install_process_allocation_cap(size_t bytes) { + metal::allocator().install_process_allocation_cap(bytes); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + return metal::allocator().get_process_allocation_cap_snapshot(); +} + size_t set_cache_limit(size_t limit) { return metal::allocator().set_cache_limit(limit); } @@ -260,6 +556,9 @@ "the maximum working set size is not allowed."); } return metal::allocator().set_wired_limit(limit); } +MemorySnapshot get_memory_snapshot() { + return metal::allocator().get_memory_snapshot(); +} size_t get_active_memory() { return metal::allocator().get_active_memory(); } @@ -271,6 +570,12 @@ metal::allocator().reset_peak_memory(); } size_t get_cache_memory() { return metal::allocator().get_cache_memory(); +} +size_t get_num_resources() { + return metal::allocator().get_num_resources(); +} +size_t get_resource_limit() { + return metal::allocator().get_resource_limit(); } void clear_cache() { return metal::allocator().clear_cache();
diff --git ml-explore/mlx/mlx/backend/metal/allocator.h Layr-Labs/mlx/mlx/backend/metal/allocator.h index 885951364e52cd93a82ab05b59839cc38875a5bb..b184944224c622765aaebb95680b95b2b36de756 100644 --- ml-explore/mlx/mlx/backend/metal/allocator.h +++ Layr-Labs/mlx/mlx/backend/metal/allocator.h @@ -9,6 +9,7 @@ #include "mlx/allocator.h" #include "mlx/backend/common/buffer_cache.h" #include "mlx/backend/metal/device.h" +#include "mlx/memory.h"   namespace mlx::core::metal {   @@ -23,6 +24,9 @@ virtual size_t size(Buffer buffer) const override; virtual Buffer make_buffer(void* ptr, size_t size) override; virtual void release(Buffer buffer) override;   + void install_process_allocation_cap(size_t bytes); + ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); + MemorySnapshot get_memory_snapshot(); size_t get_active_memory() { return active_memory_; }; @@ -36,6 +40,17 @@ }; size_t get_cache_memory() { return buffer_cache_.cache_size(); }; + // Live Metal resource (buffer) COUNT and its hard ceiling. The count limit + // (default iogpu.rsrc_limit, ~499000) is independent of the byte limits and + // is what malloc() throws on when reached; exposed so callers can observe and + // bound it (it can be far higher than byte usage implies when many tiny + // buffers accumulate in the cache). + size_t get_num_resources() { + return num_resources_; + }; + size_t get_resource_limit() { + return resource_limit_; + }; size_t set_cache_limit(size_t limit); size_t set_memory_limit(size_t limit); size_t get_memory_limit(); @@ -72,6 +87,22 @@ size_t wired_limit_{0}; size_t num_resources_{0}; size_t resource_limit_{0};   + // Count-aware cache-reclaim high-water mark (Darkbloom): when num_resources_ + // reaches resource_high_water_num_/den_ of resource_limit_ (90%), malloc() + // proactively clears the (pure-reuse) buffer cache so the resource COUNT can + // never reach resource_limit_ and throw, regardless of buffer-byte sizes. + // Integer fraction to avoid float work in the allocation hot path. + static constexpr size_t resource_high_water_num_ = 9; + static constexpr size_t resource_high_water_den_ = 10; + + Buffer malloc_capped(size_t size, std::unique_lock<std::mutex>& lock); + void relinquish_capped(MTL::Buffer* buffer, bool cached); + std::shared_ptr<allocator::ProcessAllocationCap> cap_{ + std::make_shared<allocator::ProcessAllocationCap>()}; + bool cap_installed_{false}; + bool buffer_allocation_attempted_{false}; + std::map<MTL::Buffer*, std::shared_ptr<allocator::ProcessBackingLease>> + capped_buffers_; std::mutex mutex_; };
diff --git ml-explore/mlx/mlx/backend/metal/resident.cpp Layr-Labs/mlx/mlx/backend/metal/resident.cpp index 26ab718e31f12304c7b088394847a9cbf9353e8e..bb4d7c2500c17c145f9d97d8a4edbc0e1b9b55d9 100644 --- ml-explore/mlx/mlx/backend/metal/resident.cpp +++ Layr-Labs/mlx/mlx/backend/metal/resident.cpp @@ -181,8 +181,20 @@ // set, and is added to one by resize() if the limit is raised later. if (total_wired_ + bytes > capacity_) { return; } - uint32_t idx = add_to_set_locked(buf, it->second); - sets_[idx].set->commit(); + try { + uint32_t idx = add_to_set_locked(buf, it->second); + sets_[idx].set->commit(); + } catch (...) { + // Registration must not leave a pointer to a buffer the caller will + // release. + if (it->second.set_id != kNoSet) { + const uint32_t idx = it->second.set_id; + remove_from_set_locked(buf, it->second); + sets_[idx].set->commit(); + } + buf_to_set_.erase(it); + throw; + } }   void ResidencySets::erase(MTL::Allocation* buf) {
diff --git ml-explore/mlx/mlx/backend/no_gpu/allocator.cpp Layr-Labs/mlx/mlx/backend/no_gpu/allocator.cpp index a800e381a722754289b35c5a41b59676d6463bc4..06f9bcd79df1eb3455d0c9ba42708331e3b29172 100644 --- ml-explore/mlx/mlx/backend/no_gpu/allocator.cpp +++ Layr-Labs/mlx/mlx/backend/no_gpu/allocator.cpp @@ -41,6 +41,11 @@ virtual Buffer malloc(size_t size) override; virtual void free(Buffer buffer) override; virtual size_t size(Buffer buffer) const override;   + MemorySnapshot get_memory_snapshot() const { + std::lock_guard lock(mutex_); + return {active_memory_, buffer_cache_.cache_size(), peak_memory_}; + } + size_t get_active_memory() const { return active_memory_; }; @@ -184,6 +189,21 @@ }   } // namespace allocator   +AllocationFootprintPolicy get_allocation_footprint_policy() noexcept { + return {1, 0, 0, 0, 4096}; +} + +size_t get_allocation_size_upper_bound(size_t size) { + size_t result; + if (!get_allocation_footprint_policy().upper_bound(size, result)) { + throw std::overflow_error("allocation footprint overflow"); + } + return result; +} + +MemorySnapshot get_memory_snapshot() { + return allocator::common_allocator().get_memory_snapshot(); +} size_t get_active_memory() { return allocator::common_allocator().get_active_memory(); } @@ -193,6 +213,15 @@ } void reset_peak_memory() { return allocator::common_allocator().reset_peak_memory(); } +void install_process_allocation_cap(size_t) { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + throw std::runtime_error( + "process allocation cap unsupported on this backend"); +} + size_t set_memory_limit(size_t limit) { return allocator::common_allocator().set_memory_limit(limit); } @@ -202,6 +231,12 @@ }   size_t get_cache_memory() { return allocator::common_allocator().get_cache_memory(); +} +size_t get_num_resources() { + return 0; +} +size_t get_resource_limit() { + return 0; } size_t set_cache_limit(size_t limit) { return allocator::common_allocator().set_cache_limit(limit);
diff --git ml-explore/mlx/mlx/memory.h Layr-Labs/mlx/mlx/memory.h index 14c099f1be4bdb476748bd391e3a7804f75964f8..6f2cde8889bb25a472eb2acb30c3e72ab107637b 100644 --- ml-explore/mlx/mlx/memory.h +++ Layr-Labs/mlx/mlx/memory.h @@ -2,14 +2,99 @@ // Copyright © 2025-2026 Apple Inc.   #pragma once   +#include <algorithm> #include <cstdlib> +#include <limits> #include <vector>   #include "mlx/api.h" #include "mlx/array.h" +#include "mlx/backend/common/process_allocation_cap.h"   namespace mlx::core {   +using ProcessAllocationCapSnapshot = allocator::ProcessAllocationCapSnapshot; +// One-way, pristine-allocator installation. Not a whole-process/host limit. +MLX_API void install_process_allocation_cap(size_t bytes); +MLX_API ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot(); + +struct MemorySnapshot { + size_t active_memory; + size_t cache_memory; + size_t peak_memory; +}; + +/* Read allocator accounting under one lock. This does not synchronize streams + * or include allocations that have not entered allocator accounting yet. */ +MLX_API MemorySnapshot get_memory_snapshot(); + +/* Bound one allocator buffer, including alignment and larger cache reuse. + * This does not allocate, synchronize, or inspect the live buffer cache. */ +MLX_API size_t get_allocation_size_upper_bound(size_t size); + +// A detached value: evaluating bounds requires no allocator, error callback, +// exception, lock, or allocation. Capture once before entering admission locks. +struct AllocationFootprintPolicy { + size_t alignment; + size_t rounding_threshold; + size_t minimum_allocation; + size_t power_of_two_below; + size_t cache_page_size; + + bool upper_bound(size_t size, size_t& result) const noexcept { + if (size == 0) { + result = 0; + return true; + } + if (alignment == 0 || cache_page_size == 0) { + return false; + } + size = std::max(size, minimum_allocation); + if (power_of_two_below && size < power_of_two_below) { + size_t rounded = 1; + while (rounded < size) { + if (!add(rounded, rounded, rounded)) { + return false; + } + } + size = rounded; + } else if (size > rounding_threshold) { + auto remainder = size % alignment; + if (remainder && !add(size, alignment - remainder, size)) { + return false; + } + } + size_t two_pages; + return add(cache_page_size, cache_page_size, two_pages) && + add(size, std::min(size - 1, two_pages - 1), result); + } + + // For any positive n with a valid bound, B(n) <= n + this overhead. + bool maximum_extra_bytes(size_t& result) const noexcept { + if (alignment == 0 || cache_page_size == 0) { + return false; + } + auto normalization = std::max( + {alignment - 1, + minimum_allocation ? minimum_allocation - 1 : 0, + power_of_two_below ? power_of_two_below - 1 : 0}); + size_t two_pages; + return add(cache_page_size, cache_page_size, two_pages) && + add(normalization, two_pages - 1, result); + } + + private: + static bool add(size_t a, size_t b, size_t& result) noexcept { + if (b > std::numeric_limits<size_t>::max() - a) { + return false; + } + result = a + b; + return true; + } +}; + +MLX_API AllocationFootprintPolicy get_allocation_footprint_policy() noexcept; + /* Get the actively used memory in bytes. * * Note, this will not always match memory use reported by the system because @@ -42,6 +127,21 @@ * The cache includes memory not currently used that has not been returned * to the system allocator. * */ MLX_API size_t get_cache_memory(); + +/* Get the number of live Metal resources (buffers). + * + * This is a COUNT, independent of byte usage. The Metal backend throws when it + * reaches the resource limit (see get_resource_limit). Many small cached + * buffers can push this count high while byte usage stays low. + * */ +MLX_API size_t get_num_resources(); + +/* Get the hard ceiling on the number of live Metal resources (buffers). + * + * Defaults to the iogpu.rsrc_limit sysctl (~499000 when unset). Allocation + * throws once get_num_resources() reaches this value. + * */ +MLX_API size_t get_resource_limit();   /* Set the memory limit. * The memory limit is a guideline for the maximum amount of memory to use
diff --git ml-explore/mlx/tests/allocator_tests.cpp Layr-Labs/mlx/tests/allocator_tests.cpp index 1fff8d8cc94311557fb2359e2b4a847c5dc981de..5d46c9f228583c4ca53aabfed01f7e8a2c858239 100644 --- ml-explore/mlx/tests/allocator_tests.cpp +++ Layr-Labs/mlx/tests/allocator_tests.cpp @@ -1,7 +1,9 @@ // Copyright © 2023-2026 Apple Inc.   +#include <atomic> #include <chrono> #include <future> +#include <limits> #include <memory> #include <stdexcept> #include <thread> @@ -138,3 +140,131 @@ clear_thread.join();   set_cache_limit(old_limit); } + +TEST_CASE("test coherent memory snapshot during cache transfers") { + auto old_limit = set_cache_limit(1 << 20); + clear_cache(); + auto live = allocator::allocator().malloc(32768); + auto moving = allocator::allocator().malloc(65536); + auto moving_bytes = allocator::allocator().size(moving); + auto active = get_memory_snapshot(); + allocator::allocator().free(moving); + auto cached = get_memory_snapshot(); + CHECK_EQ(active.active_memory, cached.active_memory + moving_bytes); + CHECK_EQ(active.cache_memory + moving_bytes, cached.cache_memory); + CHECK_EQ(active.peak_memory, cached.peak_memory); + auto total = cached.active_memory + cached.cache_memory; + + std::atomic<bool> stop{false}; + std::promise<void> started; + auto started_future = started.get_future(); + auto churn = std::async(std::launch::async, [&] { + started.set_value(); + size_t transfers = 0; + do { + auto buffer = allocator::allocator().malloc(65536); + allocator::allocator().free(buffer); + ++transfers; + } while (!stop.load(std::memory_order_relaxed)); + return transfers; + }); + started_future.wait(); + + size_t inconsistent = 0; + for (int i = 0; i < 20000; ++i) { + auto snapshot = get_memory_snapshot(); + inconsistent += snapshot.active_memory + snapshot.cache_memory != total; + inconsistent += snapshot.active_memory > snapshot.peak_memory; + } + stop.store(true, std::memory_order_relaxed); + CHECK_GT(churn.get(), 0); + CHECK_EQ(inconsistent, 0); + + allocator::allocator().free(live); + clear_cache(); + set_cache_limit(old_limit); +} + +TEST_CASE("test memory snapshot does not wait for stream work") { + std::promise<void> started; + auto started_future = started.get_future(); + std::promise<void> release; + auto release_future = release.get_future().share(); + auto stream = new_stream(Device{Device::cpu}); + scheduler::enqueue(stream, [&] { + started.set_value(); + release_future.wait(); + }); + started_future.wait(); + + auto snapshot = + std::async(std::launch::async, [] { return get_memory_snapshot(); }); + auto status = snapshot.wait_for(std::chrono::seconds(1)); + release.set_value(); + synchronize(stream); + (void)snapshot.get(); + CHECK_EQ(status, std::future_status::ready); +} + +TEST_CASE("allocation footprint bounds fresh and cached buffer owners") { + auto old_limit = set_cache_limit(1 << 20); + clear_cache(); + for (size_t size : {size_t(4), size_t(6000), size_t(24576), size_t(65536)}) { + auto bound = get_allocation_size_upper_bound(size); + CHECK_GE(bound, size); + auto buffer = allocator::allocator().malloc(size); + CHECK_LE(allocator::allocator().size(buffer), bound); + allocator::allocator().free(buffer); + } + clear_cache(); + auto large = allocator::allocator().malloc(49152); + auto larger_bytes = allocator::allocator().size(large); + allocator::allocator().free(large); + auto reused = allocator::allocator().malloc(32768); + CHECK_LE( + allocator::allocator().size(reused), + get_allocation_size_upper_bound(32768)); + CHECK_GE(larger_bytes, 49152); + allocator::allocator().free(reused); + clear_cache(); + set_cache_limit(old_limit); +} + +TEST_CASE("allocation prediction does not change allocator counters") { + auto before = get_memory_snapshot(); + CHECK_GE(get_allocation_size_upper_bound(24576), 24576); + CHECK_EQ(get_allocation_size_upper_bound(0), 0); + CHECK_THROWS( + get_allocation_size_upper_bound(std::numeric_limits<size_t>::max())); + auto after = get_memory_snapshot(); + CHECK_EQ(after.active_memory, before.active_memory); + CHECK_EQ(after.cache_memory, before.cache_memory); + CHECK_EQ(after.peak_memory, before.peak_memory); +} + +TEST_CASE( + "detached allocation policies preserve backend size classes without exceptions") { + const AllocationFootprintPolicy cpu{1, 0, 0, 0, 4096}; + const AllocationFootprintPolicy metal{16384, 16384, 0, 0, 16384}; + const AllocationFootprintPolicy cuda{16384, 0, 8, 16384, 16384}; + size_t result = 0; + CHECK(cpu.upper_bound(24576, result)); + CHECK_EQ(result, 32767); + CHECK(metal.upper_bound(24576, result)); + CHECK_EQ(result, 65535); + CHECK(cuda.upper_bound(1, result)); + CHECK_EQ(result, 15); + CHECK(cuda.upper_bound(8193, result)); + CHECK_EQ(result, 32767); + for (auto p : {cpu, metal, cuda}) { + size_t extra = 0; + REQUIRE(p.maximum_extra_bytes(extra)); + for (size_t n : + {1, 4, 8191, 8192, 8193, 16383, 16384, 16385, 24576, 65537}) { + REQUIRE(p.upper_bound(n, result)); + CHECK_GE(result, n); + CHECK_LE(result - n, extra); + } + CHECK_FALSE(p.upper_bound(std::numeric_limits<size_t>::max(), result)); + } +}
diff --git ml-explore/mlx/tests/standalone/process_allocation_cap.cpp Layr-Labs/mlx/tests/standalone/process_allocation_cap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1500baac9dcd83a4d335afbb6a3380cca6cd564f --- /dev/null +++ Layr-Labs/mlx/tests/standalone/process_allocation_cap.cpp @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. +#include "mlx/backend/common/process_allocation_cap.h" +#include <Block.h> +#include <sys/mman.h> +#include <unistd.h> +#include <atomic> +#include <cassert> +#include <iostream> +#include <thread> +#include <vector> +#include "mlx/backend/common/allocation_footprint.h" + +using namespace mlx::core::allocator; +using Cap = ProcessAllocationCap; +using Lease = ProcessBackingLease; + +template <typename F> +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + assert(refused); +} +void invariant(const Cap& cap) { + auto s = cap.snapshot(); + assert( + s.charged_bytes == + s.heap_bytes + s.live_bytes + s.cached_bytes + s.pending_bytes + + s.unreclaimed_bytes); + assert(s.charged_bytes <= s.peak_bytes && s.peak_bytes <= s.limit_bytes); +} +std::atomic<int> releases{0}; +bool unmap(void* p, size_t n) { + ++releases; + return munmap(p, n) == 0; +} + +using Callback = void (^)(); +Callback retainedCallback(std::shared_ptr<Lease> lease) { + return Block_copy(^{ + lease->finish(); + }); +} + +int main() { + const size_t page = static_cast<size_t>(getpagesize()); + { + Cap c; + refuses([&] { c.install(0, 0); }); + refuses([&] { c.install(3, 4); }); + assert(!c.snapshot().installed); + c.install(16, 4); + refuses([&] { c.install(32, 4); }); + c.reserve(12); + refuses([&] { c.reserve(1); }); + c.failed_before_acquisition(12); + assert(c.snapshot().charged_bytes == 4); + invariant(c); + Cap huge; + huge.install(SIZE_MAX, SIZE_MAX - 1); + huge.reserve(1); + refuses([&] { huge.reserve(SIZE_MAX); }); + huge.failed_before_acquisition(1); + invariant(huge); + refuses([&] { round_allocation_size(SIZE_MAX, page); }); + } + { + auto c = std::make_shared<Cap>(); + c->install(4 * page, page); + // Real VM backing, real copied Blocks ABI; no Metal/device initialization. + for (int i = 0; i < 1000; ++i) { + auto lease = std::make_shared<Lease>(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + lease->attach(p, unmap); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->cache(); + lease->reuse(); + lease->retire(); + lease.reset(); + assert(c->snapshot().unreclaimed_bytes == page); + assert(c->snapshot().charged_bytes == 2 * page); + callback(); + callback(); // defensive idempotence; unmap exactly once + Block_release(callback); + assert(c->snapshot().charged_bytes == page); + invariant(*c); + } + assert( + releases == 1000); // Churn does not accumulate a fake high-water cap. + } + { + auto c = std::make_shared<Cap>(); + c->install(page, 0); + auto lease = std::make_shared<Lease>(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + refuses( + [&] { Lease next(c, 1); }); // retained Metal equivalent blocks refund + std::thread completion([&] { callback(); }); + completion.join(); + Block_release(callback); + Lease next(c, page); // delayed completion makes capacity reusable + invariant(*c); + } + { + auto c = std::make_shared<Cap>(); + c->install(page, 0); + { + Lease failed(c, page); + } // no VM acquired + assert(c->snapshot().charged_bytes == 0); + auto failed = std::make_shared<Lease>(c, page); + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(p != MAP_FAILED); + failed->attach(p, unmap); + failed->finish(); // Metal constructor returned nil after VM acquisition + failed.reset(); + assert(c->snapshot().charged_bytes == 0 && releases == 1001); + Lease quarantine(c, page); + quarantine.attach(nullptr, [](void*, size_t) { return false; }); + quarantine.acquired(); + quarantine.retire(); + quarantine.finish(); + assert(c->snapshot().unreclaimed_bytes == page); + refuses([&] { Lease next(c, 1); }); + invariant(*c); + } + { + auto c = std::make_shared<Cap>(); + c->install(page, 0); + // Foreign pages stay caller-owned even after callback and ledger refund. + auto* p = static_cast<unsigned char*>(mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + assert(p != MAP_FAILED); + p[0] = 42; + { + Lease wrapper(c, page); + wrapper.acquired(); + wrapper.retire(); + wrapper.finish(); + } + assert(p[0] == 42 && c->snapshot().charged_bytes == 0); + assert(munmap(p, page) == 0); + } + { + auto c = std::make_shared<Cap>(); + c->install(1, 0); + std::atomic<int> arrived{0}, successes{0}; + std::atomic<bool> release{false}; + std::vector<std::thread> threads; + for (int i = 0; i < 2; ++i) { + threads.emplace_back([&] { + std::shared_ptr<Lease> lease; + try { + lease = std::make_shared<Lease>(c, 1); + ++successes; + } catch (...) { + } + ++arrived; + while (!release) { + std::this_thread::yield(); + } + }); + } + while (arrived != 2) { + std::this_thread::yield(); + } + assert(successes == 1 && c->snapshot().pending_bytes == 1); + release = true; + for (auto& t : threads) { + t.join(); + } + assert(c->snapshot().charged_bytes == 0); + invariant(*c); + } + { + auto c = std::make_shared<Cap>(); + c->install(page, 0); + std::weak_ptr<Cap> weak = c; + auto lease = std::make_shared<Lease>(c, page); + auto callback = retainedCallback(lease); + lease->acquired(); + lease->retire(); + lease.reset(); + c.reset(); + assert(!weak.expired()); + callback(); + Block_release(callback); + assert(weak.expired()); // callback owns ledger, not an allocator stack + // reference + } + std::cout + << "PASS: install/overflow, 1000 VM churn cycles, delayed copied block, " + "failure rollback/quarantine, foreign ownership, concurrent reserve, ledger lifetime\n"; +}
diff --git ml-explore/mlx/tests/standalone/process_allocation_cap_metal.cpp Layr-Labs/mlx/tests/standalone/process_allocation_cap_metal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d86b3b049ed5e49da62760384e828e0e13d81c1 --- /dev/null +++ Layr-Labs/mlx/tests/standalone/process_allocation_cap_metal.cpp @@ -0,0 +1,590 @@ +// Copyright © 2026 Eigen Labs. +#include <mach/mach.h> +#include <objc/runtime.h> +#include <sys/mman.h> +#include <unistd.h> +#include <array> +#include <atomic> +#include <cassert> +#include <chrono> +#include <condition_variable> +#include <iostream> +#include <string> +#include <thread> +#include "mlx/allocator.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" + +using namespace mlx::core; +namespace a = mlx::core::allocator; +void require(bool value, const char* what) { + if (!value) { + throw std::runtime_error(what); + } +} +template <typename F> +void refuses(F f) { + bool refused = false; + try { + f(); + } catch (const std::exception&) { + refused = true; + } + require(refused, "required refusal did not occur"); +} +auto snapshot() { + return get_process_allocation_cap_snapshot(); +} +// The allocator makes no fixed heap on a virtual GPU, such as the one of a +// GitHub-hosted macOS runner (metal/allocator.cpp). +bool paravirtual() { + return std::get<std::string>(gpu::device_info(0).at("device_name")) == + "Apple Paravirtual device"; +} +void settled(size_t expected) { + for (int i = 0; i < 200 && snapshot().charged_bytes != expected; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require( + snapshot().charged_bytes == expected, "callback credit did not settle"); +} + +// Process-local Metal API interception; no production failure switches. +IMP original_no_copy = nullptr; +IMP original_allocate = nullptr; +IMP original_residency = nullptr; +MTL::Buffer* retained_failure_buffer = nullptr; +bool reject_no_copy = false; +MTL::Buffer* intercept_no_copy( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + if (reject_no_copy) { + reject_no_copy = false; + return nullptr; + } + auto fn = reinterpret_cast<MTL::Buffer* (*)(id, + SEL, + void*, + NS::UInteger, + MTL::ResourceOptions, + void (^)(void*, NS::UInteger))>( + original_no_copy); + auto* b = fn(self, selector, p, n, opts, cleanup); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::Buffer* intercept_allocate( + id self, + SEL selector, + NS::UInteger n, + MTL::ResourceOptions opts) { + auto fn = reinterpret_cast< + MTL::Buffer* (*)(id, SEL, NS::UInteger, MTL::ResourceOptions)>( + original_allocate); + auto* b = fn(self, selector, n, opts); + if (b) { + b->retain(); + retained_failure_buffer = b; + } + return b; +} +MTL::ResidencySet* +fail_residency(id, SEL, MTL::ResidencySetDescriptor*, NS::Error**) { + throw std::bad_alloc(); // insert has already added its map entry +} +struct Intercept { + Method method; + IMP previous; + Intercept(MTL::Device* device, const char* selector, IMP replacement) + : method(class_getInstanceMethod( + object_getClass(reinterpret_cast<id>(device)), + sel_registerName(selector))), + previous(nullptr) { + require(method != nullptr, "Metal interception selector missing"); + previous = method_setImplementation(method, replacement); + } + ~Intercept() { + method_setImplementation(method, previous); + } +}; + +struct PendingMetalConstruction { + std::mutex mutex; + std::condition_variable changed; + size_t entered{0}; + bool complete{false}; + std::array<MTL::Buffer*, 2> retained{nullptr, nullptr}; + IMP original{nullptr}; +}; +PendingMetalConstruction* pending_construction = nullptr; +MTL::Buffer* intercept_pending( + id self, + SEL selector, + void* p, + NS::UInteger n, + MTL::ResourceOptions opts, + void (^cleanup)(void*, NS::UInteger)) { + auto& state = *pending_construction; + auto fn = reinterpret_cast<MTL::Buffer* (*)(id, + SEL, + void*, + NS::UInteger, + MTL::ResourceOptions, + void (^)(void*, NS::UInteger))>( + state.original); + // Construct real Metal buffers before holding their return to the allocator. + auto* buffer = fn(self, selector, p, n, opts, cleanup); + std::unique_lock lock(state.mutex); + const auto index = state.entered++; + if (index < state.retained.size() && buffer) { + buffer->retain(); + state.retained[index] = buffer; + } + state.changed.notify_all(); + if (index < state.retained.size()) { + state.changed.wait(lock, [&] { return state.complete; }); + } + return buffer; +} +void concurrent_case(size_t page) { + auto& device = metal::device(Device::gpu); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + set_cache_limit(0); + const auto heap = snapshot().heap_bytes; + const auto chunk = (cap - heap) / 2; + require( + chunk % page == 0 && chunk * 2 + heap == cap, + "nonintegral test envelope"); + PendingMetalConstruction state; + pending_construction = &state; + std::array<a::Buffer, 2> buffers{a::Buffer(nullptr), a::Buffer(nullptr)}; + std::array<std::exception_ptr, 2> errors; + bool both_pending = false, contender_refused = false; + ProcessAllocationCapSnapshot pending_snapshot; + size_t actual_bytes = 0; + a::Buffer contender(nullptr); + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast<IMP>(intercept_pending)); + state.original = hook.previous; + std::array<std::thread, 2> workers; + for (size_t i = 0; i < workers.size(); ++i) { + workers[i] = std::thread([&, i] { + try { + buffers[i] = a::allocator().malloc(chunk); + } catch (...) { + errors[i] = std::current_exception(); + } + }); + } + { + std::unique_lock lock(state.mutex); + both_pending = state.changed.wait_for( + lock, std::chrono::seconds(5), [&] { return state.entered == 2; }); + if (both_pending && state.retained[0] && state.retained[1]) { + actual_bytes = + state.retained[0]->length() + state.retained[1]->length(); + } + } + pending_snapshot = snapshot(); + if (both_pending) { + try { + contender = a::allocator().malloc(page); + } catch (const std::exception&) { + contender_refused = true; + } + } + { + std::lock_guard lock(state.mutex); + state.complete = true; + } + state.changed.notify_all(); + for (auto& worker : workers) { + worker.join(); + } + } + pending_construction = nullptr; + require( + both_pending, + "allocator did not allow two real in-flight Metal allocations"); + require(!errors[0] && !errors[1], "real Metal construction failed"); + require(actual_bytes + heap == cap, "unexpected actual Metal backing total"); + require( + pending_snapshot.pending_bytes == 2 * chunk && + pending_snapshot.charged_bytes == cap && + pending_snapshot.live_bytes == 0, + "in-flight Metal backing was not reserved before completion"); + require( + contender_refused && !contender.ptr() && state.entered == 2, + "contender reached Metal despite exhausted pending budget"); + require( + snapshot().peak_bytes == cap && snapshot().pending_bytes == 0 && + snapshot().live_bytes == 2 * chunk, + "pending-to-live transfer changed cap charge"); + for (auto buffer : buffers) { + a::allocator().free(buffer); + } + clear_cache(); + require( + snapshot().unreclaimed_bytes == 2 * chunk && + snapshot().charged_bytes == cap, + "allocator release refunded externally retained Metal backing"); + refuses([&] { a::allocator().malloc(page); }); + state.retained[0]->release(); + settled(heap + chunk); + auto recovered = a::allocator().malloc(chunk); + require( + snapshot().charged_bytes == cap && snapshot().peak_bytes == cap, + "callback recovery failed exact-cap replacement"); + a::allocator().free(recovered); + clear_cache(); + settled(heap + chunk); + state.retained[1]->release(); + settled(heap); + require( + snapshot().pending_bytes == 0 && snapshot().unreclaimed_bytes == 0, + "concurrent allocation left stranded charges"); +} +void failure_case(const std::string& mode, size_t page) { + const bool capped = mode.find("ordinary") == std::string::npos; + const bool foreign = mode.find("foreign") != std::string::npos; + auto& device = metal::device(Device::gpu); + auto& sets = device.residency_sets(); + (void)snapshot(); // initialize allocator and its fixed heap + if (capped) { + install_process_allocation_cap(8 << 20); + } + const auto baseline = capped ? snapshot().charged_bytes : 0; + set_cache_limit(0); + if (mode == "nil-foreign") { + void* p = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(p != MAP_FAILED, "foreign map failed"); + int deleter_calls = 0; + bool threw = false; + { + Intercept hook( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast<IMP>(intercept_no_copy)); + original_no_copy = hook.previous; + reject_no_copy = true; + try { + array foreign_array( + p, {static_cast<int>(page / sizeof(float))}, float32, [&](void*) { + ++deleter_calls; + }); + } catch (const std::exception&) { + threw = true; + } + } + require(munmap(p, page) == 0, "caller unmap failed"); + require(threw, "nil wrapper silently copied instead of throwing"); + require(deleter_calls == 0, "failed wrapper invoked caller deleter"); + settled(baseline); + return; + } + set_wired_limit(8 << 20); + sets.set_max_bytes_per_set(page); + require(sets.enabled(), "residency sets are disabled on this device"); + // The failure is injected where a new residency set is made. Fill one set + // with a page first, so that the next page needs a new set. On a device with + // the fixed heap, set 0 holds the heap and the filler gets a new set; on a + // device without it, the filler goes into the empty set 0. + auto filler = a::allocator().malloc(page); + const auto filled = capped ? snapshot().charged_bytes : 0; + const auto wired = sets.wired_size(); + const auto resources = get_num_resources(); + const auto active = get_active_memory(); + void* foreign_pages = nullptr; + if (foreign) { + foreign_pages = mmap( + nullptr, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + require(foreign_pages != MAP_FAILED, "foreign map failed"); + } + { + Intercept no_copy( + device.mtl_device(), + "newBufferWithBytesNoCopy:length:options:deallocator:", + reinterpret_cast<IMP>(intercept_no_copy)); + original_no_copy = no_copy.previous; + Intercept allocated( + device.mtl_device(), + "newBufferWithLength:options:", + reinterpret_cast<IMP>(intercept_allocate)); + original_allocate = allocated.previous; + Intercept registration( + device.mtl_device(), + "newResidencySetWithDescriptor:error:", + reinterpret_cast<IMP>(fail_residency)); + original_residency = registration.previous; + refuses([&] { + if (foreign) { + (void)a::make_buffer(foreign_pages, page); + } else { + (void)a::allocator().malloc(page); + } + }); + } + require( + retained_failure_buffer != nullptr, + "failure did not reach allocated buffer"); + // Keep the object alive to diagnose stale registration without dereferencing + // freed memory. On the broken path resize wires this failed allocation. + set_wired_limit((8 << 20) + page); + require( + sets.wired_size() == wired, + "failed insert left a tracked Metal allocation"); + require( + get_num_resources() == resources && get_active_memory() == active, + "failed registration changed allocator counters"); + if (capped) { + require( + snapshot().charged_bytes == filled + page, + "retained failure refunded early"); + } + require( + retained_failure_buffer->retainCount() == 1, + "allocator leaked failed buffer reference"); + retained_failure_buffer->release(); + retained_failure_buffer = nullptr; + if (capped) { + settled(filled); + } + if (foreign) { + require(munmap(foreign_pages, page) == 0, "foreign pages lost ownership"); + } + a::allocator().free(filler); + clear_cache(); + if (capped) { + settled(baseline); + } +} +// Capped backing is owned no-copy VM. Pages first written by the GPU must +// still be charged to this process, or the OS cannot see the model's memory. +size_t physical_footprint() { + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + require( + task_info( + mach_task_self(), + TASK_VM_INFO, + reinterpret_cast<task_info_t>(&info), + &count) == KERN_SUCCESS, + "task footprint unavailable"); + return static_cast<size_t>(info.phys_footprint); +} + +bool footprint_growth_at_least(size_t before, size_t after, size_t expected) { + return after >= before && after - before >= expected; +} + +void footprint_delta_case() { + require( + !footprint_growth_at_least(1024, 1023, 512), + "decrease wrapped into growth"); + require( + !footprint_growth_at_least(1024, 1024, 1), "unchanged footprint grew"); + require(!footprint_growth_at_least(1024, 1535, 512), "short growth passed"); + require(footprint_growth_at_least(1024, 1536, 512), "exact growth failed"); + require( + !footprint_growth_at_least(SIZE_MAX, 0, 1), "maximum baseline wrapped"); +} + +void gpu_footprint_case() { + const size_t bytes = size_t(512) << 20; + install_process_allocation_cap(size_t(2) << 30); + const auto before = physical_footprint(); + { + auto filled = + full({int(bytes / sizeof(float))}, 1.0f, float32, Device::gpu); + eval(filled); + synchronize(default_stream(Device::gpu)); + const auto after = physical_footprint(); + require( + footprint_growth_at_least(before, after, bytes - (bytes >> 4)), + "GPU-written capped backing missing from process footprint"); + } + clear_cache(); +} + +int main(int argc, char** argv) { + try { + require(argc == 2, "one fresh-process case required"); + const std::string mode = argv[1]; + const size_t page = static_cast<size_t>(getpagesize()); + // Facts of the device that decide which paths the cases take. + std::cout << "device: " + << std::get<std::string>(gpu::device_info(0).at("device_name")) + << ", residency sets: " + << (metal::device(Device::gpu).residency_sets().enabled() + ? "enabled" + : "disabled") + << '\n'; + if (mode == "footprint-delta") { + footprint_delta_case(); + } else if (mode == "gpu-footprint") { + gpu_footprint_case(); + } else if (mode == "concurrent") { + concurrent_case(page); + } else if ( + mode.find("registration-") == 0 && + !metal::device(Device::gpu).residency_sets().enabled()) { + // These cases inject a failure into the creation of a residency set. + // Without residency sets (no Metal 3 GPU family or macOS < 15, as on a + // virtual GPU) the allocator registers nothing, so the path under test + // does not exist. Exit code 77 is SKIP_RETURN_CODE in + // tests/CMakeLists.txt. + std::cout << "SKIP " << mode + << ": residency sets are disabled on this device\n"; + return 77; + } else if (mode.find("registration-") == 0 || mode == "nil-foreign") { + failure_case(mode, page); + } else if (mode == "late") { + auto b = a::allocator().malloc(page); + a::allocator().free(b); + clear_cache(); + refuses([] { install_process_allocation_cap(8 << 20); }); + require(!snapshot().installed, "late install mutated state"); + } else { + // The allocator's fixed heap is created when queried, before + // installation. + require(!snapshot().installed, "process already capped"); + const size_t cap = 8 << 20; + install_process_allocation_cap(cap); + const auto baseline = snapshot(); + const auto heap = baseline.heap_bytes; + require((heap > 0) == !paravirtual(), "fixed heap does not match device"); + require(baseline.charged_bytes == heap, "existing heap not charged"); + require(baseline.limit_bytes == cap, "wrong cap"); + if (mode == "install") { + refuses([&] { install_process_allocation_cap(cap); }); + refuses([&] { install_process_allocation_cap(cap + page); }); + require(snapshot().limit_bytes == cap, "limit changed"); + refuses([] { a::allocator().malloc(SIZE_MAX); }); + require( + snapshot().charged_bytes == heap, "overflow leaked reservation"); + auto exact = a::allocator().malloc(cap - heap); + require(snapshot().charged_bytes == cap, "exact fill mismatch"); + refuses([&] { a::allocator().malloc(page); }); + a::allocator().free(exact); + clear_cache(); + settled(heap); + } else if (mode == "retained") { + auto b = a::allocator().malloc(cap - heap); + auto* metal = static_cast<MTL::Buffer*>(b.ptr()); + metal->retain(); + a::allocator().free(b); + clear_cache(); + require( + snapshot().unreclaimed_bytes == cap - heap, + "release refunded early"); + require(snapshot().charged_bytes == cap, "extra reference lost charge"); + refuses([&] { a::allocator().malloc(page); }); + metal->release(); + settled(heap); + auto replacement = a::allocator().malloc(cap - heap); + a::allocator().free(replacement); + clear_cache(); + settled(heap); + } else if (mode == "churn") { + auto tiny = a::allocator().malloc(8); + const bool from_heap = + static_cast<MTL::Buffer*>(tiny.ptr())->heap() != nullptr; + require( + from_heap == (heap > 0), "fixed heap use does not match device"); + // A small buffer from the heap adds no charge. Without the heap it is + // a capped buffer of its own, charged one page. + require( + snapshot().charged_bytes == heap + (from_heap ? 0 : page), + "small buffer charge wrong"); + a::allocator().free(tiny); + clear_cache(); + settled(heap); + for (size_t i = 0; i < 1000; ++i) { + const auto size = page * (1 + i % 31); + auto b = a::allocator().malloc(size); + const auto bytes = snapshot().charged_bytes; + auto pointer = b.ptr(); + a::allocator().free(b); + require( + snapshot().cached_bytes > 0 && snapshot().charged_bytes == bytes, + "cache transfer refunded credit"); + auto reused = a::allocator().malloc(size); + require( + reused.ptr() == pointer && snapshot().charged_bytes == bytes, + "cache reuse allocated new backing"); + a::allocator().free(reused); + clear_cache(); + settled(heap); + } + require(snapshot().peak_bytes < cap, "churn accumulated backing"); + } else if (mode == "foreign") { + void* p = mmap( + nullptr, + page, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + require(p != MAP_FAILED, "foreign map failed"); + static_cast<unsigned char*>(p)[0] = 42; + auto b = a::make_buffer(p, page); + require(b.ptr() != nullptr, "foreign wrapper failed"); + auto* metal = static_cast<MTL::Buffer*>(b.ptr()); + metal->retain(); + a::release(b); + require( + snapshot().charged_bytes == heap + page, + "foreign wrapper refunded early"); + metal->release(); + settled(heap); + require( + static_cast<unsigned char*>(p)[0] == 42, + "caller pages invalidated"); + refuses([&] { a::make_buffer(static_cast<char*>(p) + 1, page); }); + require(munmap(p, page) == 0, "caller unmap failed"); + } else if (mode == "gpu") { + { + // Real native graph roots stay owned through GPU evaluation and + // readback. + auto input = arange(1024, float32, Device::gpu); + auto output = + add(multiply(input, array(2.0f), Device::gpu), + array(3.0f), + Device::gpu); + async_eval(output); + synchronize(default_stream(Device::gpu)); + for (int i = 0; i < 1024; ++i) { + require( + output.data<float>()[i] == i * 2.0f + 3.0f, + "GPU value mismatch"); + } + require(snapshot().live_bytes > 0, "evaluated roots uncharged"); + } + synchronize(default_stream(Device::gpu)); + clear_cache(); + settled(heap); + } else { + throw std::runtime_error("unknown case"); + } + require(snapshot().pending_bytes == 0, "pending reservation leaked"); + require(snapshot().charged_bytes <= cap, "cap exceeded"); + } + std::cout << "PASS " << mode << '\n'; + return 0; + } catch (const std::exception& e) { + std::cerr << "FAIL " << e.what() << '\n'; + return 1; + } +}

The two-pass vector SDPA cast unnormalized partial sums to the input dtype before combining them: BF16 lost cancellation residuals and FP16 could overflow even when the final output was representable. Partials now stay FP32 through the second pass and only the final result is cast; kernel entry names change so a stale shader cannot silently satisfy the new buffer contract. Python regressions cover cancellation and overflow across D64/D128/D256, 32⁄128 partitions, masked and unmasked. (PR #16)

diff --git ml-explore/mlx/mlx/backend/metal/kernels/scaled_dot_product_attention.metal Layr-Labs/mlx/mlx/backend/metal/kernels/scaled_dot_product_attention.metal index 733c4379151619bcca4eb07983ab47a77ea5f019..482b9f178a2ad72465ce3f0265c6d1a80b4a0873 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/scaled_dot_product_attention.metal +++ Layr-Labs/mlx/mlx/backend/metal/kernels/scaled_dot_product_attention.metal @@ -27,7 +27,7 @@ // SDPA vector instantiations #define instantiate_sdpa_vector_aggregation(type, value_dim) \ instantiate_kernel( \ - "sdpa_vector_2pass_2_" #type "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_2_" #type "_" #value_dim, \ sdpa_vector_2pass_2, \ type, \ value_dim) @@ -40,7 +40,7 @@ type, \ qk_dim, \ value_dim) \ instantiate_kernel( \ - "sdpa_vector_2pass_1_" #type "_" #qk_dim "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_1_" #type "_" #qk_dim "_" #value_dim, \ sdpa_vector_2pass_1, \ type, \ qk_dim, \ @@ -48,7 +48,7 @@ value_dim)   #define instantiate_sdpa_vector_gqa(type, qk_dim, value_dim, g, hpt) \ instantiate_kernel( \ - "sdpa_vector_2pass_1_gqa_" #g "_" #type "_" #qk_dim "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_1_gqa_" #g "_" #type "_" #qk_dim "_" #value_dim, \ sdpa_vector_2pass_1_gqa, \ type, \ qk_dim, \ @@ -82,7 +82,7 @@ instantiate_sdpa_vector_heads(float16_t)   #define instantiate_sdpa_vector_tk1(type, dim) \ instantiate_kernel( \ - "sdpa_vector_2pass_1_" #type "_" #dim "_" #dim "_tk1", \ + "sdpa_vector_2pass_fp32partials_1_" #type "_" #dim "_" #dim "_tk1", \ sdpa_vector_2pass_1, \ type, \ dim, \
diff --git ml-explore/mlx/mlx/backend/metal/kernels/sdpa_vector.h Layr-Labs/mlx/mlx/backend/metal/kernels/sdpa_vector.h index 1d312038ca1fa18900a73f45cd21e996158c0dbc..e1dea06f2b7e98bb9d9674822eab005d6afada39 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/sdpa_vector.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/sdpa_vector.h @@ -182,7 +182,7 @@ [[kernel]] void sdpa_vector_2pass_1( const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], const device T* values [[buffer(2)]], - device T* out [[buffer(3)]], + device float* out [[buffer(3)]], device float* sums [[buffer(4)]], device float* maxs [[buffer(5)]], const constant int& N [[buffer(7)]], @@ -379,7 +379,7 @@ maxs[0] = max_score; }   for (int i = 0; i < v_per_thread; i++) { - out[i] = static_cast<T>(o[i]); + out[i] = o[i]; } }   @@ -393,7 +393,7 @@ [[kernel]] void sdpa_vector_2pass_1_gqa( const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], const device T* values [[buffer(2)]], - device T* out [[buffer(3)]], + device float* out [[buffer(3)]], device float* sums [[buffer(4)]], device float* maxs [[buffer(5)]], const constant int& N [[buffer(7)]], @@ -516,10 +516,10 @@ } }   const int o_offset = base_head + g; - device T* op = + device float* op = out + o_offset * blocks * V + block_idx * V + simd_lid * v_per_thread; for (int i = 0; i < v_per_thread; i++) { - op[i] = static_cast<T>(acc[i]); + op[i] = acc[i]; } if (simd_lid == 0) { sums[o_offset * blocks + block_idx] = denom; @@ -529,7 +529,7 @@ }   template <typename T, int D> [[kernel]] void sdpa_vector_2pass_2( - const device T* partials [[buffer(0)]], + const device float* partials [[buffer(0)]], const device float* sums [[buffer(1)]], const device float* maxs [[buffer(2)]], device T* out [[buffer(3)]],
diff --git ml-explore/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp Layr-Labs/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp index 82c4963ee06e7621fdf593c276bd82c3c47b4e7c..86b5b6df677b005b616ed6180f629474c1e683ca 100644 --- ml-explore/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp +++ Layr-Labs/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp @@ -754,7 +754,7 @@ const std::optional<array>& sinks) { // Set the kernel name std::string kname; kname.reserve(64); - kname += "sdpa_vector_2pass_1"; + kname += "sdpa_vector_2pass_fp32partials_1"; int gqa_factor = q.shape(1) / k.shape(1); bool gqa_dims = (gqa_factor == 8 && (q.shape(-1) == 64 || q.shape(-1) == 128)) || @@ -828,7 +828,8 @@ intermediate_shape.insert( intermediate_shape.end(), out.shape().begin(), out.shape().end() - 1); intermediate_shape.push_back(blocks); intermediate_shape.push_back(out.shape().back()); - array intermediate(intermediate_shape, q.dtype(), nullptr, {}); + // Keep unnormalized partials in float until the final reduction. + array intermediate(intermediate_shape, float32, nullptr, {}); intermediate_shape.pop_back(); array sums(intermediate_shape, float32, nullptr, {}); array maxs(std::move(intermediate_shape), float32, nullptr, {}); @@ -912,7 +913,7 @@ compute_encoder.dispatch_threadgroups(grid_dims, group_dims);   // Final pass kname.clear(); - kname = "sdpa_vector_2pass_2_"; + kname = "sdpa_vector_2pass_fp32partials_2_"; kname += get_type_string(q.dtype()); kname += "_"; kname += std::to_string(v.shape(-1)); @@ -1526,7 +1527,8 @@ if (shape[0] == 1 || shape[1] == 1) { // If either the batch or head dimension is a singleton, the other can // be transposed with the sequence dimension auto bidx = shape[0] == 1 ? 1 : 0; - return (strides[3] == 1) && (strides[2] == shape[3] * shape[bidx]) && + return (strides[3] == 1) && + (strides[2] == static_cast<int64_t>(shape[3]) * shape[bidx]) && (strides[bidx] == shape[3]); } return false;
diff --git ml-explore/mlx/python/tests/test_fast_sdpa.py Layr-Labs/mlx/python/tests/test_fast_sdpa.py index 73170371025335df81ca860f42820c619da266bc..03a2951e015e43bde5e782aa34296d16a7ceb3a1 100644 --- ml-explore/mlx/python/tests/test_fast_sdpa.py +++ Layr-Labs/mlx/python/tests/test_fast_sdpa.py @@ -2,9 +2,11 @@ import math import os import unittest from itertools import product +from unittest.mock import patch   import mlx.core as mx import mlx_tests +import numpy as np   def mlx_ref_attn(q, k, v, scale=1.0, mask=None, sinks=None): @@ -639,6 +641,54 @@ ref = mlx_primitives_sdpa(q, kr, vr, scale) out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4))   + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_two_pass_partial_cancellation(self): + # Uniform attention has the exact output 1 / L. Casting an + # unnormalized block sum to the input dtype loses the residual 1. + L = 8192 + for dtype, D, blocks, masked in product( + (mx.bfloat16, mx.float16, mx.float32), + (64, 128, 256), + (32, 128), + (False, True), + ): + with self.subTest(dtype=dtype, D=D, blocks=blocks, masked=masked): + amplitude = 2048 if dtype == mx.float16 else 256 + values = np.zeros((1, 1, L, D), dtype=np.float32) + values[:, :, 0, :] = amplitude + # D64/D128 without a mask uses contiguous GQA chunks. + gqa = D in (64, 128) and not masked + values[:, :, 1 if gqa else blocks, :] = 1 + values[:, :, L - 1 if gqa else 1, :] = -amplitude + q = mx.zeros((1, 8, 1, D), dtype=dtype) + k = mx.zeros((1, 1, L, D), dtype=dtype) + v = mx.array(values, dtype=dtype) + mask = mx.ones((L,), dtype=mx.bool_) if masked else None + with patch.dict(os.environ, MLX_SDPA_BLOCKS=str(blocks)): + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=1, mask=mask + ) + mx.eval(out) + self.assertEqual(out.dtype, dtype) + self.assertTrue(mx.array_equal(out, mx.full(out.shape, 1 / L, dtype))) + + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_two_pass_partial_overflow(self): + # The final mean is representable in FP16, but its partial sums are not. + L = 8192 + for D, blocks in product((64, 128, 256), (32, 128)): + with self.subTest(D=D, blocks=blocks): + q = mx.zeros((1, 8, 1, D), dtype=mx.float16) + k = mx.zeros((1, 1, L, D), dtype=mx.float16) + v = mx.full((1, 1, L, D), 32768, dtype=mx.float16) + with patch.dict(os.environ, MLX_SDPA_BLOCKS=str(blocks)): + out = mx.fast.scaled_dot_product_attention(q, k, v, scale=1) + mx.eval(out) + self.assertTrue(mx.all(mx.isfinite(out))) + self.assertTrue( + mx.array_equal(out, mx.full(out.shape, 32768, mx.float16)) + ) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") def test_sdpa_vector_d96_v64(self): if mx.default_device() != mx.gpu: @@ -921,6 +971,14 @@ q = mx.random.normal(shape=(1, q_heads, q_len, D), dtype=dtype) k = mx.random.normal(shape=(1, kv_heads, 1029, D), dtype=dtype) v = mx.random.normal(shape=(1, kv_heads, 1029, D), dtype=dtype) scale = D**-0.5 + + if mx.default_device() != mx.gpu: + # The fused kernels need a GPU stream. + with self.assertRaises(ValueError): + mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + continue   out = mx.fast.scaled_dot_product_attention( q, k, v, scale=scale, mask=mask, force_fused=True

metal_kernel_with_mutable_inputs lets a caller declare which custom-kernel inputs will be written, so paged-KV consumers keep writes on the original allocation and Metal sees the read/write hazard. Mutable names must identify exactly one input; mutable device pointers are generated (including for small/scalar storage) and take part in the compiled-kernel identity; an implicit contiguous copy of declared-mutable storage is rejected; allocations are registered for writes as well as reads. A separate MutableInputCustomKernel primitive serializes the declaration while the existing CustomKernel export schema is untouched. (PR #18)

diff --git ml-explore/mlx/mlx/backend/common/metal_kernel.cpp Layr-Labs/mlx/mlx/backend/common/metal_kernel.cpp index d38a43395fe886e24eacc9f78167d74e0cd6957b..b656d33dc551c7e7076855c395afc4ccdcf8d877 100644 --- ml-explore/mlx/mlx/backend/common/metal_kernel.cpp +++ Layr-Labs/mlx/mlx/backend/common/metal_kernel.cpp @@ -1,7 +1,13 @@ // Copyright © 2024 Apple Inc.   +#include <algorithm> #include <iostream> +#include <memory> +#include <mutex> #include <sstream> +#include <unordered_map> + +#include <fmt/format.h>   #include "mlx/backend/common/compiled.h" #include "mlx/backend/metal/metal.h" @@ -49,6 +55,52 @@ } return Stream(-1, Device::gpu); }   +// MLX_FENCED_INPUT_WAIT(name): thread 0 of each threadgroup spins until the +// CPU fence reaches the count, as fence_wait does. A count of 0 does not wait. +constexpr const char* fenced_input_wait = R"( +#pragma METAL internals : enable +#ifndef __METAL_MEMORY_SCOPE_SYSTEM__ +#define __METAL_MEMORY_SCOPE_SYSTEM__ 3 +#endif +inline void mlx_fenced_input_wait( + volatile coherent(system) device uint* fence, + uint count, + uint index) { + constexpr metal::thread_scope scope = + static_cast<metal::thread_scope>(__METAL_MEMORY_SCOPE_SYSTEM__); + if (count == 0) { + return; + } + if (index == 0) { + while (true) { + metal::atomic_thread_fence( + metal::mem_flags::mem_device, metal::memory_order_seq_cst, scope); + if (fence[0] >= count) { + break; + } + } + } + metal::threadgroup_barrier(metal::mem_flags::mem_device); + metal::atomic_thread_fence( + metal::mem_flags::mem_device, metal::memory_order_seq_cst, scope); +} +#define MLX_FENCED_INPUT_WAIT(name) mlx_fenced_input_wait( \ + name##_fence, name##_fence_count, thread_index_in_threadgroup) +)"; + +constexpr const char* fenced_input_no_wait = + "\n#define MLX_FENCED_INPUT_WAIT(name) ((void)0)\n"; + +bool fenced_inputs_enabled() { +#ifdef __APPLE__ + if (__builtin_available(macOS 15, iOS 18, *)) { + return env::metal_fenced_inputs() && env::metal_fast_synch() && + !detail::in_export_tracing(); + } +#endif + return false; +} + std::string write_signature( std::string func_name, const std::string& header, @@ -60,10 +112,14 @@ const std::vector<Dtype>& output_dtypes, const std::vector<std::pair<std::string, TemplateArg>>& template_args, const std::vector<std::string>& attributes, const std::vector<std::tuple<bool, bool, bool>>& shape_infos, - bool atomic_outputs) { + bool atomic_outputs, + const std::vector<int>& mutable_inputs, + const char* fence_preamble, + const std::vector<int>& fenced_inputs) { std::string kernel_source; kernel_source.reserve(header.size() + source.size() + 16384); kernel_source += header; + kernel_source += fence_preamble; // Auto-generate a function signature based on `template_args` // and the dtype/shape of the arrays passed as `inputs`. if (!template_args.empty()) { @@ -97,11 +153,20 @@ // Add inputs for (int i = 0; i < inputs.size(); ++i) { const auto& name = input_names[i]; const auto& arr = inputs[i]; + bool is_mutable = + std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != + mutable_inputs.end(); + // A fenced input is read after the kernel waits for its CPU producer, + // so it stays in the device address space: the GPU may load a small + // constant buffer before the kernel runs, which is before the wait. + bool is_fenced = std::find(fenced_inputs.begin(), fenced_inputs.end(), i) != + fenced_inputs.end(); auto dtype = get_type_string(arr.dtype()); - std::string location = - arr.size() < max_constant_array_size ? "constant" : "device"; - std::string ref = arr.ndim() == 0 ? "&" : "*"; - kernel_source += " const "; + bool in_constant = + !is_mutable && !is_fenced && arr.size() < max_constant_array_size; + std::string location = in_constant ? "constant" : "device"; + std::string ref = !is_mutable && arr.ndim() == 0 ? "&" : "*"; + kernel_source += is_mutable ? " " : " const "; kernel_source += location; kernel_source += " "; kernel_source += dtype; @@ -159,6 +224,14 @@ } else { kernel_source += ") {\n"; } index++; + } + // Fenced inputs: the CPU fence and its count (attributes follow). + for (int i : fenced_inputs) { + const auto& name = input_names[i]; + kernel_source += " volatile coherent(system) device uint* " + name + + "_fence [[buffer(" + std::to_string(index++) + ")]],\n"; + kernel_source += " constant uint& " + name + "_fence_count [[buffer(" + + std::to_string(index++) + ")]],\n"; }   index = 0; @@ -228,6 +301,99 @@ const std::string& header /* = "" */, bool ensure_row_contiguous /* = true */, bool atomic_outputs /* = false */, const CompileOptions& compile_options /* = {} */) { + return metal_kernel_with_mutable_inputs( + name, + input_names, + output_names, + source, + {}, + header, + ensure_row_contiguous, + atomic_outputs, + compile_options); +} + +CustomKernelFunction metal_kernel_with_mutable_inputs( + const std::string& name, + const std::vector<std::string>& input_names, + const std::vector<std::string>& output_names, + const std::string& source, + const std::vector<std::string>& mutable_input_names, + const std::string& header, + bool ensure_row_contiguous, + bool atomic_outputs, + const CompileOptions& compile_options) { + return metal_kernel_with_fenced_inputs( + name, + input_names, + output_names, + source, + mutable_input_names, + {}, + header, + ensure_row_contiguous, + atomic_outputs, + compile_options); +} + +CustomKernelFunction metal_kernel_with_fenced_inputs( + const std::string& name, + const std::vector<std::string>& input_names, + const std::vector<std::string>& output_names, + const std::string& source, + const std::vector<std::string>& mutable_input_names, + const std::vector<std::string>& fenced_input_names, + const std::string& header, + bool ensure_row_contiguous, + bool atomic_outputs, + const CompileOptions& compile_options) { + std::vector<int> mutable_inputs; + for (const auto& mutable_name : mutable_input_names) { + auto it = std::find(input_names.begin(), input_names.end(), mutable_name); + if (it == input_names.end() || + std::count(input_names.begin(), input_names.end(), mutable_name) != 1) { + throw std::invalid_argument("Mutable input must name one kernel input."); + } + int index = static_cast<int>(it - input_names.begin()); + if (std::find(mutable_inputs.begin(), mutable_inputs.end(), index) != + mutable_inputs.end()) { + throw std::invalid_argument("Duplicate mutable kernel input."); + } + mutable_inputs.push_back(index); + } + std::sort(mutable_inputs.begin(), mutable_inputs.end()); + std::vector<int> fenced_inputs; + for (const auto& fenced_name : fenced_input_names) { + auto it = std::find(input_names.begin(), input_names.end(), fenced_name); + if (it == input_names.end() || + std::count(input_names.begin(), input_names.end(), fenced_name) != 1) { + throw std::invalid_argument("Fenced input must name one kernel input."); + } + int index = static_cast<int>(it - input_names.begin()); + if (std::find(fenced_inputs.begin(), fenced_inputs.end(), index) != + fenced_inputs.end() || + std::find(mutable_inputs.begin(), mutable_inputs.end(), index) != + mutable_inputs.end()) { + throw std::invalid_argument( + "A fenced kernel input must be unique and not mutable."); + } + for (const auto& suffix : {"_fence", "_fence_count"}) { + auto param = fenced_name + suffix; + if (std::count(input_names.begin(), input_names.end(), param) || + std::count(output_names.begin(), output_names.end(), param)) { + throw std::invalid_argument( + "Kernel argument name " + param + " is used by a fenced input."); + } + } + if (source.find("MLX_FENCED_INPUT_WAIT(" + fenced_name + ")") == + std::string::npos) { + throw std::invalid_argument( + "The kernel source must call MLX_FENCED_INPUT_WAIT(" + fenced_name + + ") before it reads the fenced input."); + } + fenced_inputs.push_back(index); + } + std::sort(fenced_inputs.begin(), fenced_inputs.end()); if (output_names.empty()) { throw std::invalid_argument( "[metal_kernel] Must specify at least one output."); @@ -265,11 +431,32 @@ };   std::vector<std::string> attributes; for (const auto& [attr, dtype] : metal_attributes) { - if (source.find(attr) != std::string::npos) { + if (source.find(attr) != std::string::npos || + (!fenced_inputs.empty() && attr == "thread_index_in_threadgroup")) { attributes.push_back(" " + dtype + " " + attr + " [[" + attr + "]]"); } }   + // The generated source is a pure function of this kernel object (header, + // body, names, attributes, shape infos, atomic and mutable inputs: all + // fixed here) and of the per-call key built below: the template + // arguments and, per input, its dtype and how it is passed (mutable, + // scalar, constant or device; a 0-d mutable input also drops its shape + // parameters), the output dtypes and whether fenced waits are compiled in. + // Cache the kernel name, source and Metal library name per key, so a + // repeated call neither formats names nor regenerates the (often multi-KB) + // source, and every launch of one entry shares it (and its pipeline, see + // CustomKernel::eval_gpu). Shared by every copy of the returned function. + struct Generated { + std::string kernel_name; + std::shared_ptr<const CustomKernelSource> source; + }; + struct SourceCache { + std::mutex mtx; + std::unordered_map<std::string, std::shared_ptr<const Generated>> entries; + }; + auto source_cache = std::make_shared<SourceCache>(); + return [=, shape_infos = std::move(shape_infos), attributes = std::move(attributes)]( @@ -297,71 +484,164 @@ check_size(output_shapes.size(), output_names.size(), "output_shapes"); check_size(output_dtypes.size(), output_names.size(), "output_dtypes");   auto s = resolve_metal_kernel_stream(s_); + const bool fenced = !fenced_inputs.empty() && fenced_inputs_enabled();   - std::string kernel_name = "custom_kernel_" + name; - std::string template_def = ""; - if (!template_args.empty()) { - template_def = write_template(template_args); - auto template_hash = make_template_hash(template_def); - kernel_name += "_"; - kernel_name += template_hash; + // The per-call key as raw bytes: each template argument (name, kind, + // value), each input's dtype and passing, each output's dtype and the + // fenced form. It determines the kernel name and the source below. + thread_local std::string key; + key.clear(); + for (const auto& [arg_name, arg] : template_args) { + key += arg_name; + key += '\0'; + key += static_cast<char>(arg.index()); + if (auto* v = std::get_if<int>(&arg)) { + key.append(reinterpret_cast<const char*>(v), sizeof(int)); + } else if (auto* b = std::get_if<bool>(&arg)) { + key += *b ? '1' : '0'; + } else { + key += static_cast<char>(std::get<Dtype>(arg).val()); + } } - - // The generated source depends on the dtypes of the inputs and outputs - // and on how each input is passed (see `write_signature`). Include them - // in the kernel name so that a given name always maps to the same source. - for (const auto& arr : inputs) { - kernel_name += "_"; - kernel_name += get_type_string(arr.dtype()); - if (arr.ndim() == 0) { - kernel_name += "s"; + key += '\0'; + for (int i = 0; i < inputs.size(); ++i) { + const auto& arr = inputs[i]; + key += static_cast<char>(arr.dtype().val()); + if (std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != + mutable_inputs.end()) { + key += arr.ndim() == 0 ? 'z' : 'n'; + } else if (arr.ndim() == 0) { + key += 's'; } else if (arr.size() < max_constant_array_size) { - kernel_name += "c"; + key += 'c'; + } else { + key += 'd'; } } + key += '\0'; for (const auto& dtype : output_dtypes) { - kernel_name += "_"; - kernel_name += get_type_string(dtype); + key += static_cast<char>(dtype.val()); } + key += fenced ? 'f' : 'u';   - std::string kernel_source = write_signature( - kernel_name, - header, - source, - input_names, - inputs, - output_names, - output_dtypes, - template_args, - attributes, - shape_infos, - atomic_outputs); + std::shared_ptr<const Generated> generated; + { + std::lock_guard lock(source_cache->mtx); + if (auto it = source_cache->entries.find(key); + it != source_cache->entries.end()) { + generated = it->second; + } + } + if (!generated) { + std::string kernel_name = "custom_kernel_" + name; + std::string template_def = ""; + if (!template_args.empty()) { + template_def = write_template(template_args); + auto template_hash = make_template_hash(template_def); + kernel_name += "_"; + kernel_name += template_hash; + }   - if (!template_args.empty()) { - template_def = kernel_name + template_def; - kernel_source += "\ntemplate [[host_name(\""; - kernel_source += kernel_name; - kernel_source += "\")]] [[kernel]] decltype("; - kernel_source += template_def; - kernel_source += ") "; - kernel_source += template_def; - kernel_source += ";\n"; + // The generated source depends on the dtypes of the inputs and outputs + // and on how each input is passed (see `write_signature`). Include them + // in the kernel name so that a given name always maps to the same + // source. + for (int i = 0; i < inputs.size(); ++i) { + const auto& arr = inputs[i]; + kernel_name += "_"; + kernel_name += get_type_string(arr.dtype()); + if (std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != + mutable_inputs.end()) { + kernel_name += "m"; + } else if (arr.ndim() == 0) { + kernel_name += "s"; + } else if (arr.size() < max_constant_array_size) { + kernel_name += "c"; + } + } + for (const auto& dtype : output_dtypes) { + kernel_name += "_"; + kernel_name += get_type_string(dtype); + } + + std::string kernel_source = write_signature( + kernel_name, + header, + source, + input_names, + inputs, + output_names, + output_dtypes, + template_args, + attributes, + shape_infos, + atomic_outputs, + mutable_inputs, + fenced_inputs.empty() ? "" + : fenced ? fenced_input_wait + : fenced_input_no_wait, + fenced ? fenced_inputs : std::vector<int>{}); + + if (!template_args.empty()) { + auto instantiation = kernel_name + template_def; + kernel_source += "\ntemplate [[host_name(\""; + kernel_source += kernel_name; + kernel_source += "\")]] [[kernel]] decltype("; + kernel_source += instantiation; + kernel_source += ") "; + kernel_source += instantiation; + kernel_source += ";\n"; + } + // Exactly the name CustomKernel::eval_gpu derived before. + auto library_name = fmt::format( + "{}_{:x}_{}", + kernel_name, + std::hash<std::string>{}(kernel_source), + compile_options.serialize()); + auto entry = std::make_shared<Generated>(); + entry->kernel_name = std::move(kernel_name); + entry->source = std::make_shared<const CustomKernelSource>( + std::move(kernel_source), std::move(library_name)); + generated = std::move(entry); + std::lock_guard lock(source_cache->mtx); + source_cache->entries.emplace(key, generated); }   if (verbose) { std::cout << "Generated source code for `" << name << "`:" << std::endl << "```" << std::endl - << kernel_source << std::endl + << generated->source->source << std::endl << "```" << std::endl; }   + if (!mutable_inputs.empty()) { + return array::make_arrays( + output_shapes, + output_dtypes, + std::make_shared<MutableInputCustomKernel>( + s, + generated->kernel_name, + generated->source, + grid, + threadgroup, + shape_infos, + ensure_row_contiguous, + init_value, + std::vector<ScalarArg>{}, + false, + 0, + compile_options.serialize(), + mutable_inputs, + fenced ? fenced_inputs : std::vector<int>{}), + inputs); + } return array::make_arrays( - std::move(output_shapes), - std::move(output_dtypes), + output_shapes, + output_dtypes, std::make_shared<CustomKernel>( s, - std::move(kernel_name), - std::move(kernel_source), + generated->kernel_name, + generated->source, grid, threadgroup, shape_infos, @@ -370,8 +650,10 @@ init_value, std::vector<ScalarArg>{}, false, 0, - compile_options.serialize()), - std::move(inputs)); + compile_options.serialize(), + std::vector<int>{}, + fenced ? fenced_inputs : std::vector<int>{}), + inputs); }; }
diff --git ml-explore/mlx/mlx/backend/metal/custom_kernel.cpp Layr-Labs/mlx/mlx/backend/metal/custom_kernel.cpp index b73dd72def76fa3412ef9155749507fe5d5cb48e..8b96fee8382233874d5135293ee319bacfabe4ed 100644 --- ml-explore/mlx/mlx/backend/metal/custom_kernel.cpp +++ Layr-Labs/mlx/mlx/backend/metal/custom_kernel.cpp @@ -2,11 +2,15 @@ // Copyright © 2024 Apple Inc.   #include "mlx/backend/common/metal_kernel.h" #include "mlx/backend/gpu/copy.h" +#include "mlx/backend/metal/fenced_input.h" #include "mlx/backend/metal/jit/includes.h" #include "mlx/backend/metal/utils.h" #include "mlx/fast_primitives.h"   #include <fmt/format.h> +#include <algorithm> +#include <cstdint> +#include <limits>   namespace mlx::core::fast {   @@ -17,7 +21,60 @@ // silence some warnings (void)is_precompiled_; (void)shared_memory_;   + // Take the waits on fenced inputs that Fence::wait_in_consumer gave to this + // kernel before any check below can throw, so that no wait is left for a + // later kernel at the same address. + std::vector<metal::FencedInput> fenced; + if (!fenced_inputs_.empty()) { + fenced = metal::take_fenced_inputs(this); + } + + const auto [tx, ty, tz] = threadgroup_; + const auto [gx, gy, gz] = grid_; + if (tx <= 0 || ty <= 0 || tz <= 0 || gx < 0 || gy < 0 || gz < 0) { + throw std::invalid_argument("Invalid custom kernel launch dimensions."); + } + size_t tg_size = 1; + for (auto dimension : {tx, ty, tz}) { + if (static_cast<size_t>(dimension) > + std::numeric_limits<std::uint32_t>::max() / tg_size) { + throw std::invalid_argument( + "Custom kernel threadgroup size exceeds 32 bits."); + } + tg_size *= static_cast<size_t>(dimension); + } + auto& s = stream(); + auto& d = metal::device(s.device); + // The device limit is fixed: query it once rather than per launch. + static const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + if (static_cast<size_t>(tx) > device_max.width || + static_cast<size_t>(ty) > device_max.height || + static_cast<size_t>(tz) > device_max.depth) { + throw std::invalid_argument( + "Custom kernel threadgroup exceeds device dimensions."); + } + + for (auto i : mutable_inputs_) { + if (i < 0 || i >= inputs.size()) { + throw std::invalid_argument("Invalid mutable kernel input index."); + } + if (ensure_row_contiguous_ && !inputs[i].flags().row_contiguous) { + throw std::invalid_argument( + "Mutable kernel inputs cannot use an implicit contiguous copy."); + } + } + + // An input that is copied first is read before the kernel: wait for it now. + for (auto it = fenced.begin(); it != fenced.end();) { + auto& in = inputs[it->input]; + if (ensure_row_contiguous_ && !in.flags().row_contiguous) { + metal::encode_fence_wait(s, in, *it); + it = fenced.erase(it); + } else { + ++it; + } + }   std::vector<array> copies;   @@ -40,18 +97,86 @@ copy_gpu(x, copies.back(), CopyType::General, s); return copies.back(); } }; - std::vector<array> checked_inputs; - for (const array& in : inputs) { - checked_inputs.push_back(check_input(in)); + // Bind the inputs themselves unless one needs a contiguous copy (the same + // arrays either way, without a reference-counted copy of each). + bool needs_copy = false; + if (ensure_row_contiguous_) { + for (const array& in : inputs) { + needs_copy |= !in.flags().row_contiguous; + } } + std::vector<array> copied_inputs; + if (needs_copy) { + copied_inputs.reserve(inputs.size()); + for (const array& in : inputs) { + copied_inputs.push_back(check_input(in)); + } + } + const std::vector<array>& checked_inputs = + needs_copy ? copied_inputs : inputs;   - auto& d = metal::device(s.device); + // Hashing the whole generated source (often tens of KB) on every dispatch + // dominated the host cost of decode-sized custom kernels; the kernel + // builder precomputes the identical name once per generated source. + const std::string& source = source_->source; + std::string derived_name; + if (source_->library_name.empty()) { + derived_name = fmt::format( + "{}_{:x}_{}", + name_, + std::hash<std::string>{}(source), + compile_options_); + } + const std::string& lib_name = + source_->library_name.empty() ? derived_name : source_->library_name; + // Launches that share a generated source skip the library and kernel + // lookups (a name hash and a shared lock each) after the first one. + std::call_once(source_->resolved, [&] { + auto lib = d.get_library(lib_name, compile_options_, [&source] { + return metal::utils() + source; + }); + auto pipeline = d.get_kernel(name_, lib); + source_->max_total_threads = pipeline->maxTotalThreadsPerThreadgroup(); + source_->pipeline = std::shared_ptr<void>(pipeline->retain(), [](void* p) { + static_cast<MTL::ComputePipelineState*>(p)->release(); + }); + }); + auto kernel = + static_cast<MTL::ComputePipelineState*>(source_->pipeline.get()); + auto max_tg_size = source_->max_total_threads; + const bool retry_geometry = (tx == 512 || tx == 1024) && ty == 1 && tz == 1 && + gx >= tx && gx % tx == 0 && gy > 0 && gz > 0; + if (tg_size > max_tg_size && retry_geometry) { + const std::string declaration = "[[kernel]] void " + name_ + "("; + const auto position = source.find(declaration); + if (position != std::string::npos && + source.find(declaration, position + declaration.size()) == + std::string::npos) { + // Keep the dispatch geometry and give the compiler its required size. + auto constrained_source = source; + constrained_source.insert( + position, + "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + + ")]] "); + auto constrained_name = + lib_name + "_required_tg_" + std::to_string(tg_size); + auto constrained_lib = d.get_library( + constrained_name, compile_options_, [&constrained_source] { + return metal::utils() + constrained_source; + }); + kernel = d.get_kernel(name_, constrained_lib); + max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + } + } + if (tg_size > max_tg_size) { + std::ostringstream msg; + msg << "Thread group size (" << tg_size << ") is greater than " + << " the maximum allowed threads per threadgroup (" << max_tg_size + << "). Kernel: " << name_ << "; threadgroup=(" << tx << "," << ty << "," + << tz << "); grid=(" << gx << "," << gy << "," << gz << ")."; + throw std::invalid_argument(msg.str()); + }   - std::string lib_name = fmt::format( - "{}_{:x}_{}", name_, std::hash<std::string>{}(source_), compile_options_); - auto lib = d.get_library( - lib_name, compile_options_, [this] { return metal::utils() + source_; }); - auto kernel = d.get_kernel(name_, lib); auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); int index = 0; @@ -59,6 +184,10 @@ for (int i = 0; i < checked_inputs.size(); i++) { const array& in = checked_inputs[i]; auto& shape_info = shape_infos_[i]; compute_encoder.set_input_array(in, index); + if (std::find(mutable_inputs_.begin(), mutable_inputs_.end(), i) != + mutable_inputs_.end()) { + compute_encoder.register_output_array(in); + } index++; if (in.ndim() > 0) { int ndim = in.ndim(); @@ -80,19 +209,25 @@ for (auto& out : outputs) { compute_encoder.set_output_array(out, index); index++; } - - const auto [tx, ty, tz] = threadgroup_; - auto tg_size = tx * ty * tz; - auto max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); - if (tg_size > max_tg_size) { - std::ostringstream msg; - msg << "Thread group size (" << tg_size << ") is greater than " - << " the maximum allowed threads per threadgroup (" << max_tg_size - << ")."; - throw std::invalid_argument(msg.str()); + for (int i : fenced_inputs_) { + auto it = std::find_if( + fenced.begin(), fenced.end(), [i](auto& f) { return f.input == i; }); + if (it != fenced.end()) { + metal::bind_fenced_input(compute_encoder, *it, index); + } else { + // No CPU-stream producer in this eval: a count of 0 does not wait. + compute_encoder.set_input_array(checked_inputs[i], index); + compute_encoder.set_bytes(uint32_t(0), index + 1); + } + index += 2; + } + if (!fenced.empty()) { + // As Fence::wait: start after every pass and kernel encoded before, so + // the CPU work that the kernel waits for never waits for the kernel. + compute_encoder.wait_for_all_pending(); + compute_encoder.barrier(); }   - const auto [gx, gy, gz] = grid_; MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); MTL::Size grid_dims = MTL::Size(gx, gy, gz);
diff --git ml-explore/mlx/mlx/export.cpp Layr-Labs/mlx/mlx/export.cpp index c10934d1bd08cacedc4726abea53ad3f131e6ebc..f4fc08b1b8ae08bb8d421b6610c2def828e6b945 100644 --- ml-explore/mlx/mlx/export.cpp +++ Layr-Labs/mlx/mlx/export.cpp @@ -465,7 +465,8 @@ SERIALIZE_PRIMITIVE(LayerNorm), SERIALIZE_PRIMITIVE(LayerNormVJP), SERIALIZE_PRIMITIVE(RoPE), SERIALIZE_PRIMITIVE(ScaledDotProductAttention), - SERIALIZE_PRIMITIVE(CustomKernel)}; + SERIALIZE_PRIMITIVE(CustomKernel), + SERIALIZE_PRIMITIVE(MutableInputCustomKernel)}; std::unordered_map<std::string, std::string> name_remap; std::unordered_map<int, Stream> stream_map;
diff --git ml-explore/mlx/mlx/fast.h Layr-Labs/mlx/mlx/fast.h index 14a46de657cc49e5124a5e961bdb618db455b1ad..7d86fe74ba251d4a854459f8643331e8bac79f5d 100644 --- ml-explore/mlx/mlx/fast.h +++ Layr-Labs/mlx/mlx/fast.h @@ -94,6 +94,34 @@ bool ensure_row_contiguous = true, bool atomic_outputs = false, const CompileOptions& compile_options = {});   +MLX_API CustomKernelFunction metal_kernel_with_mutable_inputs( + const std::string& name, + const std::vector<std::string>& input_names, + const std::vector<std::string>& output_names, + const std::string& source, + const std::vector<std::string>& mutable_input_names, + const std::string& header = "", + bool ensure_row_contiguous = true, + bool atomic_outputs = false, + const CompileOptions& compile_options = {}); + +// As `metal_kernel_with_mutable_inputs`. A fenced input can come from a CPU +// stream in the same eval; with MLX_METAL_FENCED_INPUTS=1 the kernel waits for +// that CPU work itself, and MLX encodes no separate fence wait. The source +// calls MLX_FENCED_INPUT_WAIT(name) for each fenced input before it reads it, +// in control flow that all threads of the threadgroup reach. +MLX_API CustomKernelFunction metal_kernel_with_fenced_inputs( + const std::string& name, + const std::vector<std::string>& input_names, + const std::vector<std::string>& output_names, + const std::string& source, + const std::vector<std::string>& mutable_input_names, + const std::vector<std::string>& fenced_input_names, + const std::string& header = "", + bool ensure_row_contiguous = true, + bool atomic_outputs = false, + const CompileOptions& compile_options = {}); + MLX_API CustomKernelFunction cuda_kernel( const std::string& name, const std::vector<std::string>& input_names,
diff --git ml-explore/mlx/mlx/fast_primitives.h Layr-Labs/mlx/mlx/fast_primitives.h index 8117a7a7b6d00986ea6b781498b77a1861d97e59..6d5effd791ec4b711651e95ee6b8dd2e98132ab0 100644 --- ml-explore/mlx/mlx/fast_primitives.h +++ Layr-Labs/mlx/mlx/fast_primitives.h @@ -1,5 +1,7 @@ // Copyright © 2024-2026 Apple Inc.   +#include <memory> +#include <mutex> #include <optional> #include <variant>   @@ -505,12 +507,29 @@ };   using ScalarArg = std::variant<bool, int, float>;   +// Generated source of a custom kernel. `metal_kernel` makes one for each +// kernel and template instance, and all its launches share it. +struct CustomKernelSource { + explicit CustomKernelSource(std::string source, std::string library_name = "") + : source(std::move(source)), library_name(std::move(library_name)) {} + + std::string source; + // Metal library name. When empty, eval_gpu makes it from the source. + std::string library_name; + + // The compiled kernel and its threadgroup limit, resolved once by the + // first launch (Metal). + mutable std::once_flag resolved; + mutable std::shared_ptr<void> pipeline; + mutable size_t max_total_threads = 0; +}; + class CustomKernel : public Primitive { public: CustomKernel( Stream stream, std::string name, - std::string source, + std::shared_ptr<const CustomKernelSource> source, std::tuple<int, int, int> grid, std::tuple<int, int, int> threadgroup, std::vector<std::tuple<bool, bool, bool>> shape_infos, @@ -519,7 +538,9 @@ std::optional<float> init_value, std::vector<ScalarArg> scalar_arguments, bool is_precompiled, int shared_memory, - CompileOptions::Data compile_options = {}) + CompileOptions::Data compile_options = {}, + std::vector<int> mutable_inputs = {}, + std::vector<int> fenced_inputs = {}) : Primitive(stream), name_(std::move(name)), source_(std::move(source)), @@ -531,7 +552,39 @@ init_value_(init_value), scalar_arguments_(std::move(scalar_arguments)), is_precompiled_(is_precompiled), shared_memory_(shared_memory), - compile_options_(compile_options) {} + compile_options_(compile_options), + mutable_inputs_(std::move(mutable_inputs)), + fenced_inputs_(std::move(fenced_inputs)) {} + + // A private source entry (graph import, cuda): resolved once per primitive. + CustomKernel( + Stream stream, + std::string name, + std::string source, + std::tuple<int, int, int> grid, + std::tuple<int, int, int> threadgroup, + std::vector<std::tuple<bool, bool, bool>> shape_infos, + bool ensure_row_contiguous, + std::optional<float> init_value, + std::vector<ScalarArg> scalar_arguments, + bool is_precompiled, + int shared_memory, + CompileOptions::Data compile_options = {}, + std::vector<int> mutable_inputs = {}) + : CustomKernel( + stream, + std::move(name), + std::make_shared<const CustomKernelSource>(std::move(source)), + grid, + threadgroup, + std::move(shape_infos), + ensure_row_contiguous, + init_value, + std::move(scalar_arguments), + is_precompiled, + shared_memory, + compile_options, + std::move(mutable_inputs)) {}   void eval_cpu(const std::vector<array>& inputs, std::vector<array>& outputs) override { @@ -542,10 +595,20 @@ void eval_gpu(const std::vector<array>& inputs, std::vector<array>& outputs) override;   DEFINE_NAME(CustomKernel); + + bool fenced_input(int index) const { + for (int i : fenced_inputs_) { + if (i == index) { + return true; + } + } + return false; + } + auto state() const { return std::make_tuple( name_, - source_, + source_->source, grid_, threadgroup_, shape_infos_, @@ -559,7 +622,7 @@ }   private: std::string name_; - std::string source_; + std::shared_ptr<const CustomKernelSource> source_; std::tuple<int, int, int> grid_; std::tuple<int, int, int> threadgroup_; std::vector<std::tuple<bool, bool, bool>> shape_infos_; @@ -569,6 +632,22 @@ std::vector<ScalarArg> scalar_arguments_; bool is_precompiled_; int shared_memory_; CompileOptions::Data compile_options_; + + protected: + std::vector<int> mutable_inputs_; + // Inputs whose fence wait runs in the kernel. Not in `state()`: never set + // while exporting (see metal_kernel_with_fenced_inputs). + std::vector<int> fenced_inputs_; +}; + +class MutableInputCustomKernel : public CustomKernel { + public: + using CustomKernel::CustomKernel; + DEFINE_NAME(MutableInputCustomKernel); + auto state() const { + return std::tuple_cat( + CustomKernel::state(), std::make_tuple(mutable_inputs_)); + } };   } // namespace mlx::core::fast

Compile caches became thread-local upstream; bindings built before that (the mlx-c / mlx-swift consumers) still call the process-wide compile_erase / compile_clear_cache. A process-lifetime registry records each thread’s cache once at construction so those entrypoints can erase or clear every live cache, with no per-call hot-path work. (PR #10)

diff --git ml-explore/mlx/mlx/compile.cpp Layr-Labs/mlx/mlx/compile.cpp index e6bb2953b586c8c7d8b5e67dd14cd38894c01f3b..fbb04aa6ed3483989b9917ef30c33963df8b78d2 100644 --- ml-explore/mlx/mlx/compile.cpp +++ Layr-Labs/mlx/mlx/compile.cpp @@ -215,6 +215,27 @@ }   namespace detail {   +class CompileCache; + +class CompileCacheRegistry { + public: + void add(CompileCache* cache); + void remove(CompileCache* cache); + void erase(std::uintptr_t fun_id); + void clear(); + + private: + std::mutex mutex_; + std::unordered_set<CompileCache*> caches_; +}; + +CompileCacheRegistry& compile_cache_registry() { + // Intentionally process-lifetime: thread-local compile caches can be torn + // down after ordinary static destruction has started. + static auto* registry = new CompileCacheRegistry(); + return *registry; +} + std::atomic<CompileMode>& compile_mode() { auto get_val = []() { if (std::getenv("MLX_DISABLE_COMPILE")) { @@ -317,6 +338,11 @@ CompileCache() { // Make sure the allocator is fully initialized before the compiler cache. allocator::allocator(); + compile_cache_registry().add(this); + } + + ~CompileCache() { + compile_cache_registry().remove(this); }   // Returns a reference to a CacheEntry which can be updated by the caller to @@ -410,6 +436,30 @@ std::unordered_map<std::uintptr_t, std::shared_ptr<std::vector<CacheEntry>>> cache_; std::shared_mutex mutex_; }; + +void CompileCacheRegistry::add(CompileCache* cache) { + std::unique_lock lock(mutex_); + caches_.insert(cache); +} + +void CompileCacheRegistry::remove(CompileCache* cache) { + std::unique_lock lock(mutex_); + caches_.erase(cache); +} + +void CompileCacheRegistry::erase(std::uintptr_t fun_id) { + std::unique_lock lock(mutex_); + for (auto* cache : caches_) { + cache->erase(fun_id); + } +} + +void CompileCacheRegistry::clear() { + std::unique_lock lock(mutex_); + for (auto* cache : caches_) { + cache->clear(); + } +}   std::shared_ptr<CompileCache>& compile_cache_unsafe() { static thread_local auto cache = std::make_shared<CompileCache>(); @@ -1221,10 +1271,18 @@ p->erase(fun_id); } }   +void compile_erase(std::uintptr_t fun_id) { + compile_cache_registry().erase(fun_id); +} + void compile_clear_cache(const CompileCacheWeakPtr& cache) { if (auto p = cache.lock()) { p->clear(); } +} + +void compile_clear_cache() { + compile_cache_registry().clear(); }   } // namespace detail @@ -1244,8 +1302,13 @@ } else { auto pfun = std::shared_ptr< std::function<std::vector<array>(const std::vector<array>&)>>( new std::function<std::vector<array>(const std::vector<array>&)>{fun}, - [cache = detail::compile_cache()](auto* p) { - detail::compile_erase(cache, reinterpret_cast<std::uintptr_t>(p)); + [](auto* p) { + // The compiled function can be called on any thread, and each call + // records its trace in the cache of the calling thread. Erase the + // key from every live thread cache, and do it before the delete so + // that no new function can get this address while a trace for it + // is still cached. + detail::compile_erase(reinterpret_cast<std::uintptr_t>(p)); delete p; }); fun_id = reinterpret_cast<std::uintptr_t>(pfun.get());
diff --git ml-explore/mlx/mlx/compile_impl.h Layr-Labs/mlx/mlx/compile_impl.h index 1afe07b931d1a1a66f31ef7a2cc6c532600bd844..64249f3e488a085bb4b25775ad538bd52c621c32 100644 --- ml-explore/mlx/mlx/compile_impl.h +++ Layr-Labs/mlx/mlx/compile_impl.h @@ -37,9 +37,17 @@ MLX_API void compile_erase( const CompileCacheWeakPtr& cache, std::uintptr_t fun_id);   +// Compatibility entrypoint for bindings created before caches became +// thread-local. Erases the function from every live thread cache. +MLX_API void compile_erase(std::uintptr_t fun_id); + // Clear the compiler cache causing a recompilation of all compiled functions // when called again. MLX_API void compile_clear_cache(const CompileCacheWeakPtr& cache); + +// Compatibility entrypoint for bindings created before caches became +// thread-local. Clears every live thread cache. +MLX_API void compile_clear_cache();   bool compile_available_for_device(const Device& device);
diff --git ml-explore/mlx/tests/compile_tests.cpp Layr-Labs/mlx/tests/compile_tests.cpp index 30c2f887acc269998494820af4d7c62f46d5e408..2fd000877d5e994ec7e29c79ecf57e37d99aa3a4 100644 --- ml-explore/mlx/tests/compile_tests.cpp +++ Layr-Labs/mlx/tests/compile_tests.cpp @@ -5,13 +5,24 @@ #define _USE_MATH_DEFINES   #include "doctest/doctest.h"   +#include <atomic> +#include <barrier> #include <cmath> #include <limits> +#include <thread>   +#include "mlx/compile_impl.h" #include "mlx/mlx.h" #include "mlx/primitives.h"   using namespace mlx::core; + +namespace mlx::core::detail { +// Backward-compatible entrypoints required by the C/Swift binding. Unlike the +// cache-specific overloads, these must affect every live thread-local cache. +void compile_erase(std::uintptr_t fun_id); +void compile_clear_cache(); +} // namespace mlx::core::detail   std::vector<array> simple_fun(const std::vector<array>& inputs) { return std::vector<array>{inputs[0] + inputs[1]}; @@ -875,3 +886,72 @@ auto out = cfun({}); REQUIRE_EQ(out.size(), 1); CHECK_EQ(out[0].item<float>(), 3.0f); } + +TEST_CASE("test compatibility erase clears every live thread cache") { + std::atomic<int> trace_count{0}; + constexpr std::uintptr_t fun_id = 0x0322; + std::barrier phase(3); + + auto worker = [&]() { + auto compiled = detail::compile( + [&](const std::vector<array>& inputs) { + trace_count.fetch_add(1, std::memory_order_relaxed); + return std::vector<array>{inputs[0] + array(1)}; + }, + fun_id); + + compiled({array(1)}); + phase.arrive_and_wait(); + phase.arrive_and_wait(); + compiled({array(1)}); + phase.arrive_and_wait(); + }; + + std::thread first(worker); + std::thread second(worker); + + phase.arrive_and_wait(); + CHECK_EQ(trace_count.load(std::memory_order_relaxed), 2); + + detail::compile_erase(fun_id); + phase.arrive_and_wait(); + phase.arrive_and_wait(); + CHECK_EQ(trace_count.load(std::memory_order_relaxed), 4); + + first.join(); + second.join(); +} + +TEST_CASE("test freeing a compiled closure erases every thread cache") { + // compile(std::function) keys a closure by the address of a heap copy of + // it. When the last copy of the compiled function is freed, its traces must + // go from every thread cache, not only from the cache of the thread that + // called compile(). A trace that stays keeps its arrays alive, and a later + // closure that gets the same heap address replays it. + // + // The trace holds the captured array, so the array is uniquely referenced + // again only when no cache holds the trace. The array is built from host + // data and the worker does not evaluate the output, so no device work holds + // a reference to it. + auto captured = array({1.0f, 2.0f, 3.0f}); + auto compiled = compile([captured](const std::vector<array>& inputs) { + return std::vector<array>{inputs[0] + captured}; + }); + + std::barrier phase(2); + std::thread worker([&]() { + { + // Record a trace in this thread's cache only. + auto outputs = compiled({array({1.0f, 1.0f, 1.0f})}); + } + phase.arrive_and_wait(); + // Keep this thread, and so its cache, alive while the closure is freed. + phase.arrive_and_wait(); + }); + + phase.arrive_and_wait(); + compiled = nullptr; + CHECK(captured.is_uniquely_referenced()); + phase.arrive_and_wait(); + worker.join(); +}

compile(std::function) keys a closure by the address of a heap copy of it. Upstream, the deleter of that copy erases the key only from the cache of the thread that called compile(). Each call records its trace in the cache of the calling thread, so a trace from another thread stayed after the copy was freed. The trace kept its arrays alive, and a later closure at the same address could replay it. The deleter now erases the key from every live thread cache through the registry above, before the delete. The test test freeing a compiled closure erases every thread cache records a trace on a second thread, frees the closure, and checks that the captured array is uniquely referenced. (PR #43)

The Python binding keys the traces of mx.compile(fun) by the address of fun. Upstream, PyCompiledFun keeps the cache of the thread that called it last, and its destructor erases the key only from that cache. Each call records its trace in the cache of the calling thread, so a trace from another thread stayed after the free. The trace kept its arrays alive, and a later compile of a callable at the same address replayed it without a new trace. The destructor now erases the key from every live thread cache through the registry above, before it releases fun, and PyCompiledFun no longer keeps a cache. The test test_compile_free_erases_every_thread_cache calls a compiled function on two threads, frees it on the thread that called it last, and compiles the same callable again on the other thread. It expects a new trace there. (PR #44)

diff --git ml-explore/mlx/python/src/transforms.cpp Layr-Labs/mlx/python/src/transforms.cpp index 223e232e2911e59048aa928c8e6749a4bb1ce19b..0397ca04471c080370e62489495e103af39e1ff2 100644 --- ml-explore/mlx/python/src/transforms.cpp +++ Layr-Labs/mlx/python/src/transforms.cpp @@ -416,7 +416,6 @@ std::uintptr_t fun_id; nb::object captured_inputs; nb::object captured_outputs; bool shapeless; - mx::detail::CompileCacheWeakPtr cache;   // Data to attach to the compiled function that contains the python output // structure and the number of arrays in said structure. @@ -452,14 +451,11 @@ : fun(std::move(other.fun)), fun_id(reinterpret_cast<std::uintptr_t>(fun.ptr())), captured_inputs(std::move(other.captured_inputs)), captured_outputs(std::move(other.captured_outputs)), - shapeless(other.shapeless), - cache(other.cache) { + shapeless(other.shapeless) { other.fun_id = 0; };   nb::object call_impl(const nb::args& args, const nb::kwargs& kwargs) { - cache = mx::detail::compile_cache(); - // Flat array inputs std::vector<mx::array> inputs;   @@ -593,7 +589,14 @@ ~PyCompiledFun() { nb::gil_scoped_acquire gil;   - mx::detail::compile_erase(cache, fun_id); + // The compiled function can be called on any thread, and each call + // records its trace in the cache of the calling thread. Erase the key from + // every live thread cache, and do it before fun is released so that no + // new callable can get this address while a trace for it is still cached. + // A moved-from object has fun_id 0 and no traces. + if (fun_id != 0) { + mx::detail::compile_erase(fun_id); + } fun.reset(); captured_inputs.reset(); captured_outputs.reset();
diff --git ml-explore/mlx/python/tests/test_compile.py Layr-Labs/mlx/python/tests/test_compile.py index 7436e58cd211ebf6a8586558c2173fbdce3a69b1..12daa0347b9e85180fbae06cfd3fe66501765558 100644 --- ml-explore/mlx/python/tests/test_compile.py +++ Layr-Labs/mlx/python/tests/test_compile.py @@ -169,6 +169,66 @@ if errors: raise errors[0] self.assertEqual(len(traces), 2)   + def test_compile_free_erases_every_thread_cache(self): + # Each call of a compiled function records its trace in the cache of + # the calling thread. When the function is freed, its entry must go + # from every thread cache, not only from the cache of the thread that + # called it last. Otherwise a later compile of the same callable (so + # the same id) on another thread gets the old tape and is not traced + # again. + traces = [] + + def fun(x): + traces.append(1) + return x + 1 + + holder = {"fn": mx.compile(fun)} + traced = threading.Event() + released = threading.Event() + errors = [] + worker_traces = [] + + def worker(): + try: + # Make the default stream of this thread first. A trace is + # cached under the default stream of the calling thread, and + # the first op of a new thread makes that stream. A trace + # recorded before it exists never matches a later call. + mx.default_stream(mx.default_device()) + # Record a trace in the cache of this thread. The second call + # must use it, which shows that this thread finds the entry. + mx.eval(holder["fn"](mx.array([1.0]))) + mx.eval(holder["fn"](mx.array([1.0]))) + worker_traces.append(len(traces)) + traced.set() + self.assertTrue(released.wait(10)) + # The same callable, so the same id. + fn = mx.compile(fun) + mx.eval(fn(mx.array([1.0]))) + except Exception as e: + errors.append(e) + finally: + traced.set() + mx.clear_streams() + + # The worker has to outlive the release. On exit it would tear down + # its cache anyway. + thread = threading.Thread(target=worker) + thread.start() + self.assertTrue(traced.wait(10)) + # Call the function last on this thread, then free it here. + mx.eval(holder["fn"](mx.array([1.0]))) + holder.clear() + gc.collect() + released.set() + thread.join() + + if errors: + raise errors[0] + self.assertEqual(worker_traces, [1]) + # One trace on each thread, and one more on the worker after the free. + self.assertEqual(len(traces), 3) + def test_compile_grad(self): def loss_fn(x): return mx.exp(x).sum()

The fork keeps its regression tests for integer floor_divide from PR #32. Upstream now does the fix itself: ml-explore/mlx #4515 fixes floor_divide in ops.cpp and #4642 adds a FloorDivide primitive that rounds down. The fork dropped its own flooring Divide functors when it merged upstream on 2026-10-22, so integer Divide truncates again, as in upstream. The tests check negative operands of every signed integer type, the SIMD and scalar paths, unsigned and floating-point division, and compiled graphs. On the CPU they also check that x // 0 gives 0 and min // -1 gives the minimum value. Upstream’s CPU floor_divide divided min by -1, which overflows and traps on x86 (SIGFPE). The fork divides by 1 there, as PR #32 did, so the result wraps to min.

diff --git ml-explore/mlx/mlx/backend/cpu/simd/accelerate_simd.h Layr-Labs/mlx/mlx/backend/cpu/simd/accelerate_simd.h index 649365373899826c778badda0e9c9724f6b09375..5a3af8f135091a79db492f06808bb74e3699c6ad 100644 --- ml-explore/mlx/mlx/backend/cpu/simd/accelerate_simd.h +++ Layr-Labs/mlx/mlx/backend/cpu/simd/accelerate_simd.h @@ -248,8 +248,16 @@ template <typename T, int N> Simd<T, N> floor_divide(Simd<T, N> a, Simd<T, N> b) { if constexpr (std::is_integral_v<T>) { // Swap zero divisors for 1 before dividing so the quotient is defined. + // For signed types also swap -1 where a is min: min / -1 overflows, and + // min / 1 gives min, the wrapped result. auto zero = b == Simd<T, N>(0); - auto q = a / select(zero, Simd<T, N>(1), b); + auto use_one = zero; + if constexpr (is_signed_v<T>) { + use_one = use_one || + (a == Simd<T, N>(std::numeric_limits<T>::min()) && + b == Simd<T, N>(-1)); + } + auto q = a / select(use_one, Simd<T, N>(1), b); q = select(zero, Simd<T, N>(0), q); if constexpr (is_signed_v<T>) { // a - b * q is the remainder and needs no division by zero. @@ -259,6 +267,14 @@ } return q; } else if constexpr (is_complex<T>) { return a / b; + } else if constexpr (is_half_v<T>) { + // See exact_floor_divide in base_simd.h. + Simd<T, N> q; + for (int i = 0; i < N; ++i) { + q[i] = T(exact_floor_divide( + static_cast<float>(a[i]), static_cast<float>(b[i]))); + } + return q; } else { return floor(divide(a, b)); }
diff --git ml-explore/mlx/mlx/backend/cpu/simd/base_simd.h Layr-Labs/mlx/mlx/backend/cpu/simd/base_simd.h index b24bc9d0110ea9991d466a417c7a424d7dd79b3e..9cadc8538d49a66d380aca636e0e3c79af1ac770 100644 --- ml-explore/mlx/mlx/backend/cpu/simd/base_simd.h +++ Layr-Labs/mlx/mlx/backend/cpu/simd/base_simd.h @@ -8,6 +8,7 @@ #include <stdint.h> #include <algorithm> #include <complex> #include <functional> +#include <limits>   #ifdef _MSC_VER #include <intrin.h> // For _BitScanReverse @@ -218,6 +219,33 @@ } return a / b; }   +// The floor of a / b, computed as numpy's npy_divmodf does: from fmod, so the +// quotient is not rounded before the floor. float16 and bfloat16 use it in +// float32: floor(a / b) in the half type rounds a quotient that is just below +// an integer up to that integer. +inline float exact_floor_divide(float a, float b) { + if (b == 0) { + return a / b; + } + float mod = std::fmod(a, b); + float div = (a - mod) / b; + if (mod != 0 && ((b < 0) != (mod < 0))) { + div -= 1.0f; + } + if (div == 0) { + return std::copysign(0.0f, a / b); + } + float floordiv = std::floor(div); + if (div - floordiv > 0.5f) { + floordiv += 1.0f; + } + return floordiv; +} + +template <typename T> +constexpr bool is_half_v = + std::is_same_v<T, float16_t> || std::is_same_v<T, bfloat16_t>; + template <typename T> Simd<T, 1> floor_divide(Simd<T, 1> a_, Simd<T, 1> b_) { T a = a_.value; @@ -227,6 +255,12 @@ // Integer division by zero gives 0. See divide above. if (b == 0) { return T(0); } + if constexpr (is_signed_v<T>) { + // min / -1 overflows and traps on x86. The result wraps to min. + if (b == T(-1)) { + return a == std::numeric_limits<T>::min() ? a : T(-a); + } + } T q = a / b; if constexpr (is_signed_v<T>) { if (a % b != 0 && (a < 0 != b < 0)) { @@ -236,6 +270,8 @@ } return q; } else if constexpr (is_complex<T>) { return a / b; + } else if constexpr (is_half_v<T>) { + return T(exact_floor_divide(static_cast<float>(a), static_cast<float>(b))); } else { return floor(divide(a_, b_)); }
diff --git ml-explore/mlx/python/tests/test_ops.py Layr-Labs/mlx/python/tests/test_ops.py index c1d1f7b9c74927993d51c8ef63338b83e4942590..99c9085b3e03eda14faac9a43cdb9c298ace31ff 100644 --- ml-explore/mlx/python/tests/test_ops.py +++ Layr-Labs/mlx/python/tests/test_ops.py @@ -378,6 +378,78 @@ z = x // y self.assertEqual(z.dtype, mx.int32) self.assertEqual(z.item(), 2)   + def test_floor_divide_negative_operands(self): + a = [-7, 7, -7, 7, -6, 6, -6, 6, 0, 0, -1, 1, -1, 1] + b = [2, 2, -2, -2, 3, 3, -3, -3, 5, -5, 4, -4, -4, 4] + for t in ["int8", "int16", "int32", "int64"]: + with self.subTest(dtype=t): + dtype = getattr(mx, t) + x = mx.array(a, dtype) + y = mx.array(b, dtype) + expected = np.floor_divide( + np.array(a, getattr(np, t)), np.array(b, getattr(np, t)) + ) + self.assertEqual(expected.tolist(), [u // v for u, v in zip(a, b)]) + out = mx.floor_divide(x, y) + self.assertEqual(out.dtype, dtype) + self.assertEqual(out.tolist(), expected.tolist()) + self.assertEqual((x // y).tolist(), expected.tolist()) + self.assertEqual(mx.divmod(x, y)[0].tolist(), expected.tolist()) + self.assertEqual((x // -2).tolist(), [u // -2 for u in a]) + self.assertEqual((-7 // y).tolist(), [-7 // v for v in b]) + out = mx.reshape(x, (2, 7)).T // mx.reshape(y, (2, 7)).T + self.assertEqual(out.tolist(), expected.reshape(2, 7).T.tolist()) + out = mx.compile(lambda u, v: u // v + 1)(x, y) + self.assertEqual(out.tolist(), (expected + 1).tolist()) + + # 40 elements, so the SIMD path runs for every width (16 lanes for int8) + a = list(range(-20, 20)) + b = [[3, -3, 4, -4, 7][i % 5] for i in range(40)] + for t in ["int8", "int16", "int32", "int64"]: + with self.subTest(dtype=t): + dtype = getattr(mx, t) + out = mx.array(a, dtype) // mx.array(b, dtype) + self.assertEqual(out.tolist(), [u // v for u, v in zip(a, b)]) + + # On the CPU, x // 0 gives 0 and min // -1 gives min. The Metal + # Shading Language does not define these cases. + for t in ["int8", "int16", "int32", "int64"]: + with self.subTest(dtype=t): + dtype = getattr(mx, t) + x = mx.array([-7, 7, 0], dtype) + out = mx.floor_divide(x, 0, stream=mx.cpu) + self.assertEqual(out.tolist(), [0, 0, 0]) + x = mx.arange(-16, 17, dtype=dtype, stream=mx.cpu) + y = mx.zeros((33,), dtype, stream=mx.cpu) + out = mx.floor_divide(x, y, stream=mx.cpu) + self.assertEqual(out.tolist(), [0] * 33) + lo = mx.iinfo(dtype).min + x = mx.full((33,), lo, dtype, stream=mx.cpu) + y = mx.full((33,), -1, dtype, stream=mx.cpu) + out = mx.floor_divide(x, y, stream=mx.cpu) + self.assertEqual(out.tolist(), [lo] * 33) + + a = [-128, 127, -128, 127] + b = [3, -2, 127, -128] + out = mx.array(a, mx.int8) // mx.array(b, mx.int8) + self.assertEqual(out.tolist(), [u // v for u, v in zip(a, b)]) + + for t in ["uint8", "uint16", "uint32", "uint64"]: + with self.subTest(dtype=t): + dtype = getattr(mx, t) + out = mx.array([7, 6, 0, 255], dtype) // mx.array([2, 3, 5, 16], dtype) + self.assertEqual(out.dtype, dtype) + self.assertEqual(out.tolist(), [3, 2, 0, 15]) + + a = [-7.0, 7.0, -7.5, 7.5, 7.0] + b = [2.0, -2.0, 2.0, -2.0, 2.0] + for t in ["float16", "float32"]: + with self.subTest(dtype=t): + dtype = getattr(mx, t) + out = mx.array(a, dtype) // mx.array(b, dtype) + self.assertEqual(out.dtype, dtype) + self.assertEqual(out.tolist(), [-4.0, -4.0, -4.0, -4.0, 3.0]) + def test_complex_divide_extreme_values(self): values = np.array( [1e20 + 1e20j, 1e-30 + 1e-30j, 1 + 0j, 1e20 + 0j, 3 + 4j], @@ -3887,6 +3959,72 @@ ], mx.outer, np.outer, ) + + def test_floor_divide_half_rounding_window(self): + # Pairs whose true quotient is just below an integer n. Rounded to + # float16 or bfloat16, that quotient becomes n, so floor(a / b) in the + # half type gives n. The floor of the exact quotient is n - 1, which + # is what numpy's float16 divmod gives. + def window_pairs(bits): + # bits: stored mantissa bits (10 for float16, 7 for bfloat16). + pairs = [] + for k in range(1, 2**bits): + b = 1.0 + k * 2.0**-bits + for n in range(2, 24): + exact = n * b + if bits == 10: + a = float(np.float16(exact)) + if a > exact: + a = float(np.nextafter(np.float16(a), np.float16(0))) + else: + # Keep the top 16 bits of the float32 value: the + # largest bfloat16 value at or below it. + f = np.array([exact], dtype=np.float32).view(np.uint32) + a = float((f & np.uint32(0xFFFF0000)).view(np.float32)[0]) + if a == exact: + continue + q = a / b + ulp = 2.0 ** (math.floor(math.log2(q)) - bits) + if 0 < n - q < ulp / 4: + pairs.append((a, b)) + if len(pairs) == 24: + return pairs + return pairs + + devices = [mx.cpu] + if mx.metal.is_available(): + devices.append(mx.gpu) + for dtype, bits in ((mx.float16, 10), (mx.bfloat16, 7)): + pairs = window_pairs(bits) + self.assertGreater(len(pairs), 8) + av = [a for a, _ in pairs] + bv = [b for _, b in pairs] + expected_q = np.floor_divide(np.array(av), np.array(bv)) + if dtype == mx.float16: + np_q, np_r = np.divmod( + np.array(av, np.float16), np.array(bv, np.float16) + ) + self.assertEqual(np_q.astype(np.float64).tolist(), expected_q.tolist()) + for device in devices: + with self.subTest(dtype=dtype, device=device): + a = mx.array(av, dtype) + b = mx.array(bv, dtype) + self.assertEqual(a.astype(mx.float32).tolist(), av) + self.assertEqual(b.astype(mx.float32).tolist(), bv) + for q in ( + mx.floor_divide(a, b, stream=device), + mx.divmod(a, b, stream=device)[0], + ): + self.assertEqual( + q.astype(mx.float32).tolist(), expected_q.tolist() + ) + q, r = mx.divmod(a, b, stream=device) + r = np.array(r.astype(mx.float32)) + if dtype == mx.float16: + self.assertEqual(r.tolist(), np_r.astype(np.float32).tolist()) + self.assertTrue(np.all((r >= 0) & (r < np.array(bv)))) + q = np.array(q.astype(mx.float32), np.float64) + self.assertTrue(np.allclose(q * np.array(bv) + r, av))   def test_divmod(self): # A few sizes for the inputs with and without broadcasting
diff --git ml-explore/mlx/tests/ops_tests.cpp Layr-Labs/mlx/tests/ops_tests.cpp index da0f9e287365eae99125c00b9636ab1c0deada0d..e670542b91e1a8ae264e824f6bb1f29e18516648 100644 --- ml-explore/mlx/tests/ops_tests.cpp +++ Layr-Labs/mlx/tests/ops_tests.cpp @@ -3833,6 +3833,96 @@ eval(out_holder); CHECK_EQ(out_holder[0].item<float>(), 1.0); }   +TEST_CASE("test floor_divide with negative operands") { + std::vector<Device> devices = {Device::cpu}; + if (metal::is_available()) { + devices.push_back(Device::gpu); + } + for (auto& d : devices) { + for (auto t : {int8, int16, int32, int64}) { + auto a = array({-7, 7, -7, 7, -6, 6, -6, 6, 0, 0, -1, 1, -1, 1}, t); + auto b = array({2, 2, -2, -2, 3, 3, -3, -3, 5, -5, 4, -4, -4, 4}, t); + auto expected = + array({-4, 3, 3, -4, -2, 2, 2, -2, 0, 0, -1, -1, 0, 0}, t); + auto out = floor_divide(a, b, d); + CHECK_EQ(out.dtype(), t); + CHECK(array_equal(out, expected).item<bool>()); + CHECK(array_equal(out, divmod(a, b, d)[0]).item<bool>()); + + // Scalar and strided inputs + out = floor_divide(a, array(-2, t), d); + expected = array({3, -4, 3, -4, 3, -3, 3, -3, 0, 0, 0, -1, 0, -1}, t); + CHECK(array_equal(out, expected).item<bool>()); + out = floor_divide( + transpose(reshape(a, {2, 7})), transpose(reshape(b, {2, 7})), d); + expected = transpose(reshape( + array({-4, 3, 3, -4, -2, 2, 2, -2, 0, 0, -1, -1, 0, 0}, t), {2, 7})); + CHECK(array_equal(out, expected).item<bool>()); + } + + // 40 elements, so the SIMD path runs for every width (16 lanes for int8) + { + std::vector<int> av, bv, ev; + int divisors[] = {3, -3, 4, -4, 7}; + for (int i = 0; i < 40; ++i) { + int u = i - 20; + int v = divisors[i % 5]; + av.push_back(u); + bv.push_back(v); + ev.push_back(static_cast<int>(std::floor(double(u) / v))); + } + for (auto t : {int8, int16, int32, int64}) { + auto out = floor_divide( + array(av.begin(), {40}, t), array(bv.begin(), {40}, t), d); + CHECK(array_equal(out, array(ev.begin(), {40}, t)).item<bool>()); + } + } + + auto a = array({-128, 127, -128, 127}, int8); + auto b = array({3, -2, 127, -128}, int8); + auto out = floor_divide(a, b, d); + CHECK(array_equal(out, array({-43, -64, -2, -1}, int8)).item<bool>()); + + for (auto t : {uint8, uint16, uint32, uint64}) { + out = floor_divide(array({7, 6, 0, 255}, t), array({2, 3, 5, 16}, t), d); + CHECK_EQ(out.dtype(), t); + CHECK(array_equal(out, array({3, 2, 0, 15}, t)).item<bool>()); + } + + out = floor_divide( + array({-7.0f, 7.0f, -7.5f, 7.5f, 7.0f}), + array({2.0f, -2.0f, 2.0f, -2.0f, 2.0f}), + d); + CHECK(array_equal(out, array({-4.0f, -4.0f, -4.0f, -4.0f, 3.0f})) + .item<bool>()); + } +} + +TEST_CASE("test floor_divide integer edge cases on the CPU") { + // The Metal Shading Language does not define these cases. + for (auto t : {int8, int16, int32, int64}) { + auto out = floor_divide(array({-7, 7, 0}, t), array(0, t), Device::cpu); + CHECK(array_equal(out, array({0, 0, 0}, t)).item<bool>()); + + // 33 elements run the SIMD path and the scalar path. + auto x = astype(arange(-16, 17, Device::cpu), t, Device::cpu); + out = floor_divide(x, zeros({33}, t, Device::cpu), Device::cpu); + CHECK(array_equal(out, zeros({33}, t)).item<bool>()); + } + + auto check_min = [](int64_t lo, Dtype t) { + auto out = floor_divide( + full({33}, lo, t, Device::cpu), + full({33}, -1, t, Device::cpu), + Device::cpu); + CHECK(array_equal(out, full({33}, lo, t)).item<bool>()); + }; + check_min(std::numeric_limits<int8_t>::min(), int8); + check_min(std::numeric_limits<int16_t>::min(), int16); + check_min(std::numeric_limits<int32_t>::min(), int32); + check_min(std::numeric_limits<int64_t>::min(), int64); +} + TEST_CASE("test diagonal") { auto x = array({0, 1, 2, 3, 4, 5, 6, 7}, {4, 2}); auto out = diagonal(x); @@ -4848,3 +4938,20 @@ auto x = array({1, 2, 3, 4}); auto rolled = roll(x, -2147483647 - 1); CHECK(array_equal(rolled, x).item<bool>()); } + +TEST_CASE("quantized matmul casts on the caller's stream") { + // mlx-swift passes its own stream to every op. A cast on the thread's + // default stream instead put one projection on two GPU streams. + auto s = new_stream(default_device()); + auto w = reshape(astype(arange(64 * 64), float32), {64, 64}); + auto quantized = quantize(w, 64, 4); + auto scales = astype(quantized[1], bfloat16); + auto biases = astype(quantized[2], bfloat16); + auto x = ones({1, 64}, float32); + auto out = quantized_matmul( + x, quantized[0], scales, biases, true, 64, 4, "affine", s); + // x is float32 already; the bfloat16 scales and biases are cast to it. + CHECK(out.primitive().stream() == s); + CHECK(out.inputs()[2].primitive().stream() == s); + CHECK(out.inputs()[3].primitive().stream() == s); +}

Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond the device limits before allocating outputs. A nonempty grid with complete x-axis multiples of the group width and groups (512,1,1) or (1024,1,1) may retry an insufficient pipeline with max_total_threads_per_threadgroup(requestedWidth) on its unique generated declaration. The original capable pipeline is retained; retry compilation and the selected pipeline’s actual capacity remain authoritative. Other geometries refuse without clamping. Shader math and dispatch axes do not change.

diff --git ml-explore/mlx/docs/src/dev/custom_metal_kernels.rst Layr-Labs/mlx/docs/src/dev/custom_metal_kernels.rst index 6a9471fd5123e8d8936b7dac2c6dd6bb1cf5a8e8..8c160167ef1ae853f6d0bdcfa7b3ac9a254018b9 100644 --- ml-explore/mlx/docs/src/dev/custom_metal_kernels.rst +++ Layr-Labs/mlx/docs/src/dev/custom_metal_kernels.rst @@ -466,3 +466,17 @@ There's an even larger speed up for the vjp:   ``676.4ms -> 16.7ms => 40x speed up`` + +Threadgroup compiler capacity +----------------------------- + +Custom Metal kernels require positive threadgroup axes, nonnegative grid axes, +a thread count within UINT32_MAX, and axes within the device limits. Invalid +geometry is refused before output allocation. A capable original pipeline is +kept. For a nonempty grid containing complete 512- or 1024-wide groups, exactly +``(512, 1, 1)`` or ``(1024, 1, 1)`` may retry an insufficient pipeline with the MSL +``max_total_threads_per_threadgroup(requestedWidth)`` declaration attribute. The retry +uses a distinct source/library identity and must itself support the full +threadgroup. Compile errors and remaining capacity failures propagate. This +does not change shader math, precision, group/grid axes, or guarantee that a +particular shader can compile at the requested width. Other geometries receive no retry.
diff --git ml-explore/mlx/python/tests/test_metal_threadgroup_bounds.py Layr-Labs/mlx/python/tests/test_metal_threadgroup_bounds.py new file mode 100644 index 0000000000000000000000000000000000000000..49466d0440386f1bb4c3caaba8c7fe43064fbf12 --- /dev/null +++ Layr-Labs/mlx/python/tests/test_metal_threadgroup_bounds.py @@ -0,0 +1,80 @@ +# Custom Metal launch validation. + +import unittest + +import mlx.core as mx + + +@unittest.skipIf(not mx.metal.is_available(), "Metal is unavailable; not a pass") +class ThreadgroupBoundsTests(unittest.TestCase): + def test_invalid_dimensions_precede_compilation(self): + # A compiler attempt would raise RuntimeError instead of ValueError. + cases = [ + ((0, 1, 1), (1024, 1, 1), "dimensions"), + ((1, 0, 1), (1024, 1, 1), "dimensions"), + ((1, 1, 0), (1024, 1, 1), "dimensions"), + ((-1, 1, 1), (1024, 1, 1), "dimensions"), + ((1, -1, 1), (1024, 1, 1), "dimensions"), + ((1, 1, -1), (1024, 1, 1), "dimensions"), + ((1024, 1, 1), (-1, 1, 1), "dimensions"), + ((1024, 1, 1), (1, -1, 1), "dimensions"), + ((1024, 1, 1), (1, 1, -1), "dimensions"), + ((65536, 65536, 1), (1024, 1, 1), "32 bits"), + ( + (2147483647, 2147483647, 2147483647), + (1024, 1, 1), + "32 bits", + ), + ((2147483647, 1, 1), (1024, 1, 1), "device dimensions"), + ((1, 2147483647, 1), (1024, 1, 1), "device dimensions"), + ((1, 1, 2147483647), (1024, 1, 1), "device dimensions"), + ] + for index, (group, grid, message) in enumerate(cases): + with self.subTest(group=group, grid=grid): + kernel = mx.fast.metal_kernel( + name=f"invalid_geometry_{index}", + input_names=[], + output_names=["out"], + source="INTENTIONAL_INVALID_METAL;", + ensure_row_contiguous=True, + ) + with self.assertRaisesRegex(ValueError, message): + outputs = kernel( + inputs=[], + grid=grid, + threadgroup=group, + output_shapes=[(1,)], + output_dtypes=[mx.uint32], + init_value=0, + stream=mx.gpu, + ) + mx.eval(outputs) + + def test_legal_launch_keeps_threads_and_values(self): + for group in [32, 256, 512, 1024]: + kernel = mx.fast.metal_kernel( + name="thread_count_and_math", + input_names=["a"], + output_names=["out", "count"], + source=""" + uint i = thread_position_in_grid.x; + out[i] = a[i] * 2.0f + 1.0f; + count[i] = threads_per_threadgroup.x; + """, + ) + a = mx.arange(2048, dtype=mx.float32) + out, count = kernel( + inputs=[a], + grid=(2048, 1, 1), + threadgroup=(group, 1, 1), + output_shapes=[(2048,), (2048,)], + output_dtypes=[mx.float32, mx.uint32], + stream=mx.gpu, + ) + mx.eval(out, count) + self.assertTrue(mx.array_equal(out, a * 2 + 1).item()) + self.assertTrue(mx.all(count == group).item()) + + +if __name__ == "__main__": + unittest.main()

JACCL is the RDMA-over-Thunderbolt backend. Upstream has changed none of the three things below.

Send frames: JACCL posts every frame at the full size of its scratch buffer, so a payload shorter than the buffer went to the peer followed by the bytes of earlier sends. stage_send_frame (send_frame.h) copies the payload and zeroes the rest of the frame, and every mesh and ring send path stages through SharedBuffer::stage_send. The posted sizes and the receive paths are unchanged.

Progress guard: the polling loops waited for completions without a limit and never read wc.status, so a rank whose peer had died spun on a full core until it was killed, and a failed completion was used as data. ProgressGuard (progress_guard.h) is called after every poll of every mesh and ring loop. A completion with a failure status, or a failed ibv_poll_cq, is an error at once; no completion for longer than JACCL_PROGRESS_TIMEOUT_MS / MLX_JACCL_PROGRESS_TIMEOUT_MS (default 30000 ms; 0 or a negative value removes the limit) is an error. The clock is read once per 1024 polls that return nothing, so the polling fast path gains a counter and no clock read. The failed call first destroys the group’s queue pairs and completion queues and deregisters its buffers; the ring does so only after all wires have returned. Then, by default (JACCL_TIMEOUT_ACTION / MLX_JACCL_TIMEOUT_ACTION = teardown-exit), it prints the reason, runs the memory release hook that MLX’s jaccl.cpp registers (set_wired_limit(0), then clear_cache(), at most 10 s) and leaves through std::_Exit(75), a restartable status. With throw it throws a [jaccl] std::runtime_error instead; every later call on that group throws immediately and the group cannot be reopened in the process. The ring keeps its own guarded dispatch_wires, which also reports the errors of the ring pool wires that it used to drop. A mesh with more than one wire (upstream’s second cable) has one MeshImpl, and so one guard, for each wire, and the wires of a MeshGroup share one failure flag: a failed wire closes its own queue pairs and buffers, a wire that waits in the same call stops with WireStopped and closes its own, and every later call on the group is refused. The mesh runs its wires through the shared dispatch_wires in threadpool.h, which upstream lets drop the error of a pool wire; the fork throws that error after all wires returned. A region that the verbs refuse to deregister is reported and kept for the destructor, as a refused queue pair or completion queue is. Each completion queue has four times the entries its queue pair can have outstanding (COMPLETION_QUEUE_DEPTH, used by mesh.cpp and ring.cpp when they create the queues). MLX’s jaccl.cpp registers the release hook each time it wraps a new JACCL group.

Startup readiness: a per-group one-shot budget of 1..900000 ms replaces the idle limit until its fixed monotonic deadline. Progress never renews it. Begin/end refuse running calls; callers drain queued work and serialize scheduling. End restores the original idle policy and refuses expired or closed groups. A mesh gives the budget to each of its wires. The MLX Group API forwards to JACCL only; unsupported backends refuse without fallback.

Advertised GID: Connection::info() advertises the IPv4-mapped GID of the port, but queue_pair_rtr sent from GID index 1 whatever the index of that GID. The connection now remembers the index where the advertised GID was found and sends from it; behaviour is unchanged where that index is 1.

tests/jaccl is a separate CMake project that the MLX build does not build; the build-cpp job of Fork Tests builds it and runs it. It compiles the real mesh, ring and RDMA headers against simulated verbs and checks the frame tails, the guard and the release path under ASan, UBSan and TSan.

diff --git ml-explore/mlx/docs/src/usage/distributed.rst Layr-Labs/mlx/docs/src/usage/distributed.rst index 861525dcbfcb6a6f654d1c6d508cb168dd7b511e..6566e42f2454133d3802df49309dc2951f5b1de5 100644 --- ml-explore/mlx/docs/src/usage/distributed.rst +++ Layr-Labs/mlx/docs/src/usage/distributed.rst @@ -401,6 +401,32 @@ backend="jaccl", all_gather_factory=make_side_channel, )   +A peer that does not answer +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +JACCL waits for RDMA completions in a polling loop. When the peer stops or the +link fails, no completion arrives. A JACCL call that gets no completion for +longer than :envvar:`MLX_JACCL_PROGRESS_TIMEOUT_MS` (30 seconds by default) +fails. A call that gets a failed completion fails immediately. + +A failed call closes the communication group: JACCL destroys the queue pairs +and the completion queues of the group and deregisters its buffers. Then, by +default, it releases the wired GPU memory of the process (it sets the wired +limit to zero and clears the buffer cache) and exits the process with status +75, so that a supervisor can restart it. This teardown exit is the default +because a rank that dies with RDMA work outstanding can leave its memory wired +until the machine restarts, and because the call often runs on a thread where +an exception cannot reach the program. + +With :envvar:`MLX_JACCL_TIMEOUT_ACTION` set to ``throw`` the call raises an +error instead and the process continues. Each later call on the closed group +raises an error immediately, and the group cannot be opened again. Start a new +process to communicate again. + +The time that a rank waits includes the time that its peer computes, for +example in :func:`mlx.core.distributed.recv`. Set the limit above the longest +such wait, or set it to ``0`` to remove the limit. + .. _nccl_section:   Getting Started with NCCL @@ -572,6 +598,13 @@ ["rdma_en5", null, "rdma_en3", "rdma_en4"], ["rdma_en4", "rdma_en3", null, "rdma_en5"], ["rdma_en3", "rdma_en4", "rdma_en5", null] ] + +:envvar:`MLX_JACCL_PROGRESS_TIMEOUT_MS` is optional. It contains the longest time +in milliseconds that a call waits for an RDMA completion before it fails and +closes the group. The default is 30000 and 0 removes the limit. +:envvar:`MLX_JACCL_TIMEOUT_ACTION` is optional. It selects what a failed call +does after it closed the group: ``teardown-exit`` (the default) releases the +GPU memory and exits the process with status 75, ``throw`` raises an error.   NCCL
diff --git ml-explore/mlx/mlx/distributed/distributed.cpp Layr-Labs/mlx/mlx/distributed/distributed.cpp index d8fca8b160ccd03a81b7e170a65562da2837d5ed..98cba6d7ac0351798451c34a2ff2613b7385f15b 100644 --- ml-explore/mlx/mlx/distributed/distributed.cpp +++ Layr-Labs/mlx/mlx/distributed/distributed.cpp @@ -138,6 +138,22 @@ Group Group::split(int color, int key /* = -1 */) const { return Group(group_->split(color, key)); }   +void Group::begin_startup_wait_budget(int64_t timeout_ms) const { + if (!group_) { + throw std::runtime_error( + "[distributed] Cannot set a budget on a null group."); + } + group_->begin_startup_wait_budget(timeout_ms); +} + +void Group::end_startup_wait_budget() const { + if (!group_) { + throw std::runtime_error( + "[distributed] Cannot end a budget on a null group."); + } + group_->end_startup_wait_budget(); +} + namespace {   std::unordered_map<std::string, std::shared_ptr<detail::GroupImpl>>&
diff --git ml-explore/mlx/mlx/distributed/distributed.h Layr-Labs/mlx/mlx/distributed/distributed.h index 0d6e4d41efdf89ab61320e3cab5f69525f897c49..fd312e133aaa14d4f2c6138a16beeb0623ba7714 100644 --- ml-explore/mlx/mlx/distributed/distributed.h +++ Layr-Labs/mlx/mlx/distributed/distributed.h @@ -3,6 +3,7 @@ #pragma once   #include <cstddef> +#include <cstdint> #include <functional> #include <memory>   @@ -60,6 +61,20 @@ * the key the smaller the rank. If the provided key is negative, then the * rank in the current group is used. */ Group split(int color, int key = -1) const; + + /** + * Start one JACCL readiness budget of 1..900000 ms from the current + * monotonic time. Progress does not renew it. Other backends refuse. + * Drain queued work and serialize scheduling around begin/end; both require + * no running calls. The budget cannot restart after end or expiry. + */ + void begin_startup_wait_budget(int64_t timeout_ms) const; + + /** + * End an unexpired budget and restore the original idle timeout for later + * calls. Refuses unused, ended, expired or failed groups; never reopens one. + */ + void end_startup_wait_budget() const;   const std::shared_ptr<detail::GroupImpl>& raw_group() const { return group_;
diff --git ml-explore/mlx/mlx/distributed/distributed_impl.h Layr-Labs/mlx/mlx/distributed/distributed_impl.h index d889587abcdb81b4538e97ea8df67f8c1d33c83d..32ac950a843496da9f348e1d35e5a8a89ef5a5af 100644 --- ml-explore/mlx/mlx/distributed/distributed_impl.h +++ Layr-Labs/mlx/mlx/distributed/distributed_impl.h @@ -21,6 +21,15 @@ virtual int rank() = 0; virtual int size() = 0; virtual std::shared_ptr<GroupImpl> split(int color, int key = -1) = 0;   + virtual void begin_startup_wait_budget(int64_t) { + throw std::runtime_error( + "[distributed] Startup wait budgets require a JACCL group."); + } + virtual void end_startup_wait_budget() { + throw std::runtime_error( + "[distributed] Startup wait budgets require a JACCL group."); + } + // Actual communication operations virtual void all_sum(const array& input, array& output, Stream stream) = 0; virtual void all_gather(const array& input, array& output, Stream stream) = 0; @@ -30,6 +39,22 @@ virtual void all_max(const array& input, array& output, Stream stream) = 0; virtual void all_min(const array& input, array& output, Stream stream) = 0; virtual void sum_scatter(const array& input, array& output, Stream stream) = 0; + + // Two ranks, on the calling thread (a CPU-stream task): send n bytes while + // the peer's n bytes land in recv. ready(end) tells if send[0, end) is + // final; it is polled and must not block. arrived(end) runs when + // recv[0, end) holds the peer's bytes. Neither callback may throw. + virtual bool supports_exchange() { + return false; + } + virtual void exchange( + const char* /* send */, + char* /* recv */, + size_t /* n */, + const std::function<bool(size_t)>& /* ready */, + const std::function<void(size_t)>& /* arrived */) { + throw std::runtime_error("[distributed] This group cannot exchange."); + } };   /* Define the MLX stream that the communication should happen in. */
diff --git ml-explore/mlx/mlx/distributed/jaccl/jaccl.cpp Layr-Labs/mlx/mlx/distributed/jaccl/jaccl.cpp index 99a4ac3be32e430f5ab8c48a4c9678f812b9a076..b18c465d3e51582baa12877980c8f3848a2953ab 100644 --- ml-explore/mlx/mlx/distributed/jaccl/jaccl.cpp +++ Layr-Labs/mlx/mlx/distributed/jaccl/jaccl.cpp @@ -4,9 +4,11 @@ #include "mlx/distributed/jaccl/jaccl.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/distributed/distributed_impl.h" #include "mlx/dtype_utils.h" +#include "mlx/memory.h"   #include <jaccl/group.h> #include <jaccl/jaccl.h> +#include <jaccl/progress_guard.h>   #include <optional> #include <sstream> @@ -78,6 +80,27 @@ int size() override { return group_->size(); }   + void begin_startup_wait_budget(int64_t timeout_ms) override { + group_->begin_startup_wait_budget(timeout_ms); + } + + void end_startup_wait_budget() override { + group_->end_startup_wait_budget(); + } + + bool supports_exchange() override { + return group_->supports_exchange(); + } + + void exchange( + const char* send, + char* recv, + size_t n, + const std::function<bool(size_t)>& ready, + const std::function<void(size_t)>& arrived) override { + group_->exchange(send, recv, n, ready, arrived); + } + void all_sum(const array& input, array& output, Stream stream) override { auto in_ptr = input.data<char>(); auto out_ptr = output.data<char>(); @@ -168,6 +191,31 @@ private: std::shared_ptr<::jaccl::Group> group_; };   +/** + * Run by a JACCL teardown exit (see progress_guard.h) after the group released + * its queue pairs. The exit skips static destructors, so release the wired GPU + * memory here: unwire first (the residency set shrinks to nothing), then drop + * the buffer cache. Best effort; it never throws into the exit path. + */ +void release_memory_before_exit() { + try { + set_wired_limit(0); + } catch (...) { + } + try { + clear_cache(); + } catch (...) { + } +} + +std::shared_ptr<GroupImpl> make_group(std::shared_ptr<::jaccl::Group> group) { + if (group == nullptr) { + return nullptr; + } + ::jaccl::set_memory_release(&release_memory_before_exit); + return std::make_shared<JACCLGroup>(std::move(group)); +} + } // namespace   bool is_available() { @@ -175,19 +223,11 @@ return ::jaccl::is_available(); }   std::shared_ptr<GroupImpl> init(bool strict /* = false */) { - auto group = ::jaccl::init(strict); - if (group == nullptr) { - return nullptr; - } - return std::make_shared<JACCLGroup>(std::move(group)); + return make_group(::jaccl::init(strict)); }   std::shared_ptr<GroupImpl> init(bool strict, AllGatherFactory factory) { - auto group = ::jaccl::init(strict, factory); - if (group == nullptr) { - return nullptr; - } - return std::make_shared<JACCLGroup>(std::move(group)); + return make_group(::jaccl::init(strict, factory)); }   } // namespace mlx::core::distributed::jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/README.md Layr-Labs/mlx/mlx/distributed/jaccl/lib/README.md index d682a06bbc4d83cc25f4b2ea118defb48af0c632..5e2bb9c7134a9d30328674842ec35f6807f2d784 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/README.md +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/README.md @@ -102,6 +102,27 @@ - **JACCL_COORDINATOR** / **MLX_JACCL_COORDINATOR**: IP:port of the coordinator (rank 0 listener) - **JACCL_RING** / **MLX_JACCL_RING**: (Optional) Prefer ring topology over mesh +- **JACCL_PROGRESS_TIMEOUT_MS** / **MLX_JACCL_PROGRESS_TIMEOUT_MS**: (Optional) + The longest time in milliseconds that a call waits for an RDMA completion. + The default is 30000. Zero or a negative value removes the limit. +- **JACCL_TIMEOUT_ACTION** / **MLX_JACCL_TIMEOUT_ACTION**: (Optional) What a + failed call does: `teardown-exit` (the default) or `throw`. Any other value + keeps the default. + +A call fails when it gets no completion for this time, a failed work +completion or a failed poll. It first destroys the queue pairs and completion +queues of the group and deregisters its buffers (the ring waits until all of +its wires have returned). With `teardown-exit` it then prints the reason, runs +the memory release hook registered with `jaccl::set_memory_release` (MLX +registers one that sets the wired limit to zero and clears the buffer cache; +it gets at most 10 seconds) and exits the process with status 75 (EX_TEMPFAIL, +restartable) through `std::_Exit`. With `throw` the caller gets the exception; +every later call on that group throws immediately, and the group cannot be +opened again in the same process. Set the limit above the longest time that a +rank can wait for a peer, for example in `recv` while the peer computes. + +Each completion queue has `4 * (MAX_SEND_WR + MAX_RECV_WR)` entries, four times +what its queue pair can have outstanding.   ### Device File Format   @@ -321,6 +342,26 @@ bool is_valid_ring() const; } ```   +## Tests + +`tests/jaccl` in the MLX repository has tests that do not use RDMA hardware. +They compile the mesh, ring and RDMA headers with a small stand-in for +`<infiniband/verbs.h>` and simulate the verbs. They check that each send frame +holds its payload and then only zero bytes, and that a call fails and the group +is closed when a completion does not arrive or reports a failure. The directory +is a separate CMake project, so the MLX build does not build it: + +```bash +cmake -S tests/jaccl -B build/jaccl-tests +cmake --build build/jaccl-tests +ctest --test-dir build/jaccl-tests --output-on-failure +``` + +The tests use AddressSanitizer and UndefinedBehaviorSanitizer. Configure with +`-DJACCL_TESTS_TSAN=ON` to use ThreadSanitizer. The guard tests measure time: a +stalled call must fail between its limit of 250 ms and one second after it, so +a machine under heavy load can make them fail. + ## License   JACCL is part of MLX and is released under the same license. @@ -331,3 +372,41 @@ The name JACCL (pronounced Jackal) stands for Jack and Angelos’ Collective Communication Library and it is an obvious pun to Nvidia’s NCCL but also tribute to Jack Beasley who led the development of RDMA over Thunderbolt at Apple. + +### One-shot startup readiness budget + +MLX callers can use `Group::begin_startup_wait_budget(int64_t timeout_ms) const` +and `Group::end_startup_wait_budget() const` on an initialized JACCL group. +The standalone JACCL group exposes the same operations. Other MLX backends +and unsupported JACCL group implementations throw; there is no fallback. + +Begin accepts 1..900000 ms and checks the monotonic deadline before publishing +state. Each actual mesh or ring group owns one policy shared by its wires. +The deadline starts at begin, includes time spent loading, and stays fixed +across calls and completions. During startup it replaces the idle limit. +Successful completions check expiry too; empty polls sample it every 1024 +polls. This bounds polling waits, not arbitrary computation or blocked system +calls. Keep the embedding runtime's hard startup deadline and cancellation. + +Drain queued work and serialize scheduling around begin and end. A running +call makes either transition fail. The caller must retain the group and must +not move/destroy its implementation while calls run. This API does not make +concurrent initialization or backend-cache clearing safe. + +Only an unused group can begin. Invalid arguments or deadline overflow leave +it unused. Only an active, unexpired, open and idle group can end; duplicate +end is refused. Expiry cannot be cleared by end, and begin can never renew or +reopen a used budget. Expiry observed by polling follows the existing failure +path: stop wires, close resources, then the configured throw or teardown-exit +with status 75 and the memory release hook. Ending does not create a transport +success, clear a failure, or reopen a group. + +After a successful end, later calls use the original environment/default idle +policy (normally 30000 ms). Existing zero/negative environment handling stays +unchanged, but the startup API always requires a positive finite budget. +The API accepts a relative duration; an external absolute deadline must still +be checked by the caller because dispatch/bridge time precedes core begin. + +`tests/jaccl/startup_wait_budget_tests.cpp` uses a controllable clock with the +real policy/guard. The group tests exercise real mesh/ring dispatch and cleanup +against simulated verbs. These CPU tests do not qualify native RDMA or loading.
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/group.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/group.h index 603765a5115126949370ae2f97c443c8fc1ae23f..c413287f1792486e5f2296eea288323ad7404de8 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/group.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/group.h @@ -3,7 +3,10 @@ #pragma once   #include <cstddef> +#include <cstdint> +#include <functional> #include <memory> +#include <stdexcept>   namespace jaccl {   @@ -17,6 +20,13 @@ virtual int rank() = 0; virtual int size() = 0;   + virtual void begin_startup_wait_budget(int64_t) { + throw std::runtime_error("[jaccl] Startup wait budget is unsupported."); + } + virtual void end_startup_wait_budget() { + throw std::runtime_error("[jaccl] Startup wait budget is unsupported."); + } + virtual void all_sum(const void* input, void* output, size_t n_bytes, int dtype) = 0;   @@ -41,6 +51,23 @@ virtual void send(const void* input, size_t n_bytes, int dst) = 0; virtual void recv(void* output, size_t n_bytes, int src) = 0; virtual void barrier() = 0; + + /** + * Two ranks: send n_bytes while the peer's n_bytes land in output. A frame + * goes out when ready(end) says input[0, end) is final; arrived(end) runs + * when output[0, end) is filled. See MeshImpl::exchange. + */ + virtual bool supports_exchange() { + return false; + } + virtual void exchange( + const char* /* input */, + char* /* output */, + size_t /* n_bytes */, + const std::function<bool(size_t)>& /* ready */, + const std::function<void(size_t)>& /* arrived */) { + throw std::runtime_error("[jaccl] This group cannot exchange."); + } };   /**
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.cpp Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.cpp index fe856faf971a86bd374cf9cb428e072ca5d9722a..5470ff1342386a819db5a50e832178e2c845fe4f 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.cpp +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.cpp @@ -32,10 +32,16 @@ // Make sure every node has reached here before continuing side_channel_.barrier();   - // Create the mesh implementation objects + // Create the mesh implementation objects. The wires share one failure flag. + auto failed = std::make_shared<std::atomic<bool>>(false); for (int w = 0; w < n_wires_; w++) { meshes_.emplace_back( - rank_, size_, connections_[w], buffers_[w], scatter_buffers_[w]); + rank_, + size_, + connections_[w], + buffers_[w], + scatter_buffers_[w], + failed); } }   @@ -47,7 +53,7 @@ if (conn.ctx == nullptr) { continue; } conn.allocate_protection_domain(); - conn.create_completion_queue(MAX_SEND_WR + MAX_RECV_WR); + conn.create_completion_queue(COMPLETION_QUEUE_DEPTH); conn.create_queue_pair(); } }
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.h index aa19fddb8c86a8c44279e60d3e275d5e86615729..d31da3d9772bbbd4613a38aa199569648276ffef 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh.h @@ -33,6 +33,19 @@ int size() override { return size_; }   + // Every wire gets the budget. + void begin_startup_wait_budget(int64_t timeout_ms) override { + for (auto& mesh : meshes_) { + mesh.begin_startup_wait_budget(timeout_ms); + } + } + + void end_startup_wait_budget() override { + for (auto& mesh : meshes_) { + mesh.end_startup_wait_budget(); + } + } + void all_sum(const void* input, void* output, size_t n_bytes, int dtype) override;   @@ -51,6 +64,20 @@ void send(const void* input, size_t n_bytes, int dst) override; void recv(void* output, size_t n_bytes, int src) override;   void barrier() override; + + bool supports_exchange() override { + return size_ == 2; + } + + void exchange( + const char* input, + char* output, + size_t n_bytes, + const std::function<bool(size_t)>& ready, + const std::function<void(size_t)>& arrived) override { + // An exchange runs on the first wire only. + meshes_[0].exchange(input, output, n_bytes, ready, arrived); + }   private: template <typename T, typename ReduceOp>
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index 7beed48e642ed432662aa38278b4b4c17732d08d..aa6ae9e2cd835d00c5df13648ebebf4b4290f13a 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -2,9 +2,12 @@ // Copyright © 2026 Apple Inc.   #pragma once   +#include <atomic> +#include <exception> #include <memory> #include <span>   +#include "jaccl/progress_guard.h" #include "jaccl/rdma.h"   constexpr int MESH_MAX_PEERS = 8; @@ -21,17 +24,27 @@ int rank, int size, std::vector<Connection>& conns, std::vector<SharedBuffer>& buffers, - std::vector<SharedBuffer>& scatter_buffers) + std::vector<SharedBuffer>& scatter_buffers, + std::shared_ptr<std::atomic<bool>> failed = + std::make_shared<std::atomic<bool>>(false)) : rank_(rank), size_(size), connections_(conns), buffers_(buffers), scatter_buffers_(scatter_buffers), - staging_mem_( - std::make_unique<char[]>(MESH_PIPELINE * MAX_BUFFER_SIZE)) {} + staging_mem_(std::make_unique<char[]>(MESH_PIPELINE * MAX_BUFFER_SIZE)), + failed_(std::move(failed)) {}   MeshImpl() : rank_(0), size_(1) {}   + void begin_startup_wait_budget(int64_t timeout_ms) { + wait_budget_->begin(timeout_ms, *failed_); + } + + void end_startup_wait_budget() { + wait_budget_->end(*failed_); + } + template <typename T, typename ReduceOp> void all_reduce(const T* in, T* out, int64_t size, ReduceOp reduce_op) { // Fully connected all reduce with deterministic reduction order. @@ -42,9 +55,14 @@ // // Our own data is copied to a staging buffer to ensure we can reduce it in // the output when needed.   + Call call(*this, "mesh all_reduce"); auto [sz, buffer_size] = buffer_size_from_message(size * sizeof(T)); int64_t N = buffer_size / sizeof(T); - constexpr int PIPELINE = 2; + // Frames in flight per peer (staging holds this many; NUM_BUFFERS >= it). + constexpr int PIPELINE = MESH_PIPELINE; + static_assert( + MESH_PIPELINE <= NUM_BUFFERS, + "mesh pipeline exceeds registered buffers"); constexpr int WC_NUM = PIPELINE * MESH_MAX_PEERS * 2; int64_t total = static_cast<int64_t>(size); int num_peers = size_ - 1; @@ -74,10 +92,7 @@ // Copy the local data to send buffer and staging buffer int64_t elems = std::min(N, total - read_offset); std::copy( in + read_offset, in + read_offset + elems, local_staging(buff)); - std::copy( - in + read_offset, - in + read_offset + elems, - send_buffer(sz, buff).begin<T>()); + send_buffer(sz, buff).stage_send(in + read_offset, elems); recv_end[rank_]++; post_send_all(sz, buff);   @@ -101,6 +116,7 @@ // If a receive is completed then advance the pointer of completed // receives. ibv_wc wc[WC_NUM]; int n = poll(connections_, WC_NUM, wc); + call.check(wc, n); for (int i = 0; i < n; i++) { int work_type = wc[i].wr_id >> 16; int buff = (wc[i].wr_id >> 8) & 0xff; @@ -112,10 +128,7 @@ if (work_type == SEND_WR && read_offset < total) { completed_send_count[buff]++; if (completed_send_count[buff] == num_peers) { int64_t elems = std::min(N, total - read_offset); - std::copy( - in + read_offset, - in + read_offset + elems, - send_buffer(sz, buff).begin<T>()); + send_buffer(sz, buff).stage_send(in + read_offset, elems); post_send_all(sz, buff);   completed_send_count[buff] = 0; @@ -198,6 +211,7 @@ // Drain remaining in-flight completions (outstanding sends). while (in_flight > 0) { ibv_wc wc[WC_NUM]; int n = poll(connections_, WC_NUM, wc); + call.check(wc, n); in_flight -= n; } } @@ -207,6 +221,8 @@ const char* in_ptr, char* out_ptr, int64_t n_bytes, int64_t stride) { + Call call(*this, "mesh all_gather"); + // Copy our data to the appropriate place. Skip when in place (the scatter // gather all reduce passes our own reduced shard which already lives at // out_ptr + rank_ * stride). @@ -225,18 +241,16 @@ int num_peers = size_ - 1;   // Counters to maintain the state of transfers int in_flight = 0; - int read_offset = 0; + int64_t read_offset = 0; int completed_send_count[PIPELINE] = {0}; - int write_offset[MESH_MAX_PEERS] = {0}; + int64_t write_offset[MESH_MAX_PEERS] = {0};   // Prefill the pipeline int buff = 0; while (read_offset < total && buff < PIPELINE) { post_recv_all(sz, buff); - std::copy( - our_data + read_offset, - our_data + std::min(read_offset + N, total), - send_buffer(sz, buff).begin<char>()); + send_buffer(sz, buff).stage_send( + our_data + read_offset, std::min(N, total - read_offset)); post_send_all(sz, buff);   buff++; @@ -250,6 +264,7 @@ // Keep going until we have no longer data in flight. while (in_flight > 0) { ibv_wc wc[WC_NUM]; int n = poll(connections_, WC_NUM, wc); + call.check(wc, n); for (int i = 0; i < n; i++) { int work_type = wc[i].wr_id >> 16; int buff = (wc[i].wr_id >> 8) & 0xff; @@ -261,10 +276,8 @@ // Send completed. If all sends completed then send the next chunk. if (work_type == SEND_WR && read_offset < total) { completed_send_count[buff]++; if (completed_send_count[buff] == num_peers) { - std::copy( - our_data + read_offset, - our_data + std::min(read_offset + N, total), - send_buffer(sz, buff).begin<char>()); + send_buffer(sz, buff).stage_send( + our_data + read_offset, std::min(N, total - read_offset)); post_send_all(sz, buff);   completed_send_count[buff] = 0; @@ -290,6 +303,90 @@ } } }   + // Two ranks: send n_bytes from in_ptr while the peer's n_bytes land in + // out_ptr, with no self copy. Frame j goes out when ready(end of frame j) + // tells that its bytes are final. ready is polled between completions, so + // the receives are posted again in time. arrived(end) runs when + // out_ptr[0, end) is filled. The last frame uses the smallest buffer that + // holds it. Both ranks size each frame from n_bytes. + void exchange( + const char* in_ptr, + char* out_ptr, + int64_t n_bytes, + const std::function<bool(size_t)>& ready, + const std::function<void(size_t)>& arrived) { + if (size_ != 2 || n_bytes <= 0) { + throw std::invalid_argument( + "[jaccl] An exchange needs two ranks and a nonempty message."); + } + Call call(*this, "mesh exchange"); + const int peer = 1 - rank_; + const int top = buffer_size_from_message(MAX_BUFFER_SIZE).first; + const int64_t N = int64_t(FRAME_SIZE) << top; + const int64_t frames = (n_bytes + N - 1) / N; + auto length = [&](int64_t j) { return std::min(N, n_bytes - j * N); }; + auto size_class = [&](int64_t j) { + int sz = 0; + while (sz < top && (int64_t(FRAME_SIZE) << sz) < length(j)) { + sz++; + } + return sz; + }; + constexpr int PIPELINE = MESH_PIPELINE; + constexpr int WC_NUM = 2 * PIPELINE; + + int64_t recv_posted = 0; + int64_t received = 0; + int64_t sent = 0; + int64_t send_done = 0; + bool send_busy[PIPELINE] = {}; + auto post_recv = [&]() { + recv_from(size_class(recv_posted), peer, int(recv_posted % PIPELINE)); + recv_posted++; + }; + auto post_ready_sends = [&]() { + while (sent < frames && !send_busy[sent % PIPELINE] && + ready(size_t(sent * N + length(sent)))) { + int buff = int(sent % PIPELINE); + int sz = size_class(sent); + send_buffer(sz, buff).stage_send(in_ptr + sent * N, length(sent)); + send_to(sz, peer, buff); + send_busy[buff] = true; + sent++; + } + }; + + while (recv_posted < std::min<int64_t>(PIPELINE, frames)) { + post_recv(); + } + post_ready_sends(); + while (received < frames || send_done < frames) { + ibv_wc wc[WC_NUM]; + int n = connections_[peer].poll(WC_NUM, wc); + call.check(wc, n); + for (int i = 0; i < n; i++) { + int work_type = wc[i].wr_id >> 16; + int buff = (wc[i].wr_id >> 8) & 0xff; + if (work_type == SEND_WR) { + send_busy[buff] = false; + send_done++; + } else { + // Receives complete in the order they were posted. + std::memcpy( + out_ptr + received * N, + recv_buffer(size_class(received), buff, peer).begin<char>(), + length(received)); + received++; + if (recv_posted < frames) { + post_recv(); + } + arrived(size_t(std::min(n_bytes, received * N))); + } + } + post_ready_sends(); + } + } + template <typename T, typename ReduceOp> void sum_scatter( const T* in, @@ -310,6 +407,7 @@ // Unlike all_reduce/all_gather each peer receives a *different* chunk, so // we use the dedicated scatter buffers: per (sz, buff) tile there are size_ // send slots (slot p -> peer p) and size_ recv slots (slot p <- peer p).   + Call call(*this, "mesh sum_scatter"); const T* our_chunk = in + static_cast<int64_t>(rank_) * stride;   auto [sz, buffer_size] = buffer_size_from_message(count * sizeof(T)); @@ -340,8 +438,7 @@ if (p == rank_) { continue; } const T* src = in + static_cast<int64_t>(p) * stride + read_offset; - std::copy( - src, src + elems, scatter_send_buffer(sz, buff, p).begin<T>()); + scatter_send_buffer(sz, buff, p).stage_send(src, elems); } scatter_post_send_all(sz, buff);   @@ -356,6 +453,7 @@ // Keep going until we have no longer data in flight. while (in_flight > 0) { ibv_wc wc[WC_NUM]; int n = poll(connections_, WC_NUM, wc); + call.check(wc, n); for (int i = 0; i < n; i++) { int work_type = wc[i].wr_id >> 16; int buff = (wc[i].wr_id >> 8) & 0xff; @@ -375,10 +473,7 @@ continue; } const T* src = in + static_cast<int64_t>(p) * stride + read_offset; - std::copy( - src, - src + elems, - scatter_send_buffer(sz, buff, p).begin<T>()); + scatter_send_buffer(sz, buff, p).stage_send(src, elems); } scatter_post_send_all(sz, buff);   @@ -456,6 +551,7 @@ } }   void send(const char* in_ptr, int64_t n_bytes, int dst) { + Call call(*this, "mesh send"); constexpr int PIPELINE = 2; constexpr int WC_NUM = PIPELINE; auto [sz, N] = buffer_size_from_message(n_bytes); @@ -466,10 +562,8 @@ // Prefill the pipeline int buff = 0; while (read_offset < n_bytes && buff < PIPELINE) { - std::copy( - in_ptr + read_offset, - in_ptr + std::min(read_offset + N, n_bytes), - send_buffer(sz, buff).begin<char>()); + send_buffer(sz, buff).stage_send( + in_ptr + read_offset, std::min(N, n_bytes - read_offset)); send_to(sz, dst, buff);   buff++; @@ -485,6 +579,7 @@ // If a send was completed and we have more data to send then go ahead // and send them. ibv_wc wc[WC_NUM]; int n = connections_[dst].poll(WC_NUM, wc); + call.check(wc, n); for (int i = 0; i < n; i++) { int buff = (wc[i].wr_id >> 8) & 0xff; int rank = wc[i].wr_id & 0xff; @@ -492,10 +587,8 @@ in_flight--;   if (read_offset < n_bytes) { - std::copy( - in_ptr + read_offset, - in_ptr + std::min(read_offset + N, n_bytes), - send_buffer(sz, buff).begin<char>()); + send_buffer(sz, buff).stage_send( + in_ptr + read_offset, std::min(N, n_bytes - read_offset)); send_to(sz, dst, buff);   read_offset += N; @@ -506,6 +599,7 @@ } }   void recv(char* out_ptr, int64_t n_bytes, int src) { + Call call(*this, "mesh recv"); constexpr int PIPELINE = 2; constexpr int WC_NUM = PIPELINE; auto [sz, N] = buffer_size_from_message(n_bytes); @@ -530,6 +624,7 @@ // If a recv was completed copy it to the output and if we have more // data to fetch post another recv. ibv_wc wc[WC_NUM]; int n = connections_[src].poll(WC_NUM, wc); + call.check(wc, n); for (int i = 0; i < n; i++) { int buff = (wc[i].wr_id >> 8) & 0xff; int rank = wc[i].wr_id & 0xff; @@ -553,6 +648,48 @@ } }   private: + // One call into the group. It refuses a closed group, and it closes the + // group when the call ends with an exception. Unless the failure action is + // Throw, it then leaves the process through teardown_exit(). + class Call : public ProgressGuard { + public: + Call(MeshImpl& mesh, const char* op) + : ProgressGuard(op, *mesh.failed_, mesh.wait_budget_.get()), + mesh_(mesh), + exceptions_(std::uncaught_exceptions()) { + require_open(*mesh.failed_); + } + + ~Call() { + if (std::uncaught_exceptions() > exceptions_) { + mesh_.close(); + if (failure_action() == FailureAction::TeardownExit) { + teardown_exit( + failure().empty() ? "[jaccl] A mesh call failed with an error." + : failure().c_str()); + } + } + } + + private: + MeshImpl& mesh_; + int exceptions_; + }; + + // Cancel the posted work and unpin the buffers. + void close() { + failed_->store(true); + for (auto& c : connections_) { + c.release(); + } + for (auto& b : buffers_) { + b.deregister(); + } + for (auto& b : scatter_buffers_) { + b.deregister(); + } + } + void send_to(int sz, int rank, int buff) { connections_[rank].post_send( send_buffer(sz, buff), SEND_WR << 16 | buff << 8 | rank); @@ -640,6 +777,12 @@ std::span<Connection> connections_; std::span<SharedBuffer> buffers_; std::span<SharedBuffer> scatter_buffers_; std::unique_ptr<char[]> staging_mem_; + std::unique_ptr<StartupWaitBudget> wait_budget_ = + std::make_unique<StartupWaitBudget>(); + // Shared by the wires of one group, so that a failure on one wire stops the + // others and closes the group for every later call. + std::shared_ptr<std::atomic<bool>> failed_ = + std::make_shared<std::atomic<bool>>(false); };   } // namespace jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/progress_guard.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/progress_guard.h new file mode 100644 index 0000000000000000000000000000000000000000..4a56deb37c9b63daf1ed77f87ddaa01c69a1820d --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/progress_guard.h @@ -0,0 +1,286 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include <infiniband/verbs.h> + +#include <atomic> +#include <cerrno> +#include <chrono> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <exception> +#include <sstream> +#include <stdexcept> +#include <string> +#include <thread> + +#include "jaccl/startup_wait_budget.h" + +namespace jaccl { + +constexpr int64_t DEFAULT_PROGRESS_TIMEOUT_MS = 30000; +// The clock is read once per this number of polls without a completion. +constexpr int64_t PROGRESS_SAMPLE_POLLS = 1024; + +/** + * The longest time in milliseconds that a call waits for a completion. It is + * read once from JACCL_PROGRESS_TIMEOUT_MS / MLX_JACCL_PROGRESS_TIMEOUT_MS. + * Zero or a negative value removes the limit. + */ +inline int64_t progress_timeout_ms() { + static const int64_t timeout = []() -> int64_t { + const char* value = std::getenv("JACCL_PROGRESS_TIMEOUT_MS"); + if (value == nullptr) { + value = std::getenv("MLX_JACCL_PROGRESS_TIMEOUT_MS"); + } + if (value == nullptr) { + return DEFAULT_PROGRESS_TIMEOUT_MS; + } + // Keep the default when the value is not a number. + char* end = nullptr; + errno = 0; + long long parsed = std::strtoll(value, &end, 10); + if (end == value || *end != '\0' || errno == ERANGE) { + return DEFAULT_PROGRESS_TIMEOUT_MS; + } + return parsed; + }(); + return timeout; +} + +// What a call does after it failed and closed its group. +enum class FailureAction { + // Release the group, run the memory release hook, exit with status 75. + TeardownExit, + // Throw to the caller; the process continues with the group closed. + Throw, +}; + +// EX_TEMPFAIL: the failure is temporary and the process can be restarted. +constexpr int TEARDOWN_EXIT_STATUS = 75; +// The memory release hook gets this long, then the process exits anyway. +constexpr int64_t TEARDOWN_RELEASE_LIMIT_MS = 10000; + +/** + * The action after a failed call. It is read once from JACCL_TIMEOUT_ACTION / + * MLX_JACCL_TIMEOUT_ACTION: "teardown-exit" (the default) or "throw". Any + * other value keeps the default. + */ +inline FailureAction failure_action() { + static const FailureAction action = []() { + const char* value = std::getenv("JACCL_TIMEOUT_ACTION"); + if (value == nullptr) { + value = std::getenv("MLX_JACCL_TIMEOUT_ACTION"); + } + if (value != nullptr && std::strcmp(value, "throw") == 0) { + return FailureAction::Throw; + } + return FailureAction::TeardownExit; + }(); + return action; +} + +// Releases the memory of the embedding library before a teardown exit, for +// example the wired GPU buffers that would otherwise stay wired after the +// process is gone. It must not throw. +using MemoryRelease = void (*)(); + +inline std::atomic<MemoryRelease>& memory_release_hook() { + static std::atomic<MemoryRelease> hook{nullptr}; + return hook; +} + +// Register the hook that teardown_exit() runs. The last registration wins. +inline void set_memory_release(MemoryRelease release) { + memory_release_hook().store(release); +} + +/** + * Leave the process after a failed call when the action is teardown-exit. + * The caller has already destroyed the queue pairs and completion queues of + * the group and deregistered its buffers. This prints the reason, runs the + * memory release hook (at most TEARDOWN_RELEASE_LIMIT_MS), then exits with + * TEARDOWN_EXIT_STATUS without running atexit handlers or static destructors. + * Only the first caller does so; a thread that fails at the same time waits + * for that exit. + */ +[[noreturn]] inline void teardown_exit(const char* reason) noexcept { + static std::atomic<bool> exiting{false}; + if (exiting.exchange(true)) { + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + } + std::fprintf( + stderr, + "%s\n[jaccl] The group is released; releasing memory, then " + "exiting with status %d (JACCL_TIMEOUT_ACTION=teardown-exit).\n", + reason, + TEARDOWN_EXIT_STATUS); + std::fflush(stderr); + MemoryRelease release = memory_release_hook().load(); + if (release != nullptr) { + try { + std::thread([] { + std::this_thread::sleep_for( + std::chrono::milliseconds(TEARDOWN_RELEASE_LIMIT_MS)); + std::fprintf( + stderr, + "[jaccl] The memory release did not finish in %lld ms; exiting.\n", + static_cast<long long>(TEARDOWN_RELEASE_LIMIT_MS)); + std::fflush(stderr); + std::_Exit(TEARDOWN_EXIT_STATUS); + }).detach(); + } catch (...) { + // Without the time limit the release still runs. + } + try { + release(); + } catch (...) { + // The hook must not throw; the exit goes ahead. + } + } + std::fprintf( + stderr, + "[jaccl] %s; exiting with status %d.\n", + release != nullptr ? "Memory released" : "No memory release registered", + TEARDOWN_EXIT_STATUS); + std::fflush(stderr); + std::_Exit(TEARDOWN_EXIT_STATUS); +} + +// The text of an exception, for teardown_exit(). +inline std::string describe(const std::exception_ptr& error) { + try { + std::rethrow_exception(error); + } catch (const std::exception& e) { + return e.what(); + } catch (...) { + return "[jaccl] A call failed with an exception that is not std::exception."; + } +} + +// Thrown in a wire when a different wire of the same call failed first. +struct WireStopped : std::runtime_error { + WireStopped() + : std::runtime_error( + "[jaccl] Stopped because a different wire of the call failed.") {} +}; + +// Refuse a group that an earlier failure closed. +inline void require_open(const std::atomic<bool>& failed) { + if (failed.load()) { + throw std::runtime_error( + "[jaccl] The group is closed after an earlier failure and cannot be " + "used again."); + } +} + +/** + * Stops a polling loop that makes no progress. Call check() after each poll. + * + * check() throws when a completion reports a failure, when the poll fails or + * when no completion arrived for longer than the timeout. It sets `failed` + * before it throws, which also stops the other wires of the same call. The + * owner of the group closes it and then, unless failure_action() is Throw, + * calls teardown_exit(). + */ +template <typename Clock = std::chrono::steady_clock> +class BasicProgressGuard { + public: + BasicProgressGuard( + const char* op, + std::atomic<bool>& failed, + BasicStartupWaitBudget<Clock>* startup = nullptr) + : op_(op), failed_(failed), timeout_ms_(progress_timeout_ms()) { + if (startup != nullptr) { + call_.emplace(*startup); + startup_deadline_ = call_->deadline(); + } + } + + void check(const ibv_wc* wc, int n) { + if (startup_deadline_ && + (n != 0 || ++startup_polls_ % PROGRESS_SAMPLE_POLLS == 0)) { + if (failed_.load()) { + throw WireStopped(); + } + if (Clock::now() >= *startup_deadline_) { + fail("the absolute startup wait budget expired"); + } + } + if (n > 0) { + idle_polls_ = 0; + for (int i = 0; i < n; i++) { + if (wc[i].status != IBV_WC_SUCCESS) { + std::ostringstream msg; + msg << "a work completion failed with status " << wc[i].status + << " (vendor error " << wc[i].vendor_err << ", id 0x" << std::hex + << wc[i].wr_id << ")"; + fail(msg.str()); + } + } + } else if (n < 0) { + fail("the completion queue could not be polled"); + } else if (++idle_polls_ % PROGRESS_SAMPLE_POLLS == 0) { + check_idle(); + } + } + + protected: + // The error that check() threw, or empty. + const std::string& failure() const { + return failure_; + } + + private: + void check_idle() { + if (failed_.load()) { + throw WireStopped(); + } + if (startup_deadline_ || timeout_ms_ <= 0) { + return; + } + auto now = Clock::now(); + // The first sample after a completion starts the measurement. + if (idle_polls_ == PROGRESS_SAMPLE_POLLS) { + idle_since_ = now; + return; + } + int64_t idle_ms = + std::chrono::duration_cast<std::chrono::milliseconds>(now - idle_since_) + .count(); + if (idle_ms > timeout_ms_) { + std::ostringstream msg; + msg << "no completion for " << idle_ms + << " ms (JACCL_PROGRESS_TIMEOUT_MS is " << timeout_ms_ << ")"; + fail(msg.str()); + } + } + + [[noreturn]] void fail(const std::string& reason) { + failed_.store(true); + std::ostringstream msg; + msg << "[jaccl] " << op_ << ": " << reason + << ". The group is closed and cannot be used again."; + failure_ = msg.str(); + throw std::runtime_error(failure_); + } + + const char* op_; + std::atomic<bool>& failed_; + int64_t timeout_ms_; + int64_t idle_polls_{0}; + typename Clock::time_point idle_since_; + std::optional<typename BasicStartupWaitBudget<Clock>::Call> call_; + std::optional<typename Clock::time_point> startup_deadline_; + uint64_t startup_polls_{0}; + std::string failure_; +}; + +using ProgressGuard = BasicProgressGuard<>; + +} // namespace jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.cpp Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.cpp index f449d8c814372d811d170983842a2198465dacdd..478a4d9f573842e163c7597e824929ce57d25376 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.cpp +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.cpp @@ -123,6 +123,7 @@ std::swap(protection_domain, c.protection_domain); std::swap(completion_queue, c.completion_queue); std::swap(queue_pair, c.queue_pair); std::swap(src, c.src); + std::swap(source_gid_index, c.source_gid_index); }   Connection::~Connection() { @@ -196,6 +197,7 @@ if (ibv().query_gid(ctx, 1, i, &tmp) == 0) { if (*(uint64_t*)&tmp.raw[0] == 0 && *(uint16_t*)&tmp.raw[8] == 0 && *(uint16_t*)&tmp.raw[10] == 0xffff) { gid = tmp; + source_gid_index = i; found_gid = true; break; } @@ -255,7 +257,9 @@ if (dst.global_identifier.global.interface_id) { attr.ah_attr.is_global = 1; attr.ah_attr.grh.hop_limit = 1; attr.ah_attr.grh.dgid = dst.global_identifier; - attr.ah_attr.grh.sgid_index = 1; + // Send from the GID the peer was told about. Its position depends on + // which other addresses the interface has; it is not always index 1. + attr.ah_attr.grh.sgid_index = source_gid_index; }   int mask = IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN |
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.h index 01d9ed37d600be7b6d969512d6943769bd1d0f31..6b719b69c49cbac73943bc17953e7cd520452161 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/rdma.h @@ -5,12 +5,14 @@ #include <infiniband/verbs.h>   #include <functional> +#include <iostream> #include <mutex> #include <span> #include <sstream> #include <unordered_map> #include <vector>   +#include "jaccl/send_frame.h" #include "jaccl/tcp.h"   constexpr const char* IBV_TAG = "[jaccl]"; @@ -18,7 +20,11 @@ constexpr int SEND_WR = 1; constexpr int RECV_WR = 2; constexpr int MAX_SEND_WR = 32; constexpr int MAX_RECV_WR = 32; -constexpr int BUFFER_SIZES = 8; +// Each completion queue has four times the entries its queue pair can have +// outstanding. A queue sized exactly to the outstanding work has no headroom, +// and a provider may drop a completion on a full queue without an error. +constexpr int COMPLETION_QUEUE_DEPTH = 4 * (MAX_SEND_WR + MAX_RECV_WR); +constexpr int BUFFER_SIZES = 9; constexpr int NUM_BUFFERS = 2; constexpr int FRAME_SIZE = 4096;   @@ -109,6 +115,21 @@ SharedBuffer& operator=(const SharedBuffer&) = delete;   void register_to_protection_domain(ibv_pd* protection_domain);   + // Unpin the memory. The buffer cannot be posted after this call. A region + // that the verbs refuse to deregister is reported and kept, so that the + // destructor tries again. + void deregister() { + for (auto it = memory_regions_.begin(); it != memory_regions_.end();) { + if (int status = ibv().dereg_mr(it->second); status != 0) { + std::cerr << IBV_TAG << " Could not deregister a memory region (" + << status << ")" << std::endl; + ++it; + } else { + it = memory_regions_.erase(it); + } + } + } + size_t size() const { return num_bytes_; } @@ -126,6 +147,12 @@ return entry; }   template <typename T> + void stage_send(const T* source, int64_t count) { + stage_send_frame( + std::span<char>(static_cast<char*>(data_), size()), source, count); + } + + template <typename T> T* data() { return static_cast<T*>(data_); } @@ -159,6 +186,8 @@ ibv_pd* protection_domain; ibv_cq* completion_queue; ibv_qp* queue_pair; Destination src; // holds the local information + // Index in the port's GID table of the GID advertised in `src`. + int source_gid_index = 1;   Connection(ibv_context* ctx_); Connection(Connection&& c); @@ -217,6 +246,27 @@ int poll(int num_completions, ibv_wc* work_completions) { return ibv_poll_cq(completion_queue, num_completions, work_completions); } + + // Destroy the queue pair and the completion queue, which cancels the posted + // work. The connection cannot be used after this call. + void release() { + if (queue_pair != nullptr) { + if (int status = ibv().destroy_qp(queue_pair); status != 0) { + std::cerr << IBV_TAG << " Could not destroy a queue pair (" << status + << ")" << std::endl; + } else { + queue_pair = nullptr; + } + } + if (completion_queue != nullptr) { + if (int status = ibv().destroy_cq(completion_queue); status != 0) { + std::cerr << IBV_TAG << " Could not destroy a completion queue (" + << status << ")" << std::endl; + } else { + completion_queue = nullptr; + } + } + } };   std::vector<Connection> create_connections( @@ -239,6 +289,10 @@ int n = ibv_poll_cq( c.completion_queue, num_completions - completions, work_completions + completions); + // Report a failed poll instead of adding it to the count. + if (n < 0) { + return n; + }   completions += n; } @@ -250,13 +304,15 @@ std::span<const Connection> connections_1, std::span<const Connection> connections_2, int num_completions, ibv_wc* work_completions) { - int completions = 0; - completions += poll(connections_1, num_completions, work_completions); - completions += poll( + int completions = poll(connections_1, num_completions, work_completions); + if (completions < 0) { + return completions; + } + int n = poll( connections_2, num_completions - completions, work_completions + completions); - return completions; + return n < 0 ? n : completions + n; }   /**
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring.cpp Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring.cpp index a08035f3f325dd0563f5321b77b7cd4bd9209d56..c161ab8f417f25db285ed3a0c63d79701a66f73b 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring.cpp +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring.cpp @@ -41,12 +41,12 @@ void RingGroup::initialize() { // Create the queue pairs for (auto& conn : left_) { conn.allocate_protection_domain(); - conn.create_completion_queue(MAX_SEND_WR + MAX_RECV_WR); + conn.create_completion_queue(COMPLETION_QUEUE_DEPTH); conn.create_queue_pair(); } for (auto& conn : right_) { conn.allocate_protection_domain(); - conn.create_completion_queue(MAX_SEND_WR + MAX_RECV_WR); + conn.create_completion_queue(COMPLETION_QUEUE_DEPTH); conn.create_queue_pair(); }   @@ -218,7 +218,7 @@ auto in_ptr = static_cast<const T*>(input); auto out_ptr = static_cast<T*>(output); int64_t count = n_bytes / sizeof(T);   - if (n_bytes <= 32768 || count < size_ * 2 * n_conns_) { + if (n_bytes <= 32768 || count < static_cast<int64_t>(size_) * 2 * n_conns_) { ring_.all_reduce<1, T, ReduceOp>(in_ptr, out_ptr, count, 1, reduce_op); return; } @@ -246,7 +246,7 @@ int64_t total = static_cast<int64_t>(size_) * count;   // Mirror the all_reduce heuristics: use a single wire for small messages and // scale up to n_conns_ wires for large ones where bandwidth dominates. - if (total < size_ * 2 * n_conns_ || n_bytes <= 65536) { + if (total < static_cast<int64_t>(size_) * 2 * n_conns_ || n_bytes <= 65536) { ring_.reduce_scatter<T, ReduceOp>(in_ptr, out_ptr, total, 1, reduce_op); return; }
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring.h index c901c15a85ba6f91bec09997c686a3526e351853..56a05153b53ec46ad342137f848fa0036b4d8469 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring.h @@ -34,6 +34,14 @@ int size() override { return size_; }   + void begin_startup_wait_budget(int64_t timeout_ms) override { + ring_.begin_startup_wait_budget(timeout_ms); + } + + void end_startup_wait_budget() override { + ring_.end_startup_wait_budget(); + } + void all_sum(const void* input, void* output, size_t n_bytes, int dtype) override;
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring_impl.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring_impl.h index 4fd46547b9cdda2140a8b50c6d3f975261e96dd2..604531f82835b93ca3841294d64f1787657b28fd 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/ring_impl.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/ring_impl.h @@ -2,8 +2,13 @@ // Copyright © 2026 Apple Inc.   #pragma once   +#include <atomic> +#include <exception> +#include <future> +#include <memory> #include <span>   +#include "jaccl/progress_guard.h" #include "jaccl/rdma.h" #include "jaccl/threadpool.h"   @@ -49,6 +54,14 @@ recv_buffers_(recv_buffers), pool_(pool) {}   RingImpl() : rank_(0), size_(1), n_conns_(0), pool_(nullptr) {} + + void begin_startup_wait_budget(int64_t timeout_ms) { + wait_budget_->begin(timeout_ms, *failed_); + } + + void end_startup_wait_budget() { + wait_budget_->end(*failed_); + }   // Copy the received chunk into the output. Used by the all gather passes. struct CopyOp { @@ -89,7 +102,7 @@ (chunk_size + (MAX_DIR * n_wires) - 1) / (MAX_DIR * n_wires);   // Split the reduce scatter + all gather across the available wires. Each // wire handles a contiguous slice of each chunk in every direction. - dispatch_wires(pool_, n_wires, [&](int lw) { + dispatch_wires(n_wires, [&](int lw) { all_reduce_wire<MAX_DIR>( in_ptr, out_ptr, @@ -128,10 +141,10 @@ int64_t wire_end[MAX_DIR]; int64_t send_offset[MAX_DIR]; int64_t recv_offset[MAX_DIR]; for (int lr = 0; lr < MAX_DIR; lr++) { - wire_offset[lr] = lr * n_wires * size_per_wire + + wire_offset[lr] = static_cast<int64_t>(lr) * n_wires * size_per_wire + static_cast<int64_t>(lw) * size_per_wire; - int64_t region_end = - std::min(chunk_size, (lr + 1) * n_wires * size_per_wire); + int64_t region_end = std::min( + chunk_size, static_cast<int64_t>(lr + 1) * n_wires * size_per_wire); wire_end[lr] = std::min(region_end, wire_offset[lr] + size_per_wire); send_offset[lr] = rank_ * chunk_size; } @@ -195,7 +208,7 @@ // Split the all gather across the available wires. Each wire handles a // contiguous slice of every rank's data in both directions. size_t n_bytes_per_wire = (n_bytes + (2 * n_wires) - 1) / (2 * n_wires); - dispatch_wires(pool_, n_wires, [&](int lw) { + dispatch_wires(n_wires, [&](int lw) { all_gather_wire( out_ptr, n_bytes, @@ -227,10 +240,10 @@ // upper half of every peer's region is never transferred. int64_t wire_offset[2]; int64_t wire_end[2]; for (int lr = 0; lr < 2; lr++) { - wire_offset[lr] = lr * n_wires * n_bytes_per_wire + + wire_offset[lr] = static_cast<int64_t>(lr) * n_wires * n_bytes_per_wire + static_cast<int64_t>(lw) * n_bytes_per_wire; - int64_t region_end = - std::min(n_bytes, (lr + 1) * n_wires * n_bytes_per_wire); + int64_t region_end = std::min( + n_bytes, static_cast<int64_t>(lr + 1) * n_wires * n_bytes_per_wire); wire_end[lr] = std::min(region_end, wire_offset[lr] + n_bytes_per_wire); } int64_t send_offset[2] = {rank_ * n_bytes, rank_ * n_bytes}; @@ -272,7 +285,7 @@ int64_t chunk = size / size_; // Two directional regions, each split across the wires. int64_t size_per_wire = (chunk + (2 * n_wires) - 1) / (2 * n_wires);   - dispatch_wires(pool_, n_wires, [&](int lw) { + dispatch_wires(n_wires, [&](int lw) { reduce_scatter_wire<T>( in_ptr, out_ptr, chunk, size_per_wire, n_wires, lw, reduce_op); }); @@ -317,9 +330,10 @@ // the next wire's slice when size_per_wire is not a multiple of N. int64_t wire_offset[MAX_DIR]; int64_t wire_end[MAX_DIR]; for (int lr = 0; lr < MAX_DIR; lr++) { - wire_offset[lr] = lr * n_wires * size_per_wire + + wire_offset[lr] = static_cast<int64_t>(lr) * n_wires * size_per_wire + static_cast<int64_t>(lw) * size_per_wire; - int64_t region_end = std::min(chunk, (lr + 1) * n_wires * size_per_wire); + int64_t region_end = std::min( + chunk, static_cast<int64_t>(lr + 1) * n_wires * size_per_wire); wire_end[lr] = std::min(region_end, wire_offset[lr] + size_per_wire); }   @@ -367,6 +381,7 @@ } } };   + ProgressGuard guard("ring reduce_scatter", *failed_, wait_budget_.get()); for (int k = 0; k < size_ - 1; k++) { // Step 0 forwards this rank's own input; later steps forward the partial // accumulated in the output by the previous step. @@ -386,11 +401,13 @@ recv_from(sz, buff, lr, lw); } for (int lr = 0; lr < MAX_DIR; lr++) { int64_t offset = wire_offset[lr] + send_count[lr] * N; - std::copy( - send_base + send_base_offset[lr] + offset, - send_base + send_base_offset[lr] + - std::max(offset, std::min(offset + N, wire_end[lr])), - send_buffer(sz, buff, lr, lw).template begin<T>()); + const int64_t elems = + std::max<int64_t>(0, std::min(N, wire_end[lr] - offset)); + send_buffer(sz, buff, lr, lw) + .stage_send( + elems > 0 ? send_base + send_base_offset[lr] + offset + : nullptr, + elems); send_count[lr]++; send_to(sz, buff, lr, lw); } @@ -403,6 +420,7 @@ // Main loop while (in_flight > 0) { ibv_wc wc[WC_NUM]; int n = poll_wire(lw, WC_NUM, wc); + guard.check(wc, n); for (int i = 0; i < n; i++) { int work_type = wc[i].wr_id >> 16; int buff = (wc[i].wr_id >> 8) & 0xff; @@ -413,11 +431,13 @@ if (work_type == SEND_WR) { if (send_count[lr] < n_steps) { int64_t offset = wire_offset[lr] + send_count[lr] * N; - std::copy( - send_base + send_base_offset[lr] + offset, - send_base + send_base_offset[lr] + - std::max(offset, std::min(offset + N, wire_end[lr])), - send_buffer(sz, buff, lr, lw).template begin<T>()); + const int64_t elems = + std::max<int64_t>(0, std::min(N, wire_end[lr] - offset)); + send_buffer(sz, buff, lr, lw) + .stage_send( + elems > 0 ? send_base + send_base_offset[lr] + offset + : nullptr, + elems); send_count[lr]++; send_to(sz, buff, lr, lw); in_flight++; @@ -499,6 +519,8 @@ } }; set_limits();   + ProgressGuard guard( + "ring all_reduce/all_gather", *failed_, wait_budget_.get()); for (int k = 0; k < size_ - 1; k++) { // Step 0 sends this rank's own input; later steps send the accumulated // partial from out_ptr. @@ -512,11 +534,12 @@ recv_from(sz, buff, lr, lw); } for (int lr = 0; lr < MAX_DIR; lr++) { int64_t offset = wire_offset[lr] + send_count[lr] * N; - std::copy( - send_base + send_offset[lr] + offset, - send_base + send_offset[lr] + - std::max(offset, std::min(offset + N, send_limits[lr])), - send_buffer(sz, buff, lr, lw).template begin<T>()); + const int64_t elems = + std::max<int64_t>(0, std::min(N, send_limits[lr] - offset)); + send_buffer(sz, buff, lr, lw) + .stage_send( + elems > 0 ? send_base + send_offset[lr] + offset : nullptr, + elems); send_count[lr]++; send_to(sz, buff, lr, lw); } @@ -531,6 +554,7 @@ // Keep going until we have no longer data in flight. while (in_flight > 0) { ibv_wc wc[WC_NUM]; int n = poll_wire(lw, WC_NUM, wc); + guard.check(wc, n); for (int i = 0; i < n; i++) { int work_type = wc[i].wr_id >> 16; int buff = (wc[i].wr_id >> 8) & 0xff; @@ -540,11 +564,12 @@ in_flight--;   if (work_type == SEND_WR && send_count[lr] < n_steps) { int64_t offset = wire_offset[lr] + send_count[lr] * N; - std::copy( - send_base + send_offset[lr] + offset, - send_base + send_offset[lr] + - std::max(offset, std::min(offset + N, send_limits[lr])), - send_buffer(sz, buff, lr, lw).template begin<T>()); + const int64_t elems = + std::max<int64_t>(0, std::min(N, send_limits[lr] - offset)); + send_buffer(sz, buff, lr, lw) + .stage_send( + elems > 0 ? send_base + send_offset[lr] + offset : nullptr, + elems); send_to(sz, buff, lr, lw); in_flight++; send_count[lr]++; @@ -594,7 +619,7 @@ int64_t bytes_per_wire = (n_bytes + n_wires - 1) / n_wires;   // Split the send across the available wires. Each wire handles the // contiguous slice [lw * bytes_per_wire, (lw + 1) * bytes_per_wire). - dispatch_wires(pool_, n_wires, [&](int lw) { + dispatch_wires(n_wires, [&](int lw) { send_wire(in_ptr, n_bytes, dir, bytes_per_wire, lw); }); } @@ -623,10 +648,8 @@ // Prefill the pipeline int buff = 0; while (read_offset < limit && buff < PIPELINE) { - std::copy( - in_ptr + read_offset, - in_ptr + std::min(read_offset + N, limit), - send_buffer(sz, buff, dir, lw).begin<char>()); + send_buffer(sz, buff, dir, lw) + .stage_send(in_ptr + read_offset, std::min(N, limit - read_offset)); send_to(sz, buff, dir, lw);   buff++; @@ -635,6 +658,7 @@ in_flight++; }   // Main loop + ProgressGuard guard("ring send", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -642,16 +666,16 @@ // If a send was completed and we have more data to send then go ahead // and send them. ibv_wc wc[WC_NUM]; int n = conns[lw].poll(WC_NUM, wc); + guard.check(wc, n); for (int i = 0; i < n; i++) { int buff = (wc[i].wr_id >> 8) & 0xff;   in_flight--;   if (read_offset < limit) { - std::copy( - in_ptr + read_offset, - in_ptr + std::min(read_offset + N, limit), - send_buffer(sz, buff, dir, lw).begin<char>()); + send_buffer(sz, buff, dir, lw) + .stage_send( + in_ptr + read_offset, std::min(N, limit - read_offset)); send_to(sz, buff, dir, lw);   read_offset += N; @@ -673,7 +697,7 @@ int64_t bytes_per_wire = (n_bytes + n_wires - 1) / n_wires;   // Split the recv across the available wires. Each wire handles the // contiguous slice [lw * bytes_per_wire, (lw + 1) * bytes_per_wire). - dispatch_wires(pool_, n_wires, [&](int lw) { + dispatch_wires(n_wires, [&](int lw) { recv_wire(out_ptr, n_bytes, dir, bytes_per_wire, lw); }); } @@ -709,6 +733,7 @@ in_flight++; }   // Main loop + ProgressGuard guard("ring recv", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -716,6 +741,7 @@ // If a recv was completed copy it to the output and if we have more // data to fetch post another recv. ibv_wc wc[WC_NUM]; int n = conns[lw].poll(WC_NUM, wc); + guard.check(wc, n); for (int i = 0; i < n; i++) { int buff = (wc[i].wr_id >> 8) & 0xff;   @@ -779,6 +805,87 @@ num_completions, work_completions); }   + // Run fn(lw) for each wire, the first n_wires - 1 on the pool and the last + // inline, then wait for the pool calls before returning. + // + // A wire that throws sets failed_, which stops the other wires. When all + // wires returned the group is closed and the first error is thrown, or, + // unless the failure action is Throw, the process leaves through + // teardown_exit(). + template <typename Fn> + void dispatch_wires(int n_wires, Fn&& fn) { + StartupWaitBudget::Call call(*wait_budget_); + require_open(*failed_); + + auto run = [&](int lw) { + try { + fn(lw); + } catch (...) { + failed_->store(true); + throw; + } + }; + + std::exception_ptr error; + std::exception_ptr stopped; + auto wait = [&](auto&& call) { + try { + call(); + } catch (const WireStopped&) { + stopped = std::current_exception(); + } catch (...) { + if (!error) { + error = std::current_exception(); + } + } + }; + + if (n_wires <= 1 || pool_ == nullptr) { + wait([&] { + for (int lw = 0; lw < n_wires; lw++) { + run(lw); + } + }); + } else { + std::vector<std::future<void>> futures; + futures.reserve(n_wires - 1); + wait([&] { + for (int lw = 0; lw < n_wires - 1; lw++) { + futures.emplace_back(pool_->enqueue(run, lw)); + } + run(n_wires - 1); + }); + for (auto& f : futures) { + wait([&] { f.get(); }); + } + } + + if (error || stopped) { + close(); + if (failure_action() == FailureAction::TeardownExit) { + teardown_exit(describe(error ? error : stopped).c_str()); + } + std::rethrow_exception(error ? error : stopped); + } + } + + // Cancel the posted work and unpin the buffers. No wire may be running. + void close() { + failed_->store(true); + for (auto& c : left_) { + c.release(); + } + for (auto& c : right_) { + c.release(); + } + for (auto& b : send_buffers_) { + b.deregister(); + } + for (auto& b : recv_buffers_) { + b.deregister(); + } + } + int rank_; int size_; int n_conns_; @@ -787,6 +894,10 @@ std::span<Connection> right_; std::span<SharedBuffer> send_buffers_; std::span<SharedBuffer> recv_buffers_; ThreadPool* pool_; + std::unique_ptr<StartupWaitBudget> wait_budget_ = + std::make_unique<StartupWaitBudget>(); + std::unique_ptr<std::atomic<bool>> failed_ = + std::make_unique<std::atomic<bool>>(false); };   } // namespace jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/send_frame.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/send_frame.h new file mode 100644 index 0000000000000000000000000000000000000000..ded3e4bd35f0dac22bd481abc8d9443bd0f1a751 --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/send_frame.h @@ -0,0 +1,33 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include <algorithm> +#include <cstdint> +#include <cstring> +#include <span> +#include <stdexcept> + +namespace jaccl { + +// The posted receive/send size stays fixed. Clear every byte after this +// payload. +template <typename T> +inline void +stage_send_frame(std::span<char> destination, const T* source, int64_t count) { + if (destination.empty() || destination.data() == nullptr || count < 0 || + static_cast<uint64_t>(count) > destination.size() / sizeof(T) || + (count > 0 && source == nullptr)) { + throw std::invalid_argument( + "[jaccl] Send payload exceeds its scratch frame"); + } + const size_t bytes = static_cast<size_t>(count) * sizeof(T); + if (count > 0) { + std::copy_n(source, count, reinterpret_cast<T*>(destination.data())); + } + if (bytes < destination.size()) { + std::memset(destination.data() + bytes, 0, destination.size() - bytes); + } +} + +} // namespace jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h new file mode 100644 index 0000000000000000000000000000000000000000..8b0e0b53ff09a4e4aeb1cc79387b8046c8b3c0a2 --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h @@ -0,0 +1,112 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include <atomic> +#include <chrono> +#include <cstddef> +#include <cstdint> +#include <mutex> +#include <optional> +#include <stdexcept> + +namespace jaccl { + +constexpr int64_t MAX_STARTUP_WAIT_BUDGET_MS = 900000; + +// Clock injection is local to the type; production uses steady_clock. +template <typename Clock = std::chrono::steady_clock> +class BasicStartupWaitBudget { + public: + using TimePoint = typename Clock::time_point; + + void begin(int64_t timeout_ms, const std::atomic<bool>& failed) { + if (timeout_ms <= 0 || timeout_ms > MAX_STARTUP_WAIT_BUDGET_MS) { + throw std::invalid_argument( + "[jaccl] Startup budget must be 1..900000 ms."); + } + std::lock_guard<std::mutex> lock(mutex_); + require_idle_open(failed); + if (state_ != State::Unused) { + throw std::logic_error("[jaccl] Startup budget can only begin once."); + } + using Duration = typename Clock::duration; + static_assert(Clock::is_steady); + static_assert( + std::chrono::duration_cast<std::chrono::milliseconds>(Duration::max()) + .count() >= MAX_STARTUP_WAIT_BUDGET_MS); + const auto delta = std::chrono::duration_cast<Duration>( + std::chrono::milliseconds(timeout_ms)); + const auto now = Clock::now(); + if (now.time_since_epoch() > Duration::max() - delta) { + throw std::overflow_error( + "[jaccl] Startup deadline overflows the clock."); + } + deadline_ = now + delta; + state_ = State::Active; + } + + void end(const std::atomic<bool>& failed) { + std::lock_guard<std::mutex> lock(mutex_); + require_idle_open(failed); + if (state_ != State::Active) { + throw std::logic_error("[jaccl] No active startup budget to end."); + } + if (Clock::now() >= *deadline_) { + throw std::logic_error("[jaccl] Cannot end an expired startup budget."); + } + state_ = State::Ended; + } + + // Each operation holds a lease until all its wires and teardown finish. + class Call { + public: + explicit Call(BasicStartupWaitBudget& owner) : owner_(owner) { + std::lock_guard<std::mutex> lock(owner_.mutex_); + if (owner_.state_ == State::Active) { + deadline_ = owner_.deadline_; + } + ++owner_.calls_; + } + + Call(const Call&) = delete; + Call& operator=(const Call&) = delete; + + ~Call() { + std::lock_guard<std::mutex> lock(owner_.mutex_); + --owner_.calls_; + } + + const std::optional<TimePoint>& deadline() const { + return deadline_; + } + + private: + BasicStartupWaitBudget& owner_; + std::optional<TimePoint> deadline_; + }; + + private: + enum class State { Unused, Active, Ended }; + + void require_idle_open(const std::atomic<bool>& failed) const { + if (failed.load()) { + throw std::runtime_error( + "[jaccl] The group is closed after an earlier failure and cannot be " + "used again."); + } + if (calls_ != 0) { + throw std::logic_error( + "[jaccl] Startup transition requires an idle group."); + } + } + + std::mutex mutex_; + State state_{State::Unused}; + std::size_t calls_{0}; + std::optional<TimePoint> deadline_; +}; + +using StartupWaitBudget = BasicStartupWaitBudget<>; + +} // namespace jaccl
diff --git ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/threadpool.h Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/threadpool.h index 6e96152cb5fdab1b5d2b90c5809a1b490aa24430..123233f5e813aa5be4cd2e267c5fbf953a5fe8e5 100644 --- ml-explore/mlx/mlx/distributed/jaccl/lib/jaccl/threadpool.h +++ Layr-Labs/mlx/mlx/distributed/jaccl/lib/jaccl/threadpool.h @@ -135,7 +135,8 @@ } }   // Run fn(lw) for each wire, the first n_wires - 1 on the pool and the last -// inline, then wait for the pool calls before returning. +// inline, then wait for the pool calls before returning. An error of a pool +// call is thrown after all calls returned. template <typename Fn> void dispatch_wires(ThreadPool* pool, int n_wires, Fn&& fn) { if (n_wires <= 1 || pool == nullptr) { @@ -163,6 +164,9 @@ throw; } for (auto& f : futures) { f.wait(); + } + for (auto& f : futures) { + f.get(); } }
diff --git ml-explore/mlx/tests/jaccl/CMakeLists.txt Layr-Labs/mlx/tests/jaccl/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9768aeea88346e437162d93b4fb4788eee99ffd9 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/CMakeLists.txt @@ -0,0 +1,61 @@ +cmake_minimum_required(VERSION 3.24) +project(jaccl_tests LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +option(JACCL_TESTS_TSAN "Use ThreadSanitizer in the JACCL tests" OFF) + +if(JACCL_TESTS_TSAN) + set(SANITIZE -fsanitize=thread) +else() + set(SANITIZE -fsanitize=address,undefined) +endif() + +enable_testing() + +set(JACCL_LIB ${CMAKE_CURRENT_SOURCE_DIR}/../../mlx/distributed/jaccl/lib) + +# The tests use the JACCL headers and the fake verbs, not the jaccl library. +function(jaccl_test name) + add_executable(${name} ${name}.cpp fake_rdma.cpp) + target_include_directories(${name} PRIVATE fake_verbs ${JACCL_LIB}) + target_compile_options(${name} PRIVATE -O1 -g ${SANITIZE}) + target_link_options(${name} PRIVATE ${SANITIZE}) +endfunction() + +jaccl_test(send_frame_tests) +jaccl_test(progress_guard_tests) +jaccl_test(startup_wait_budget_tests) +jaccl_test(startup_wait_budget_group_tests) +jaccl_test(startup_wait_budget_api_tests) +target_include_directories(startup_wait_budget_api_tests PRIVATE ../..) +jaccl_test(exchange_tests) +target_include_directories(exchange_tests PRIVATE ../..) +add_test(NAME exchange COMMAND exchange_tests) +set_tests_properties(exchange PROPERTIES ENVIRONMENT + "JACCL_TIMEOUT_ACTION=throw") +add_test(NAME startup_wait_budget_api COMMAND startup_wait_budget_api_tests) +add_test(NAME startup_wait_budget_groups + COMMAND startup_wait_budget_group_tests) +set_tests_properties(startup_wait_budget_groups + PROPERTIES ENVIRONMENT "JACCL_TIMEOUT_ACTION=throw") +add_test(NAME startup_wait_budget COMMAND startup_wait_budget_tests) + +add_test(NAME send_frame COMMAND send_frame_tests) + +# The guard reads its limit and action once in a process, so each mode is one +# test. teardown-exit and default-exit start this program again as children. +foreach( + mode + checks + disabled + alias + precedence + negative + not-a-number + default + teardown-exit + default-exit) + add_test(NAME progress_guard_${mode} COMMAND progress_guard_tests ${mode}) +endforeach()
diff --git ml-explore/mlx/tests/jaccl/exchange_tests.cpp Layr-Labs/mlx/tests/jaccl/exchange_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..341c12fa8998393b2f2672d2254d9b60a551a1f0 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/exchange_tests.cpp @@ -0,0 +1,458 @@ +// Copyright © 2026 Darkbloom. + +// Tests of the two-rank mesh exchange and of the streamed sealed sum with +// simulated verbs. The codec here is a stand-in: a keyed XOR stream and a +// 16-byte keyed hash per piece. It finds changed bytes, wrong pieces and wrong +// counters, as the real AES-GCM codec does; it is not cryptography. + +#include <iostream> +#include <random> +#include <thread> + +#include "fixture.h" +#include "mlx/distributed/sealed_stream.h" + +namespace { + +using mlx::core::bfloat16_t; +using mlx::core::float16_t; +namespace sealed = mlx::core::distributed; +namespace detail = mlx::core::distributed::detail; + +constexpr int64_t kFrame = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + +int64_t class_bytes(int64_t length) { + int64_t bytes = FRAME_SIZE; + while (bytes < length && bytes < kFrame) { + bytes *= 2; + } + return bytes; +} + +std::vector<char> pattern(int64_t n, int seed) { + std::vector<char> v(n); + std::mt19937 random(seed); + for (auto& c : v) { + c = char(random()); + } + return v; +} + +// Frames: full ones, then the last in the smallest buffer that holds it. +void exchange_frames(const std::vector<fixture::Frame>& frames, int64_t n) { + const int64_t count = (n + kFrame - 1) / kFrame; + fixture::require(int64_t(frames.size()) == count, "Unexpected frame count"); + for (int64_t j = 0; j < count; ++j) { + const int64_t length = std::min(kFrame, n - j * kFrame); + fixture::require( + int64_t(frames[j].bytes.size()) == class_bytes(length), + "Unexpected frame size class"); + fixture::zero_tail(frames[j], length); + } +} + +void exchange_sizes() { + for (int64_t n : + {int64_t(1), + int64_t(16), + int64_t(4096), + int64_t(4097), + int64_t(8208), + kFrame, + kFrame + 1, + 2 * kFrame, + 3 * kFrame + 2064}) { + fixture::MeshPair pair; + std::array<std::vector<char>, 2> input{pattern(n, 1), pattern(n, 2)}; + std::array<std::vector<char>, 2> output{ + std::vector<char>(n + 1, 0x29), std::vector<char>(n + 1, 0x29)}; + std::array<std::vector<size_t>, 2> arrived; + auto run = [&](int rank) { + // Each frame is refused twice before it is ready. + int polls = 0; + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [&](size_t) { return ++polls % 3 == 0; }, + [&, rank](size_t end) { arrived[rank].push_back(end); }); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + for (int rank = 0; rank < 2; ++rank) { + const auto& peer = input[1 - rank]; + fixture::require( + std::equal(peer.begin(), peer.end(), output[rank].begin()) && + output[rank].back() == 0x29, + "Exchange changed the peer's bytes or wrote past the end"); + const auto& ends = arrived[rank]; + fixture::require( + !ends.empty() && ends.back() == size_t(n) && + std::is_sorted(ends.begin(), ends.end()) && + std::adjacent_find(ends.begin(), ends.end()) == ends.end(), + "arrived() must report increasing ends up to the message size"); + exchange_frames(fixture::selected(pair.fabric, rank, rank, 0), n); + } + pair.fabric.require_drained(); + } +} + +// A frame leaves only when ready() says its bytes are final. +void exchange_waits_for_ready() { + const int64_t n = 5 * kFrame + 100; + fixture::MeshPair pair; + pair.fabric.idle_wait = std::chrono::milliseconds(0); + std::array<std::vector<char>, 2> final{pattern(n, 3), pattern(n, 4)}; + std::array<std::vector<char>, 2> input{ + std::vector<char>(n, char(fixture::sentinel)), + std::vector<char>(n, char(fixture::sentinel))}; + std::array<std::vector<char>, 2> output{ + std::vector<char>(n), std::vector<char>(n)}; + std::array<std::atomic<size_t>, 2> written{0, 0}; + auto run = [&](int rank) { + std::thread writer([&, rank] { + for (int64_t at = 0; at < n; at += 300000) { + std::this_thread::sleep_for(std::chrono::microseconds(200)); + int64_t end = std::min(n, at + 300000); + std::copy( + final[rank].begin() + at, + final[rank].begin() + end, + input[rank].begin() + at); + written[rank].store(end, std::memory_order_release); + } + }); + try { + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [&, rank](size_t end) { + return written[rank].load(std::memory_order_acquire) >= end; + }, + [](size_t) {}); + } catch (...) { + writer.join(); + throw; + } + writer.join(); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + fixture::require( + output[0] == final[1] && output[1] == final[0], + "A frame left before its bytes were final"); + pair.fabric.require_drained(); +} + +// A failed completion closes the group: the call throws, later calls refuse. +void exchange_failure() { + const int64_t n = 3 * kFrame; + fixture::MeshPair pair; + pair.fabric.expire_after(std::chrono::milliseconds(1000)); + fixture::endpoint(pair.links[1][0]).fault.fail_receive = 1; + std::array<std::vector<char>, 2> input{pattern(n, 5), pattern(n, 6)}; + std::array<std::vector<char>, 2> output{ + std::vector<char>(n), std::vector<char>(n)}; + std::array<std::string, 2> errors; + auto run = [&](int rank) { + try { + pair.nodes[rank]->exchange( + input[rank].data(), + output[rank].data(), + n, + [](size_t) { return true; }, + [](size_t) {}); + } catch (const std::exception& error) { + errors[rank] = error.what(); + } + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + fixture::require( + errors[1].find("mesh exchange") != std::string::npos && + errors[1].find("failed with status") != std::string::npos, + "A failed completion must fail the exchange"); + std::string later; + try { + pair.nodes[1]->exchange( + input[1].data(), + output[1].data(), + 16, + [](size_t) { return true; }, + [](size_t) {}); + } catch (const std::exception& error) { + later = error.what(); + } + fixture::require( + later.find("closed") != std::string::npos, + "A closed group must refuse a later exchange"); +} + +// The stand-in codec. +struct Codec { + int rank; + std::atomic<bool> refused{false}; + int64_t refuse_seal = -1; + int64_t tamper = -1; + bool jitter = false; + + static uint64_t mix(uint64_t x) { + x += 0x9e3779b97f4a7c15ull; + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull; + x = (x ^ (x >> 27)) * 0x94d049bb133111ebull; + return x ^ (x >> 31); + } + static uint64_t key(uint64_t counter, int sender, uint32_t piece) { + return mix(counter * 0x10001 ^ uint64_t(sender) << 60 ^ uint64_t(piece)); + } + static void crypt(const char* in, char* out, size_t len, uint64_t key) { + for (size_t i = 0; i < len; ++i) { + out[i] = char(in[i] ^ char(mix(key ^ (i / 8)) >> (8 * (i % 8)))); + } + } + static void tag( + const char* ct, + size_t len, + uint64_t key, + uint32_t pieces, + size_t total, + char* out) { + uint64_t a = mix(key ^ pieces), b = mix(key ^ total ^ 0x5555); + for (size_t i = 0; i < len; ++i) { + a = mix(a ^ uint8_t(ct[i])); + b = b * 0x100000001b3ull ^ uint8_t(ct[i]); + } + std::memcpy(out, &a, 8); + std::memcpy(out + 8, &b, 8); + } + + static int seal( + void* ctx, + const void* plaintext, + size_t len, + void* sealed, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total) { + auto& self = *static_cast<Codec*>(ctx); + if (self.refused || int64_t(piece) == self.refuse_seal) { + return 1; + } + if (self.jitter) { + std::this_thread::sleep_for(std::chrono::microseconds(piece % 5 * 40)); + } + uint64_t k = key(counter, self.rank, piece); + auto out = static_cast<char*>(sealed); + crypt(static_cast<const char*>(plaintext), out, len, k); + tag(out, len, k, pieces, total, out + len); + if (int64_t(piece) == self.tamper) { + out[len / 2] ^= 1; + } + return 0; + } + + static int open( + void* ctx, + const void* sealed, + size_t len, + void* plaintext, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer) { + auto& self = *static_cast<Codec*>(ctx); + if (self.refused || peer != 1 - self.rank) { + return 1; + } + uint64_t k = key(counter, peer, piece); + auto in = static_cast<const char*>(sealed); + char expected[sealed::kSealTagBytes]; + tag(in, len, k, pieces, total, expected); + if (std::memcmp(expected, in + len, sizeof(expected)) != 0) { + self.refused = true; + return 1; + } + crypt(in, static_cast<char*>(plaintext), len, k); + return 0; + } + + sealed::SealCodec codec(size_t piece_bytes) { + sealed::SealCodec c; + c.seal_piece = seal; + c.open_piece = open; + c.ctx = this; + c.piece_bytes = piece_bytes; + return c; + } +}; + +struct SumResult { + std::array<bool, 2> ok{}; + std::array<std::vector<char>, 2> out; + std::array<std::vector<char>, 2> partial; +}; + +template <typename T> +SumResult streamed_sum( + fixture::MeshPair& pair, + std::array<Codec, 2>& codecs, + size_t elements, + size_t piece_bytes, + uint64_t counter) { + SumResult r; + const size_t n = elements * sizeof(T); + detail::PieceLayout layout(n, piece_bytes); + auto run = [&](int rank) { + r.partial[rank] = pattern(n, 10 + rank); + r.out[rank].assign(n, char(fixture::sentinel)); + // Stale bytes, as a reused allocation can hold. + std::vector<char> mine(layout.frame(), char(fixture::sentinel)); + std::vector<char> theirs(layout.frame(), char(fixture::sentinel)); + detail::StreamedSum sum( + codecs[rank].codec(piece_bytes), + layout, + counter, + rank, + r.partial[rank].data(), + r.partial[rank].data(), + r.out[rank].data(), + mine.data(), + theirs.data(), + detail::add_piece<T>); + r.ok[rank] = sum.run([&, rank]( + const char* send, + char* recv, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + pair.nodes[rank]->exchange(send, recv, bytes, ready, arrived); + }); + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + pair.fabric.require_drained(); + return r; +} + +// The gathered path's sum: rank 0's addend + rank 1's, widened, rounded once. +template <typename T> +std::vector<char> reference(const SumResult& r) { + std::vector<char> sum(r.partial[0].size()); + auto a = reinterpret_cast<const T*>(r.partial[0].data()); + auto b = reinterpret_cast<const T*>(r.partial[1].data()); + auto out = reinterpret_cast<T*>(sum.data()); + for (size_t i = 0; i < sum.size() / sizeof(T); ++i) { + out[i] = + static_cast<T>(static_cast<float>(a[i]) + static_cast<float>(b[i])); + } + return sum; +} + +template <typename T> +void identical(size_t elements, size_t piece_bytes, bool jitter) { + fixture::MeshPair pair; + pair.fabric.idle_wait = std::chrono::milliseconds(0); + std::array<Codec, 2> codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].jitter = codecs[1].jitter = jitter; + auto r = streamed_sum<T>(pair, codecs, elements, piece_bytes, 7); + auto expected = reference<T>(r); + fixture::require(r.ok[0] && r.ok[1], "A streamed sum was refused"); + fixture::require( + r.out[0] == expected && r.out[1] == expected, + "The streamed sum differs from the gathered sum, bit for bit"); +} + +void streamed_sum_identical() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + identical<bfloat16_t>(4096, piece, false); // decode: one piece + identical<float>(4096, piece, false); + identical<bfloat16_t>(2048 * 1024, piece, false); // 4 MiB, 17 pieces + identical<float16_t>(2048 * 1024, piece, true); + identical<float>(1 << 20, 100000, true); // pieces that straddle frames + identical<bfloat16_t>(4096 * 2048, piece, false); // 16 MiB, 65 pieces +} + +void streamed_sum_tamper() { + fixture::MeshPair pair; + std::array<Codec, 2> codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].tamper = 5; + auto r = streamed_sum<float>( + pair, codecs, 1 << 20, (256 << 10) - sealed::kSealTagBytes, 9); + fixture::require( + !r.ok[1] && codecs[1].refused, + "A changed byte in a peer piece must refuse the sum"); +} + +void streamed_sum_seal_failure() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + fixture::MeshPair pair; + std::array<Codec, 2> codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].refuse_seal = 3; + auto r = streamed_sum<float>(pair, codecs, 1 << 20, piece, 11); + fixture::require( + !r.ok[0] && !r.ok[1], "A piece that did not seal must fail both ranks"); + // The piece that did not seal went out as zeros, not as stale bytes. + std::vector<char> wire; + for (const auto& f : fixture::selected(pair.fabric, 0, 0, 0)) { + wire.insert(wire.end(), f.bytes.begin(), f.bytes.end()); + } + detail::PieceLayout layout(size_t(1 << 20) * sizeof(float), piece); + fixture::require( + std::all_of( + wire.begin() + layout.sealed(3), + wire.begin() + layout.sealed_end(3), + [](char c) { return c == 0; }), + "A piece that did not seal must cross as zeros"); +} + +void piece_layout() { + constexpr size_t piece = (256 << 10) - sealed::kSealTagBytes; + detail::PieceLayout bf16(size_t(16) << 20, piece); + fixture::require( + bf16.count == 65 && bf16.sealed(4) == size_t(kFrame) && + bf16.frame() == (size_t(16) << 20) + 65 * 16, + "Four sealed pieces fill each 1 MiB frame"); + detail::PieceLayout decode(8192, piece); + fixture::require( + decode.count == 1 && decode.frame() == 8208, "A decode sum is one piece"); + detail::PieceLayout empty(0, piece); + fixture::require( + empty.count == 1 && empty.length(0) == 0 && empty.frame() == 16, + "An empty partial is one empty piece"); +} + +bool group(void (*check)(), const char* name) { + try { + check(); + std::cout << "PASS " << name << '\n'; + return true; + } catch (const std::exception& error) { + std::cout << "FAIL " << name << ": " << error.what() << '\n'; + return false; + } +} + +} // namespace + +int main() { + bool passed = group(piece_layout, "streamed piece layout"); + passed &= group(exchange_sizes, "exchange sizes, tail class, arrived ends"); + passed &= group(exchange_waits_for_ready, "exchange sends only ready bytes"); + passed &= group( + streamed_sum_identical, "streamed sum bit-identical to gathered sum"); + passed &= group(streamed_sum_tamper, "streamed sum refuses a changed byte"); + passed &= + group(streamed_sum_seal_failure, "streamed sum seal failure sends zeros"); + passed &= group(exchange_failure, "exchange failure closes the group"); + const auto& ledger = fixture::ledger(); + if (ledger.queue_pairs != 0 || ledger.completion_queues != 0 || + ledger.regions != 0) { + std::cout << "FAIL fake verbs objects remain after the checks\n"; + passed = false; + } + return passed ? 0 : 1; +}
diff --git ml-explore/mlx/tests/jaccl/fake_rdma.cpp Layr-Labs/mlx/tests/jaccl/fake_rdma.cpp new file mode 100644 index 0000000000000000000000000000000000000000..963b946b39603dfff031615d368fb1bfea5397d7 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/fake_rdma.cpp @@ -0,0 +1,312 @@ +// Copyright © 2026 Apple Inc. + +#include <optional> +#include <utility> + +#include "fake_rdma.h" + +namespace { +std::vector<char> bytes(const ibv_sge& entry) { + const auto* pointer = reinterpret_cast<const char*>(entry.addr); + return {pointer, pointer + entry.length}; +} + +void check_unchanged(const fixture::Pending& pending) { + fixture::require( + bytes(pending.entry) == pending.original, + "Send buffer reused before its completion was polled"); +} + +void deliver( + fixture::Endpoint& endpoint, + int index, + int drop, + int fail, + fixture::Completion completion) { + if (index == drop) { + return; + } + if (index == fail) { + completion.value.status = IBV_WC_WR_FLUSH_ERR; + } + endpoint.completions.push_back(std::move(completion)); + auto& high_water = fixture::ledger().completion_high_water; + high_water = std::max(high_water.load(), endpoint.completions.size()); +} + +void drop(ibv_qp* pair) { + if (pair) { + delete pair; + fixture::ledger().queue_pairs--; + } +} + +void drop(ibv_cq* queue) { + if (queue) { + delete queue; + fixture::ledger().completion_queues--; + } +} + +void drop(ibv_mr* region) { + if (region) { + delete region; + fixture::ledger().regions--; + } +} + +// The three verbs that a failed group calls through jaccl::ibv(). +int destroy_queue_pair(ibv_qp* pair) { + fixture::ledger().destroy_queue_pair_calls++; + if (fixture::ledger().refuse_destroy) { + return 16; + } + auto& endpoint = *static_cast<fixture::Endpoint*>(pair->fixture); + { + // The posted work is cancelled. The peer cannot match this endpoint and + // its completions are gone. + std::lock_guard lock(endpoint.fabric->mutex); + endpoint.closed = true; + endpoint.sends.clear(); + endpoint.receives.clear(); + endpoint.completions.clear(); + } + drop(pair); + return 0; +} + +int destroy_completion_queue(ibv_cq* queue) { + fixture::ledger().destroy_completion_queue_calls++; + if (fixture::ledger().refuse_destroy) { + return 16; + } + drop(queue); + return 0; +} + +int deregister(ibv_mr* region) { + fixture::ledger().deregister_calls++; + if (fixture::ledger().refuse_deregister) { + return 16; + } + drop(region); + return 0; +} +} // namespace + +namespace jaccl { +// Only allocation and registration are fake. The staging methods of +// SharedBuffer and the post and poll methods of Connection are the real ones. +SharedBuffer::SharedBuffer(size_t count) : data_(nullptr), num_bytes_(count) { + if (posix_memalign(&data_, 4096, count) != 0) { + throw std::bad_alloc(); + } + std::memset(data_, fixture::sentinel, count); +} + +SharedBuffer::SharedBuffer(SharedBuffer&& other) + : data_(nullptr), num_bytes_(0) { + std::swap(data_, other.data_); + std::swap(num_bytes_, other.num_bytes_); + memory_regions_.swap(other.memory_regions_); +} + +SharedBuffer::~SharedBuffer() { + for (const auto& entry : memory_regions_) { + drop(entry.second); + } + std::free(data_); +} + +void SharedBuffer::register_to_protection_domain(ibv_pd* domain) { + if (!memory_regions_.contains(domain)) { + memory_regions_[domain] = new ibv_mr{1}; + fixture::ledger().regions++; + } +} + +Connection::Connection(ibv_context* context) + : ctx(context), + protection_domain(nullptr), + completion_queue(nullptr), + queue_pair(nullptr), + src{} {} +Connection::Connection(Connection&& other) : Connection(nullptr) { + std::swap(ctx, other.ctx); + std::swap(protection_domain, other.protection_domain); + std::swap(completion_queue, other.completion_queue); + std::swap(queue_pair, other.queue_pair); + std::swap(src, other.src); + std::swap(source_gid_index, other.source_gid_index); +} + +Connection::~Connection() { + delete ctx; + delete protection_domain; + drop(completion_queue); + drop(queue_pair); +} + +// The real wrapper loads librdma.dylib. The fake one has only the three verbs +// that a failed group calls. +IBVWrapper::IBVWrapper() : librdma_handle_(nullptr) { + get_device_list = nullptr; + get_device_name = nullptr; + open_device = nullptr; + free_device_list = nullptr; + close_device = nullptr; + alloc_pd = nullptr; + create_qp = nullptr; + create_cq = nullptr; + dealloc_pd = nullptr; + query_port = nullptr; + query_gid = nullptr; + modify_qp = nullptr; + reg_mr = nullptr; + destroy_qp = destroy_queue_pair; + destroy_cq = destroy_completion_queue; + dereg_mr = deregister; +} + +IBVWrapper& ibv() { + static IBVWrapper wrapper; + return wrapper; +} +} // namespace jaccl + +namespace fixture { +Ledger& ledger() { + static Ledger value; + return value; +} + +Endpoint& endpoint(const jaccl::Connection& connection) { + return *static_cast<Endpoint*>(connection.queue_pair->fixture); +} + +void Fabric::pair( + jaccl::Connection& a, + jaccl::Connection& b, + int wire, + int side) { + auto first = std::make_unique<Endpoint>(); + auto second = std::make_unique<Endpoint>(); + first->fabric = second->fabric = this; + first->rank = 0; + second->rank = 1; + first->side = side; + second->side = 1 - side; + first->wire = second->wire = wire; + first->peer = second.get(); + second->peer = first.get(); + auto attach = [](jaccl::Connection& connection, Endpoint* endpoint) { + connection.ctx = new ibv_context{}; + connection.protection_domain = new ibv_pd{}; + connection.completion_queue = new ibv_cq{endpoint}; + connection.queue_pair = new ibv_qp{endpoint}; + ledger().completion_queues++; + ledger().queue_pairs++; + }; + attach(a, first.get()); + attach(b, second.get()); + endpoints.push_back(std::move(first)); + endpoints.push_back(std::move(second)); +} + +void Fabric::match(Endpoint& sender) { + auto& receiver = *sender.peer; + while (!sender.closed && !receiver.closed && !sender.sends.empty() && + !receiver.receives.empty()) { + auto send = std::move(sender.sends.front()); + sender.sends.pop_front(); + auto receive = std::move(receiver.receives.front()); + receiver.receives.pop_front(); + check_unchanged(send); + require( + send.entry.length == receive.entry.length, + "The posted send and receive lengths differ"); + std::memcpy( + reinterpret_cast<void*>(receive.entry.addr), + reinterpret_cast<const void*>(send.entry.addr), + send.entry.length); + frames.push_back({sender.rank, sender.side, sender.wire, send.original}); + const ibv_wc sent{send.id, IBV_WC_SUCCESS, 0, send.entry.length}; + const ibv_wc received{receive.id, IBV_WC_SUCCESS, 0, receive.entry.length}; + deliver( + sender, + sender.sent++, + sender.fault.drop_send, + sender.fault.fail_send, + {sent, std::move(send)}); + deliver( + receiver, + receiver.received++, + receiver.fault.drop_receive, + receiver.fault.fail_receive, + {received, std::nullopt}); + } + changed.notify_all(); +} + +void Fabric::require_drained() { + std::lock_guard lock(mutex); + for (const auto& endpoint : endpoints) { + require( + endpoint->sends.empty() && endpoint->receives.empty() && + endpoint->completions.empty(), + "A posted request or a completion was not consumed"); + } +} + +void Fabric::expire_after(std::chrono::milliseconds duration) { + std::lock_guard lock(mutex); + deadline = std::chrono::steady_clock::now() + duration; +} +} // namespace fixture + +int ibv_post_send(ibv_qp* qp, ibv_send_wr* wr, ibv_send_wr**) { + fixture::require( + wr->num_sge == 1 && wr->next == nullptr && wr->opcode == IBV_WR_SEND && + wr->send_flags == IBV_SEND_SIGNALED, + "Unexpected send work request"); + auto& endpoint = *static_cast<fixture::Endpoint*>(qp->fixture); + std::lock_guard lock(endpoint.fabric->mutex); + endpoint.sends.push_back({wr->sg_list[0], wr->wr_id, bytes(wr->sg_list[0])}); + endpoint.fabric->match(endpoint); + return 0; +} + +int ibv_post_recv(ibv_qp* qp, ibv_recv_wr* wr, ibv_recv_wr**) { + fixture::require( + wr->num_sge == 1 && wr->next == nullptr, + "Unexpected receive work request"); + auto& endpoint = *static_cast<fixture::Endpoint*>(qp->fixture); + std::lock_guard lock(endpoint.fabric->mutex); + endpoint.receives.push_back({wr->sg_list[0], wr->wr_id, {}}); + endpoint.fabric->match(*endpoint.peer); + return 0; +} + +int ibv_poll_cq(ibv_cq* cq, int maximum, ibv_wc* out) { + auto& endpoint = *static_cast<fixture::Endpoint*>(cq->fixture); + std::unique_lock lock(endpoint.fabric->mutex); + fixture::require( + std::chrono::steady_clock::now() < endpoint.fabric->deadline, + "The fake poll reached its deadline"); + if (endpoint.fault.poll_error) { + return -1; + } + if (endpoint.completions.empty() && endpoint.fabric->idle_wait.count() > 0) { + endpoint.fabric->changed.wait_for(lock, endpoint.fabric->idle_wait); + } + int count = 0; + while (count < maximum && !endpoint.completions.empty()) { + auto completion = std::move(endpoint.completions.front()); + endpoint.completions.pop_front(); + if (completion.send) { + check_unchanged(*completion.send); + } + out[count++] = completion.value; + } + return count; +}
diff --git ml-explore/mlx/tests/jaccl/fake_rdma.h Layr-Labs/mlx/tests/jaccl/fake_rdma.h new file mode 100644 index 0000000000000000000000000000000000000000..f7cb8af345de1f56d4fe0f77ea4a1157d05469a6 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/fake_rdma.h @@ -0,0 +1,94 @@ +// Copyright © 2026 Apple Inc. + +// Simulated verbs for the tests. A send completes when it meets a posted +// receive of the peer endpoint. Each endpoint can lose or fail one completion. + +#pragma once + +#include <algorithm> +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <cstring> +#include <deque> +#include <memory> +#include <optional> +#include <stdexcept> + +#include "jaccl/rdma.h" + +namespace fixture { + +constexpr unsigned char sentinel = 0xa7; +struct Frame { + int rank, side, wire; + std::vector<char> bytes; +}; + +struct Pending { + ibv_sge entry; + uint64_t id; + std::vector<char> original; +}; + +struct Completion { + ibv_wc value; + std::optional<Pending> send; +}; + +// The index, from 0, of the completion that an endpoint loses or fails. +struct Fault { + int drop_send = -1, fail_send = -1, drop_receive = -1, fail_receive = -1; + bool poll_error = false; +}; + +// The fake verbs objects that exist and the calls made through jaccl::ibv(). +struct Ledger { + std::atomic<int> queue_pairs{0}, completion_queues{0}, regions{0}; + std::atomic<int> destroy_queue_pair_calls{0}, + destroy_completion_queue_calls{0}; + std::atomic<int> deregister_calls{0}; + std::atomic<size_t> completion_high_water{0}; + std::atomic<bool> refuse_destroy{false}; + std::atomic<bool> refuse_deregister{false}; +}; + +Ledger& ledger(); +struct Endpoint; +struct Fabric { + std::mutex mutex; + std::condition_variable changed; + std::vector<std::unique_ptr<Endpoint>> endpoints; + std::vector<Frame> frames; + // The fake poll throws after this time, so that no test can run forever. + std::chrono::steady_clock::time_point deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(8); + // The sleep of an empty poll. With 0 the polling loop spins, as it does on + // hardware. + std::chrono::milliseconds idle_wait{1}; + void + pair(jaccl::Connection&, jaccl::Connection&, int wire, int first_side = 0); + void match(Endpoint&); + void require_drained(); + void expire_after(std::chrono::milliseconds); +}; + +struct Endpoint { + Fabric* fabric; + Endpoint* peer = nullptr; + int rank, side, wire; + std::deque<Pending> sends, receives; + std::deque<Completion> completions; + Fault fault; + int sent = 0, received = 0; + bool closed = false; +}; + +// Valid only while the connection has its queue pair. +Endpoint& endpoint(const jaccl::Connection&); +inline void require(bool value, const char* message) { + if (!value) { + throw std::runtime_error(message); + } +} +} // namespace fixture
diff --git ml-explore/mlx/tests/jaccl/fake_verbs/infiniband/verbs.h Layr-Labs/mlx/tests/jaccl/fake_verbs/infiniband/verbs.h new file mode 100644 index 0000000000000000000000000000000000000000..a823b0b0a043f3542a28914c48472e599f80147b --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/fake_verbs/infiniband/verbs.h @@ -0,0 +1,69 @@ +// Copyright © 2026 Apple Inc. + +// A stand-in for <infiniband/verbs.h> for the tests. It declares only the +// types that the JACCL headers use. fake_rdma.cpp defines the three verbs. + +#pragma once + +#include <cstddef> +#include <cstdint> + +struct ibv_device {}; +struct ibv_context {}; +struct ibv_pd {}; +struct ibv_comp_channel {}; +struct ibv_qp_init_attr {}; +struct ibv_port_attr {}; +struct ibv_qp_attr {}; +struct ibv_gid { + uint8_t raw[16]; +}; + +struct ibv_mr { + uint32_t lkey; +}; + +struct ibv_cq { + void* fixture; +}; + +struct ibv_qp { + void* fixture; +}; + +struct ibv_sge { + uint64_t addr; + uint32_t length; + uint32_t lkey; +}; + +struct ibv_send_wr { + uint64_t wr_id; + ibv_send_wr* next; + ibv_sge* sg_list; + int num_sge; + int opcode; + int send_flags; +}; + +struct ibv_recv_wr { + uint64_t wr_id; + ibv_recv_wr* next; + ibv_sge* sg_list; + int num_sge; +}; + +enum ibv_wc_status { IBV_WC_SUCCESS = 0, IBV_WC_WR_FLUSH_ERR = 5 }; +struct ibv_wc { + uint64_t wr_id; + ibv_wc_status status; + uint32_t vendor_err; + uint32_t byte_len; +}; + +constexpr int IBV_WR_SEND = 0; +constexpr int IBV_SEND_SIGNALED = 1; + +int ibv_post_send(ibv_qp*, ibv_send_wr*, ibv_send_wr**); +int ibv_post_recv(ibv_qp*, ibv_recv_wr*, ibv_recv_wr**); +int ibv_poll_cq(ibv_cq*, int, ibv_wc*);
diff --git ml-explore/mlx/tests/jaccl/fixture.h Layr-Labs/mlx/tests/jaccl/fixture.h new file mode 100644 index 0000000000000000000000000000000000000000..d7e01ef40971d0409620a3c2bfaac95cef559da8 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/fixture.h @@ -0,0 +1,198 @@ +// Copyright © 2026 Apple Inc. + +// Two ranks that are connected through the simulated verbs, as a mesh or as a +// ring, and helpers to check the frames that went to the peer. + +#pragma once + +#include <array> +#include <future> + +#include "fake_rdma.h" +#include "jaccl/mesh_impl.h" +#include "jaccl/ring_impl.h" + +namespace fixture { + +struct StaleTail : std::runtime_error { + StaleTail() + : std::runtime_error("Nonzero bytes after the payload of a frame") {} +}; + +inline void zero_tail(const Frame& frame, size_t logical) { + require( + logical <= frame.bytes.size(), "The payload is larger than the frame"); + for (size_t index = logical; index < frame.bytes.size(); ++index) { + if (frame.bytes[index] != 0) { + throw StaleTail(); + } + } +} + +template <typename First, typename Second> +void both(First first, Second second) { + auto a = std::async(std::launch::async, first); + auto b = std::async(std::launch::async, second); + std::exception_ptr error; + try { + a.get(); + } catch (...) { + error = std::current_exception(); + } + try { + b.get(); + } catch (...) { + if (!error) { + error = std::current_exception(); + } + } + if (error) { + std::rethrow_exception(error); + } +} + +inline void connections(std::vector<jaccl::Connection>& values, int count) { + values.reserve(count); + for (int i = 0; i < count; ++i) { + values.emplace_back(nullptr); + } +} + +inline void buffers( + std::vector<jaccl::SharedBuffer>& values, + int slots, + const std::vector<jaccl::Connection>& first, + const std::vector<jaccl::Connection>* second = nullptr) { + values.reserve(BUFFER_SIZES * slots); + for (int size = 0; size < BUFFER_SIZES; ++size) { + for (int slot = 0; slot < slots; ++slot) { + values.emplace_back(FRAME_SIZE * (1 << size)); + for (const auto& connection : first) { + if (connection.ctx) { + values.back().register_to_protection_domain( + connection.protection_domain); + } + } + if (second) { + for (const auto& connection : *second) { + values.back().register_to_protection_domain( + connection.protection_domain); + } + } + } + } +} + +// The failure flag of a mesh group, which its wires share. +using Flag = std::shared_ptr<std::atomic<bool>>; +inline Flag flag() { + return std::make_shared<std::atomic<bool>>(false); +} + +struct MeshPair { + Fabric fabric; + std::array<std::vector<jaccl::Connection>, 2> links; + std::array<std::vector<jaccl::SharedBuffer>, 2> scratch, scatter; + std::array<std::unique_ptr<jaccl::MeshImpl>, 2> nodes; + MeshPair() : MeshPair({flag(), flag()}) {} + // `failed` holds the failure flag of each rank. Two pairs that get the same + // flags are two wires of one group. + explicit MeshPair(std::array<Flag, 2> failed) { + for (auto& rank : links) { + connections(rank, 2); + } + fabric.pair(links[0][1], links[1][0], 0); + for (int rank = 0; rank < 2; ++rank) { + buffers(scratch[rank], NUM_BUFFERS * 2, links[rank]); + buffers(scatter[rank], NUM_BUFFERS * 4, links[rank]); + nodes[rank] = std::make_unique<jaccl::MeshImpl>( + rank, 2, links[rank], scratch[rank], scatter[rank], failed[rank]); + } + } +}; + +struct RingPair { + Fabric fabric; + int wires; + std::array<std::vector<jaccl::Connection>, 2> left, right; + std::array<std::vector<jaccl::SharedBuffer>, 2> sends, receives; + std::array<std::unique_ptr<jaccl::ThreadPool>, 2> pools; + std::array<std::unique_ptr<jaccl::RingImpl>, 2> nodes; + explicit RingPair(int count) : wires(count) { + for (int rank = 0; rank < 2; ++rank) { + connections(left[rank], wires); + connections(right[rank], wires); + } + for (int wire = 0; wire < wires; ++wire) { + fabric.pair(right[0][wire], left[1][wire], wire, 0); + fabric.pair(left[0][wire], right[1][wire], wire, 1); + } + for (int rank = 0; rank < 2; ++rank) { + buffers(sends[rank], NUM_BUFFERS * wires * 2, left[rank], &right[rank]); + buffers( + receives[rank], NUM_BUFFERS * wires * 2, left[rank], &right[rank]); + if (wires > 1) { + pools[rank] = std::make_unique<jaccl::ThreadPool>(wires - 1); + } + nodes[rank] = std::make_unique<jaccl::RingImpl>( + rank, + 2, + left[rank], + right[rank], + sends[rank], + receives[rank], + pools[rank].get()); + } + } +}; + +inline std::vector<Frame> +selected(const Fabric& fabric, int rank, int side, int wire) { + std::vector<Frame> result; + for (const auto& frame : fabric.frames) { + if (frame.rank == rank && frame.side == side && frame.wire == wire) { + result.push_back(frame); + } + } + return result; +} + +inline void payload_frames( + const std::vector<Frame>& frames, + std::span<const char> input) { + const size_t capacity = buffer_size_from_message(input.size()).second; + require( + frames.size() == (input.size() + capacity - 1) / capacity, + "Unexpected number of frames"); + size_t offset = 0; + for (const auto& frame : frames) { + require(frame.bytes.size() == capacity, "Unexpected frame size"); + const size_t count = std::min(capacity, input.size() - offset); + require( + std::equal( + input.begin() + offset, + input.begin() + offset + count, + frame.bytes.begin()), + "Valid payload bytes changed"); + zero_tail(frame, count); + offset += count; + } +} + +struct Add { + void operator()(const float* source, float* target, int64_t count) const { + for (int64_t i = 0; i < count; ++i) { + target[i] += source[i]; + } + } + void operator()( + const float* source, + const float* base, + float* target, + int64_t count) const { + for (int64_t i = 0; i < count; ++i) { + target[i] = source[i] + base[i]; + } + } +}; +} // namespace fixture
diff --git ml-explore/mlx/tests/jaccl/progress_guard_tests.cpp Layr-Labs/mlx/tests/jaccl/progress_guard_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34890cf9539a1828cdf7e6feb1bc13f0b9fe1cec --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/progress_guard_tests.cpp @@ -0,0 +1,1333 @@ +// Copyright © 2026 Apple Inc. + +// Tests of the progress guard with simulated verbs. Each call goes through +// the real mesh and ring headers. The limit and the failure action are read +// once in a process, so each mode of this program sets the environment first +// and is one CTest test. The modes that check the exceptions select the +// "throw" action; the teardown-exit modes run each case in a child process of +// this program and check how it ended. + +#include <fcntl.h> +#include <spawn.h> +#include <sys/wait.h> +#include <unistd.h> + +#include <atomic> +#include <cstdio> +#include <cstdlib> +#include <fstream> +#include <functional> +#include <iostream> +#include <map> +#include <sstream> +#include <stdexcept> +#include <string> +#include <thread> +#include <vector> + +extern char** environ; + +#include "fixture.h" +#include "jaccl/progress_guard.h" + +namespace { +using Clock = std::chrono::steady_clock; +using std::chrono::milliseconds; + +// The limit of this process in milliseconds. +int64_t limit = 0; +// A call may fail this much after the limit. The fake poll then stops it. +constexpr int64_t slack = 1000; +const char* const watchdog = "The fake poll reached its deadline"; +const char* const closed = + "[jaccl] The group is closed after an earlier failure and cannot be used again."; +const int64_t frame = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + +struct Outcome { + bool threw = false; + std::string message; + int64_t ms = 0; +}; + +template <typename Call> +Outcome attempt(Call call) { + Outcome outcome; + const auto start = Clock::now(); + try { + call(); + } catch (const std::exception& error) { + outcome.threw = true; + outcome.message = error.what(); + } + outcome.ms = + std::chrono::duration_cast<milliseconds>(Clock::now() - start).count(); + return outcome; +} + +template <typename First, typename Second> +std::array<Outcome, 2> together(First first, Second second) { + auto a = std::async(std::launch::async, [&] { return attempt(first); }); + auto b = std::async(std::launch::async, [&] { return attempt(second); }); + Outcome x = a.get(), y = b.get(); + return {x, y}; +} + +// Print each kind of error once, as the caller sees it. +void show(bool& shown, const Outcome& outcome) { + if (!shown) { + std::cout << "INFO error: " << outcome.message << '\n'; + shown = true; + } +} + +[[noreturn]] void mismatch(const std::string& what, const Outcome& outcome) { + std::ostringstream text; + text << what << " (after " << outcome.ms << " ms: " + << (outcome.threw ? outcome.message : std::string("returned normally")) + << ")"; + throw std::runtime_error(text.str()); +} + +void expect_success(const Outcome& outcome) { + if (outcome.threw) { + mismatch("normal traffic failed", outcome); + } +} + +// The polling loop must stop by itself, with its own error, near the limit. +void expect_timeout(const Outcome& outcome, const std::string& op) { + if (!outcome.threw) { + mismatch("a stalled call returned without an error", outcome); + } + if (outcome.message == watchdog) { + mismatch( + "the polling loop did not stop by itself; the watchdog of the fake poll ended it", + outcome); + } + if (outcome.message.rfind("[jaccl] " + op + ": no completion for ", 0) != 0) { + mismatch("not the no-progress error of " + op, outcome); + } + if (outcome.ms < limit || outcome.ms > limit + slack) { + mismatch("the failure is outside [limit, limit + slack]", outcome); + } + static bool shown = false; + show(shown, outcome); +} + +// A failed completion must be an error at once; it must not wait for the limit. +void expect_failed_completion(const Outcome& outcome, const std::string& op) { + if (!outcome.threw) { + mismatch("a failed completion was accepted as data", outcome); + } + if (outcome.message.rfind( + "[jaccl] " + op + ": a work completion failed with status 5", 0) != + 0) { + mismatch("not the failed-completion error of " + op, outcome); + } + if (limit > 0 && outcome.ms >= limit / 2) { + mismatch("the failure was not immediate", outcome); + } + static bool shown = false; + show(shown, outcome); +} + +void expect_closed(const Outcome& outcome) { + if (!outcome.threw || outcome.message != closed) { + mismatch("a closed group accepted a call", outcome); + } + if (outcome.ms > 100) { + mismatch("a closed group did not refuse at once", outcome); + } + static bool shown = false; + show(shown, outcome); +} + +void arm(fixture::Fabric& fabric, int64_t ms = -1) { + fabric.idle_wait = milliseconds(0); + fabric.expire_after(milliseconds(ms < 0 ? limit + slack : ms)); +} + +// The failed rank destroyed its queue pairs and completion queues through the +// verbs and deregistered every region. `before` is the ledger before the call. +struct Counts { + int queue_pairs, completion_queues, regions, destroy_pairs, destroy_queues, + deregister; + static Counts now() { + const auto& l = fixture::ledger(); + return { + l.queue_pairs, + l.completion_queues, + l.regions, + l.destroy_queue_pair_calls, + l.destroy_completion_queue_calls, + l.deregister_calls}; + } +}; + +void expect_released( + const Counts& before, + std::initializer_list<const std::vector<jaccl::Connection>*> links, + int ranks_failed, + int ranks) { + int connections = 0; + for (const auto* group : links) { + for (const auto& connection : *group) { + if (connection.ctx == nullptr) { + continue; + } + connections++; + fixture::require( + connection.queue_pair == nullptr && + connection.completion_queue == nullptr, + "A failed group kept a queue pair or a completion queue"); + } + } + const Counts after = Counts::now(); + fixture::require( + after.destroy_pairs - before.destroy_pairs == connections && + after.destroy_queues - before.destroy_queues == connections && + before.queue_pairs - after.queue_pairs == connections && + before.completion_queues - after.completion_queues == connections, + "Queue pairs/completion queues were not destroyed exactly once"); + const int regions = before.regions * ranks_failed / ranks; + fixture::require( + regions > 0 && before.regions - after.regions == regions && + after.deregister - before.deregister == regions, + "The buffers of a failed group were not deregistered exactly once"); +} + +std::vector<float> floats(size_t count, float value) { + return std::vector<float>(count, value); +} + +const char* raw(const std::vector<float>& values) { + return reinterpret_cast<const char*>(values.data()); +} + +char* raw(std::vector<float>& values) { + return reinterpret_cast<char*>(values.data()); +} + +using MeshCall = std::function<void(jaccl::MeshImpl&)>; +using RingCall = std::function<void(jaccl::RingImpl&, int wires)>; +struct Buffers { + std::vector<float> in = floats(4096, 1), out = floats(8192, -19); +}; + +std::vector<std::pair<std::string, MeshCall>> mesh_calls(Buffers& b) { + return { + {"mesh recv", [&](auto& node) { node.recv(raw(b.out), 100, 1); }}, + {"mesh send", [&](auto& node) { node.send(raw(b.in), 100, 1); }}, + {"mesh all_reduce", + [&](auto& node) { + node.all_reduce(b.in.data(), b.out.data(), 64, fixture::Add{}); + }}, + {"mesh all_gather", + [&](auto& node) { node.all_gather(raw(b.in), raw(b.out), 256, 256); }}, + {"mesh sum_scatter", + [&](auto& node) { + node.sum_scatter(b.in.data(), b.out.data(), 64, 64, fixture::Add{}); + }}, + // The scatter-gather all reduce starts with a reduce scatter. + {"mesh sum_scatter", + [&](auto& node) { + node.all_reduce_scatter_gather( + b.in.data(), b.out.data(), 64, fixture::Add{}); + }}, + }; +} + +std::vector<std::pair<std::string, RingCall>> ring_calls(Buffers& b) { + return { + {"ring recv", + [&](auto& node, int wires) { node.recv(raw(b.out), 100, 1, wires); }}, + {"ring send", + [&](auto& node, int wires) { node.send(raw(b.in), 100, 1, wires); }}, + {"ring all_reduce/all_gather", + [&](auto& node, int wires) { + if (wires == 1) { + node.template all_reduce<1>( + b.in.data(), b.out.data(), 64, 1, fixture::Add{}); + } else { + node.template all_reduce<2>( + b.in.data(), b.out.data(), 64, wires, fixture::Add{}); + } + }}, + {"ring all_reduce/all_gather", + [&](auto& node, int wires) { + node.all_gather(raw(b.in), raw(b.out), 256, wires); + }}, + {"ring reduce_scatter", + [&](auto& node, int wires) { + node.reduce_scatter( + b.in.data(), b.out.data(), 128, wires, fixture::Add{}); + }}, + }; +} + +int failures = 0, passes = 0; +template <typename Check> +void check(const std::string& name, Check body) { + try { + body(); + std::cout << "PASS " << name << '\n'; + passes++; + } catch (const std::exception& error) { + std::cout << "FAIL " << name << ": " << error.what() << '\n'; + failures++; + } +} + +// A peer that never answers: every polling loop must stop by itself, release +// the group and refuse every later call. +void silent_peer() { + Buffers b; + const auto mesh = mesh_calls(b); + const char* mesh_names[] = { + "recv", + "send", + "all_reduce", + "all_gather", + "sum_scatter", + "all_reduce_scatter_gather"}; + for (size_t index = 0; index < mesh.size(); ++index) { + check( + std::string("silent peer: mesh ") + mesh_names[index] + + " stops, releases, then refuses", + [&] { + fixture::MeshPair pair; + arm(pair.fabric); + const Counts before = Counts::now(); + expect_timeout( + attempt([&] { mesh[index].second(*pair.nodes[0]); }), + mesh[index].first); + expect_released(before, {&pair.links[0]}, 1, 2); + for (const auto& later : mesh) { + expect_closed(attempt([&] { later.second(*pair.nodes[0]); })); + } + }); + } + const auto ring = ring_calls(b); + const char* ring_names[] = { + "recv", "send", "all_reduce", "all_gather", "reduce_scatter"}; + for (int wires : {1, 2}) { + for (size_t index = 0; index < ring.size(); ++index) { + check( + "silent peer: ring " + std::string(ring_names[index]) + " on " + + std::to_string(wires) + " wire(s) stops, releases, then refuses", + [&] { + fixture::RingPair pair(wires); + arm(pair.fabric); + const Counts before = Counts::now(); + expect_timeout( + attempt([&] { ring[index].second(*pair.nodes[0], wires); }), + ring[index].first); + expect_released(before, {&pair.left[0], &pair.right[0]}, 1, 2); + for (const auto& later : ring) { + expect_closed( + attempt([&] { later.second(*pair.nodes[0], wires); })); + } + }); + } + } +} + +// One completion is lost while the peer keeps working. +void lost_completion() { + check( + "lost completion: mesh all_reduce drain stops after the reduction finished", + [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[0][1]).fault.drop_send = 0; + std::array<std::vector<float>, 2> in{floats(16, 1), floats(16, 2)}, + out{floats(17, -19), floats(17, -19)}; + const Counts before = Counts::now(); + auto result = together( + [&] { + pair.nodes[0]->all_reduce( + in[0].data(), out[0].data(), 16, fixture::Add{}); + }, + [&] { + pair.nodes[1]->all_reduce( + in[1].data(), out[1].data(), 16, fixture::Add{}); + }); + expect_timeout(result[0], "mesh all_reduce"); + expect_success(result[1]); + for (const auto& values : out) { + fixture::require( + std::all_of( + values.begin(), + values.begin() + 16, + [](float v) { return v == 3; }) && + values[16] == -19, + "The reduction before the drain changed"); + } + expect_released(before, {&pair.links[0]}, 1, 2); + }); + check( + "lost completion: mesh recv stops in the middle of a five-frame transfer", + [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[1][0]).fault.drop_receive = 2; + std::vector<char> in(frame * 5, 0x53), out(frame * 5, 0x29); + const Counts before = Counts::now(); + auto result = together( + [&] { pair.nodes[0]->send(in.data(), in.size(), 1); }, + [&] { pair.nodes[1]->recv(out.data(), out.size(), 0); }); + expect_success(result[0]); + expect_timeout(result[1], "mesh recv"); + expect_released(before, {&pair.links[1]}, 1, 2); + }); + // Wire 1 runs inline and wire 0 on the pool, so both orders are covered. + for (int stalled : {0, 1}) { + check( + "lost completion: ring send on 2 wires stops when wire " + + std::to_string(stalled) + " loses its completion", + [&] { + fixture::RingPair pair(2); + arm(pair.fabric); + // Rank 0 sends to rank 1 on its left connections (direction 1). + fixture::endpoint(pair.left[0][stalled]).fault.drop_send = 0; + std::vector<char> in(200, 0x64), out(201, 0x29); + const Counts before = Counts::now(); + auto result = together( + [&] { pair.nodes[0]->send(in.data(), 200, 1, 2); }, + [&] { pair.nodes[1]->recv(out.data(), 200, 0, 2); }); + expect_timeout(result[0], "ring send"); + expect_success(result[1]); + fixture::require( + std::equal(in.begin(), in.end(), out.begin()) && + out.back() == 0x29, + "The receiver of the completed transfer changed"); + expect_released(before, {&pair.left[0], &pair.right[0]}, 1, 2); + }); + } +} + +// A completion with a failure status is an error, never data. +void failed_completion() { + check( + "failed completion: mesh recv throws at once and leaves the output alone", + [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[1][0]).fault.fail_receive = 0; + std::vector<char> in(100, 0x53), out(100, 0x29); + const Counts before = Counts::now(); + auto result = together( + [&] { pair.nodes[0]->send(in.data(), 100, 1); }, + [&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + expect_success(result[0]); + expect_failed_completion(result[1], "mesh recv"); + fixture::require( + std::all_of( + out.begin(), out.end(), [](char v) { return v == 0x29; }), + "A failed completion was copied to the output"); + expect_released(before, {&pair.links[1]}, 1, 2); + Buffers b; + for (const auto& later : mesh_calls(b)) { + expect_closed(attempt([&] { later.second(*pair.nodes[1]); })); + } + }); + check("failed completion: mesh send throws at once", [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[0][1]).fault.fail_send = 0; + std::vector<char> in(100, 0x53), out(100, 0x29); + auto result = together( + [&] { pair.nodes[0]->send(in.data(), 100, 1); }, + [&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + expect_failed_completion(result[0], "mesh send"); + expect_success(result[1]); + }); + Buffers b; + const auto mesh = mesh_calls(b); + for (size_t index : {size_t(2), size_t(3), size_t(4)}) { + check("failed completion: " + mesh[index].first + " throws at once", [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[0][1]).fault.fail_receive = 0; + Buffers peer; + const auto peer_calls = mesh_calls(peer); + auto result = together( + [&] { mesh[index].second(*pair.nodes[0]); }, + [&] { peer_calls[index].second(*pair.nodes[1]); }); + expect_failed_completion(result[0], mesh[index].first); + expect_success(result[1]); + }); + } + check("failed poll: mesh recv throws at once", [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[1][0]).fault.poll_error = true; + std::vector<char> out(100, 0x29); + const Outcome outcome = + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + if (!outcome.threw || + outcome.message.rfind( + "[jaccl] mesh recv: the completion queue could not be polled", 0) != + 0 || + outcome.ms > 100) { + mismatch("a failed poll was not an immediate error", outcome); + } + static bool shown = false; + show(shown, outcome); + }); + // The collectives poll several connections through the shared helpers. + check("failed poll: mesh all_reduce throws at once", [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[0][1]).fault.poll_error = true; + Buffers b; + const Counts before = Counts::now(); + const Outcome outcome = attempt([&] { + pair.nodes[0]->all_reduce(b.in.data(), b.out.data(), 64, fixture::Add{}); + }); + if (!outcome.threw || + outcome.message.rfind( + "[jaccl] mesh all_reduce: the completion queue could not be polled", + 0) != 0 || + outcome.ms > 100) { + mismatch("a failed poll was not an immediate error", outcome); + } + expect_released(before, {&pair.links[0]}, 1, 2); + }); + for (int side : {0, 1}) { + check( + std::string("failed poll: ring all_reduce throws at once (") + + (side ? "right" : "left") + " connection)", + [&] { + fixture::RingPair pair(1); + arm(pair.fabric); + fixture::endpoint(side ? pair.right[0][0] : pair.left[0][0]) + .fault.poll_error = true; + Buffers b; + const Counts before = Counts::now(); + const Outcome outcome = attempt([&] { + pair.nodes[0]->all_reduce<1>( + b.in.data(), b.out.data(), 64, 1, fixture::Add{}); + }); + if (!outcome.threw || + outcome.message.rfind( + "[jaccl] ring all_reduce/all_gather: the completion queue could not be polled", + 0) != 0 || + outcome.ms > 100) { + mismatch("a failed poll was not an immediate error", outcome); + } + expect_released(before, {&pair.left[0], &pair.right[0]}, 1, 2); + }); + } + // Two wires: one gets the failed completion, the other has no traffic. The + // idle wire must stop, the cause must be reported, and it must not take the + // limit. `failing` selects the wire; wire 1 runs inline, wire 0 on the pool. + for (int failing : {0, 1}) { + check( + "failed completion: ring recv on 2 wires, wire " + + std::to_string(failing) + + " fails, the idle wire stops and the cause is reported", + [&] { + fixture::RingPair pair(2); + arm(pair.fabric); + // Rank 1 receives from rank 0 on its right connections (direction 1). + fixture::endpoint(pair.right[1][failing]).fault.fail_receive = 0; + std::vector<char> in(100, 0x64), out(100, 0x29); + const Counts before = Counts::now(); + auto result = together( + [&] { pair.nodes[0]->send_wire(in.data(), 100, 1, 50, failing); }, + [&] { pair.nodes[1]->recv(out.data(), 100, 0, 2); }); + expect_success(result[0]); + expect_failed_completion(result[1], "ring recv"); + fixture::require( + std::all_of( + out.begin(), out.end(), [](char v) { return v == 0x29; }), + "A failed completion was copied to the output"); + expect_released(before, {&pair.left[1], &pair.right[1]}, 1, 2); + Buffers b; + for (const auto& later : ring_calls(b)) { + expect_closed(attempt([&] { later.second(*pair.nodes[1], 2); })); + } + }); + } + check( + "failed completion: ring all_reduce on 2 wires fails on one rank, the peer then stops by itself", + [&] { + fixture::RingPair pair(2); + arm(pair.fabric); + fixture::endpoint(pair.left[0][0]).fault.fail_receive = 0; + std::array<std::vector<float>, 2> in{floats(64, 1), floats(64, 2)}, + out{floats(96, -19), floats(96, -19)}; + const Counts before = Counts::now(); + auto result = together( + [&] { + pair.nodes[0]->all_reduce<2>( + in[0].data(), out[0].data(), 64, 2, fixture::Add{}); + }, + [&] { + pair.nodes[1]->all_reduce<2>( + in[1].data(), out[1].data(), 64, 2, fixture::Add{}); + }); + expect_failed_completion(result[0], "ring all_reduce/all_gather"); + expect_timeout(result[1], "ring all_reduce/all_gather"); + expect_released( + before, + {&pair.left[0], &pair.right[0], &pair.left[1], &pair.right[1]}, + 2, + 2); + }); +} + +// When the verbs refuse to destroy, the failure is still reported, the call +// still fails, and the group still refuses later calls. +void refused_destroy() { + check( + "refused destroy: the error is printed, the handles stay for the destructor", + [&] { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[1][0]).fault.poll_error = true; + std::vector<char> out(100, 0x29); + std::ostringstream captured; + auto* previous = std::cerr.rdbuf(captured.rdbuf()); + fixture::ledger().refuse_destroy = true; + const Outcome outcome = + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + const Outcome later = + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + fixture::ledger().refuse_destroy = false; + std::cerr.rdbuf(previous); + if (!outcome.threw || + outcome.message.rfind("[jaccl] mesh recv: ", 0) != 0) { + mismatch("the call did not fail", outcome); + } + expect_closed(later); + fixture::require( + captured.str() == + "[jaccl] Could not destroy a queue pair (16)\n" + "[jaccl] Could not destroy a completion queue (16)\n", + "The refused destroy was not reported"); + fixture::require( + pair.links[1][0].queue_pair != nullptr && + pair.links[1][0].completion_queue != nullptr, + "A handle that was not destroyed was dropped"); + }); +} + +// When the verbs refuse to deregister a region, the failure is reported and +// the region stays registered, so that the destructor tries again. +void refused_deregister() { + check( + "refused deregister: the error is printed, the region stays for the destructor", + [&] { + fixture::MeshPair pair; + auto& buffer = pair.scratch[0].front(); + auto* domain = pair.links[0][1].protection_domain; + std::ostringstream captured; + auto* previous = std::cerr.rdbuf(captured.rdbuf()); + fixture::ledger().refuse_deregister = true; + buffer.deregister(); + fixture::ledger().refuse_deregister = false; + std::cerr.rdbuf(previous); + fixture::require( + captured.str() == + "[jaccl] Could not deregister a memory region (16)\n", + "The refused deregistration was not reported"); + fixture::require( + buffer.local_key(domain) == 1, + "A region that was not deregistered was dropped"); + buffer.deregister(); + bool dropped = false; + try { + buffer.local_key(domain); + } catch (const std::out_of_range&) { + dropped = true; + } + fixture::require(dropped, "A deregistered region was kept"); + }); +} + +// The wires of one mesh group share the failure flag: a failure on one wire +// stops a call that waits on the other wire, and the group then refuses +// every later call on every wire. +void mesh_wires_share_failure() { + check( + "mesh wires: a failed wire stops the other wire, then both refuse", [&] { + const auto failed = std::array{fixture::flag(), fixture::flag()}; + fixture::MeshPair first(failed), second(failed); + arm(first.fabric); + arm(second.fabric); + fixture::endpoint(second.links[1][0]).fault.poll_error = true; + std::vector<char> out(100, 0x29), other(100, 0x29); + // Rank 0 sends nothing, so the receive on the first wire waits. + auto waiting = std::async(std::launch::async, [&] { + return attempt([&] { first.nodes[1]->recv(out.data(), 100, 0); }); + }); + std::this_thread::sleep_for(milliseconds(limit / 5)); + const Outcome failure = + attempt([&] { second.nodes[1]->recv(other.data(), 100, 0); }); + const Outcome stopped = waiting.get(); + if (!failure.threw || + failure.message.rfind("[jaccl] mesh recv: ", 0) != 0) { + mismatch("the call on the failed wire did not fail", failure); + } + if (!stopped.threw || stopped.message != jaccl::WireStopped().what()) { + mismatch("the waiting wire was not stopped", stopped); + } + if (stopped.ms >= limit) { + mismatch("the waiting wire ran into the limit", stopped); + } + expect_closed( + attempt([&] { first.nodes[1]->recv(out.data(), 100, 0); })); + expect_closed( + attempt([&] { second.nodes[1]->recv(other.data(), 100, 0); })); + }); +} + +// Traffic that waits, but less than the limit, is not touched. +void below_limit() { + check("below the limit: a peer that starts late is waited for", [&] { + fixture::MeshPair pair; + arm(pair.fabric, 8000); + std::vector<char> in(100, 0x53), out(101, 0x29); + auto result = together( + [&] { + std::this_thread::sleep_for(milliseconds(limit / 2)); + pair.nodes[0]->send(in.data(), 100, 1); + }, + [&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + expect_success(result[0]); + expect_success(result[1]); + fixture::require( + std::equal(in.begin(), in.end(), out.begin()) && out.back() == 0x29, + "Late transfer changed"); + pair.fabric.require_drained(); + }); + check( + "below the limit: three gaps longer than the limit in total, each one shorter", + [&] { + fixture::MeshPair pair; + arm(pair.fabric, 8000); + std::vector<char> in(frame * 3), out(frame * 3 + 1, 0x29); + for (size_t index = 0; index < in.size(); ++index) { + in[index] = char(index / frame + 1); + } + auto result = together( + [&] { + for (int part = 0; part < 3; ++part) { + std::this_thread::sleep_for(milliseconds(limit / 2)); + pair.nodes[0]->send(in.data() + part * frame, frame, 1); + } + }, + [&] { pair.nodes[1]->recv(out.data(), frame * 3, 0); }); + expect_success(result[0]); + expect_success(result[1]); + fixture::require( + result[1].ms >= limit * 3 / 2, + "The receiver did not wait across the gaps"); + fixture::require( + std::equal(in.begin(), in.end(), out.begin()) && out.back() == 0x29, + "Paused transfer changed"); + pair.fabric.require_drained(); + }); + check( + "below the limit: ring all_reduce on 2 wires with a peer that starts late", + [&] { + fixture::RingPair pair(2); + arm(pair.fabric, 8000); + std::array<std::vector<float>, 2> in{floats(4096, 1), floats(4096, 2)}, + out{floats(4097, -19), floats(4097, -19)}; + auto result = together( + [&] { + pair.nodes[0]->all_reduce<2>( + in[0].data(), out[0].data(), 4096, 2, fixture::Add{}); + }, + [&] { + std::this_thread::sleep_for(milliseconds(limit / 2)); + pair.nodes[1]->all_reduce<2>( + in[1].data(), out[1].data(), 4096, 2, fixture::Add{}); + }); + expect_success(result[0]); + expect_success(result[1]); + for (const auto& values : out) { + fixture::require( + std::all_of( + values.begin(), + values.begin() + 4096, + [](float v) { return v == 3; }) && + values[4096] == -19, + "Late ring reduction changed"); + } + pair.fabric.require_drained(); + }); +} + +// The mesh runs its wires through the shared dispatch_wires. The error of a +// pool wire must reach the caller, after every wire returned. +void pool_wire_error() { + check("dispatch_wires throws the error of a pool wire", [&] { + jaccl::ThreadPool pool(1); + std::atomic<int> returned{0}; + std::string error; + try { + jaccl::dispatch_wires(&pool, 2, [&](int lw) { + if (lw == 0) { + std::this_thread::sleep_for(milliseconds(50)); + returned++; + throw std::runtime_error("pool wire failed"); + } + returned++; + }); + } catch (const std::runtime_error& e) { + error = e.what(); + } + fixture::require( + error == "pool wire failed", "The pool wire error was dropped"); + fixture::require(returned == 2, "A wire was still running"); + }); +} + +// With the limit removed the loops wait as before; a failed completion is +// still an error. +void disabled() { + check( + "disabled: a stalled mesh recv keeps waiting until the watchdog of the fake poll", + [&] { + fixture::MeshPair pair; + arm(pair.fabric, 1200); + std::vector<char> out(100, 0x29); + const Outcome outcome = + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + if (!outcome.threw || outcome.message != watchdog || + outcome.ms < 1200) { + mismatch("the loop stopped although the limit is removed", outcome); + } + }); + check( + "disabled: a stalled ring recv on 2 wires keeps waiting until the watchdog of the fake poll", + [&] { + fixture::RingPair pair(2); + arm(pair.fabric, 1200); + std::vector<char> out(100, 0x29); + const Outcome outcome = + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0, 2); }); + if (!outcome.threw || outcome.message != watchdog || + outcome.ms < 1200) { + mismatch("the loop stopped although the limit is removed", outcome); + } + }); + check("disabled: a failed completion is still an immediate error", [&] { + fixture::MeshPair pair; + arm(pair.fabric, 8000); + fixture::endpoint(pair.links[1][0]).fault.fail_receive = 0; + std::vector<char> in(100, 0x53), out(100, 0x29); + auto result = together( + [&] { pair.nodes[0]->send(in.data(), 100, 1); }, + [&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + expect_success(result[0]); + expect_failed_completion(result[1], "mesh recv"); + if (result[1].ms > 500) { + mismatch("the failure was not immediate", result[1]); + } + }); +} + +// Check the limit that the guard read from the environment of this process. +void value(int64_t expected) { + limit = expected; + check( + "the limit of this process is " + std::to_string(expected) + " ms", [&] { + if (jaccl::progress_timeout_ms() != expected) { + throw std::runtime_error( + "the guard read " + std::to_string(jaccl::progress_timeout_ms())); + } + }); +} + +// One stalled call that must stop at the limit of this process. +void stall() { + check("silent peer: mesh recv stops at the limit of this process", [&] { + fixture::MeshPair pair; + arm(pair.fabric); + std::vector<char> out(100, 0x29); + expect_timeout( + attempt([&] { pair.nodes[1]->recv(out.data(), 100, 0); }), "mesh recv"); + }); +} + +// Teardown exit. A child runs one failing call; its memory release hook +// reports the ledger. The parent checks the exit status, the time from the +// start of the call to the exit, and what the child printed. + +// What the release hook of a child expects to find already destroyed. +int expected_pairs = 0, expected_regions = 0; +bool at_least = false; +std::atomic<int> releases{0}; + +void report_release() { + const auto& l = fixture::ledger(); + const int pairs = l.destroy_queue_pair_calls, + queues = l.destroy_completion_queue_calls, + regions = l.deregister_calls; + const bool ok = at_least ? pairs >= expected_pairs && + queues >= expected_pairs && regions >= expected_regions + : pairs == expected_pairs && + queues == expected_pairs && regions == expected_regions; + std::printf( + "RELEASE %d %s pairs=%d queues=%d regions=%d expected=%d/%d\n", + ++releases, + ok ? "ok" : "mismatch", + pairs, + queues, + regions, + expected_pairs, + expected_regions); + std::fflush(stdout); +} + +void hang() { + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } +} + +void call_start() { + std::printf( + "CALL %lld\n", + static_cast<long long>( + std::chrono::duration_cast<std::chrono::nanoseconds>( + Clock::now().time_since_epoch()) + .count())); + std::fflush(stdout); +} + +// The connections of one rank that hold a queue pair, and the regions of one +// rank (both ranks register the same number). +int live(const std::vector<jaccl::Connection>& links) { + int count = 0; + for (const auto& connection : links) { + count += connection.ctx != nullptr; + } + return count; +} + +// Run the call; reaching the end means the process did not exit. +template <typename Call> +int child_call(Call call) { + call_start(); + const Outcome outcome = attempt(call); + if (outcome.threw) { + std::printf("THREW %s\n", outcome.message.c_str()); + } else { + std::printf("RETURNED\n"); + } + return 0; +} + +int child(const std::string& name) { + limit = jaccl::progress_timeout_ms(); + if (name != "no-hook") { + jaccl::set_memory_release(name == "hung-hook" ? &hang : &report_release); + } + if (name == "mesh-recv" || name == "no-hook" || name == "hung-hook") { + fixture::MeshPair pair; + arm(pair.fabric); + expected_pairs = live(pair.links[1]); + expected_regions = fixture::ledger().regions / 2; + std::vector<char> out(100, 0x29); + return child_call([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + } + if (name == "mesh-all-reduce") { + fixture::MeshPair pair; + arm(pair.fabric); + expected_pairs = live(pair.links[0]); + expected_regions = fixture::ledger().regions / 2; + Buffers b; + return child_call([&] { + pair.nodes[0]->all_reduce(b.in.data(), b.out.data(), 64, fixture::Add{}); + }); + } + if (name == "mesh-failed-completion") { + fixture::MeshPair pair; + arm(pair.fabric); + fixture::endpoint(pair.links[1][0]).fault.fail_receive = 0; + expected_pairs = live(pair.links[1]); + expected_regions = fixture::ledger().regions / 2; + std::vector<char> in(100, 0x53), out(100, 0x29); + std::thread sender( + [&] { attempt([&] { pair.nodes[0]->send(in.data(), 100, 1); }); }); + sender.detach(); + return child_call([&] { pair.nodes[1]->recv(out.data(), 100, 0); }); + } + if (name == "ring-recv-2") { + fixture::RingPair pair(2); + arm(pair.fabric); + expected_pairs = live(pair.left[1]) + live(pair.right[1]); + expected_regions = fixture::ledger().regions / 2; + std::vector<char> out(100, 0x29); + return child_call([&] { pair.nodes[1]->recv(out.data(), 100, 0, 2); }); + } + if (name == "two-groups") { + // Two groups fail at the same time on two threads: one exit, one release. + fixture::MeshPair first, second; + arm(first.fabric); + arm(second.fabric); + expected_pairs = live(first.links[1]); + expected_regions = fixture::ledger().regions / 4; + at_least = true; + std::vector<char> a(100, 0x29), b(100, 0x29); + std::thread other( + [&] { attempt([&] { second.nodes[1]->recv(b.data(), 100, 0); }); }); + other.detach(); + return child_call([&] { first.nodes[1]->recv(a.data(), 100, 0); }); + } + std::printf("FAIL unknown child case %s\n", name.c_str()); + return 2; +} + +struct Ended { + int status = -1; // the exit status, or -1 when the child did not exit + int64_t ms = -1; // from the start of the call to the exit + std::string out, err; +}; + +std::string slurp(const std::string& path) { + std::ifstream file(path); + std::stringstream text; + text << file.rdbuf(); + return text.str(); +} + +// Run this program as a child with `name` and only `variables` of the four +// guard variables set. +Ended run_child( + const char* program, + const std::string& name, + const std::map<std::string, std::string>& variables) { + std::vector<std::string> keep; + for (char** e = environ; *e != nullptr; ++e) { + std::string entry(*e); + bool guard = false; + for (const char* v : + {"JACCL_PROGRESS_TIMEOUT_MS=", + "MLX_JACCL_PROGRESS_TIMEOUT_MS=", + "JACCL_TIMEOUT_ACTION=", + "MLX_JACCL_TIMEOUT_ACTION="}) { + guard |= entry.rfind(v, 0) == 0; + } + if (!guard) { + keep.push_back(entry); + } + } + for (const auto& [key, value] : variables) { + keep.push_back(key + "=" + value); + } + // ThreadSanitizer sleeps 1 s in _exit by default; the timing checks measure + // the exit, so the children skip that sleep. Other sanitizers ignore it. + bool tsan_options = false; + for (auto& entry : keep) { + if (entry.rfind("TSAN_OPTIONS=", 0) == 0) { + entry += ":atexit_sleep_ms=0"; + tsan_options = true; + } + } + if (!tsan_options) { + keep.push_back("TSAN_OPTIONS=atexit_sleep_ms=0"); + } + std::vector<char*> envp; + for (auto& entry : keep) { + envp.push_back(entry.data()); + } + envp.push_back(nullptr); + + const char* dir = std::getenv("TMPDIR"); + std::string base = std::string(dir ? dir : "/tmp") + "/jaccl-guard-child-" + + std::to_string(getpid()) + "-" + name; + const std::string out_path = base + ".out", err_path = base + ".err"; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_addopen( + &actions, 1, out_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); + posix_spawn_file_actions_addopen( + &actions, 2, err_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); + std::string self(program), mode("child"); + std::string which(name); + char* argv[] = {self.data(), mode.data(), which.data(), nullptr}; + pid_t pid = 0; + const int spawned = + posix_spawn(&pid, program, &actions, nullptr, argv, envp.data()); + posix_spawn_file_actions_destroy(&actions); + fixture::require(spawned == 0, "Could not start the child process"); + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { + } + const auto end = Clock::now(); + Ended ended; + ended.status = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + ended.out = slurp(out_path); + ended.err = slurp(err_path); + std::remove(out_path.c_str()); + std::remove(err_path.c_str()); + const auto call = ended.out.find("CALL "); + if (call != std::string::npos) { + const auto started = Clock::time_point( + std::chrono::nanoseconds( + std::stoll( + ended.out.substr(call + 5, ended.out.find('\n', call))))); + ended.ms = std::chrono::duration_cast<milliseconds>(end - started).count(); + } + return ended; +} + +int count(const std::string& text, const std::string& part) { + int n = 0; + for (auto at = text.find(part); at != std::string::npos; + at = text.find(part, at + part.size())) { + n++; + } + return n; +} + +[[noreturn]] void child_mismatch(const std::string& what, const Ended& e) { + std::ostringstream text; + text << what << " (status " << e.status << ", " << e.ms + << " ms; stdout: " << e.out << "; stderr: " << e.err << ")"; + throw std::runtime_error(text.str()); +} + +// The child left through teardown_exit: status 75, the reason first, the +// release hook once after the group was released (unless `hook` is false), +// within [at, at + slack] ms of the start of the call. +void expect_teardown_exit( + const Ended& e, + const std::string& reason, + int64_t at, + bool hook = true) { + if (e.status != jaccl::TEARDOWN_EXIT_STATUS) { + child_mismatch("the process did not exit with status 75", e); + } + if (count(e.err, reason) != 1 || + count( + e.err, + "[jaccl] The group is released; releasing memory, then exiting " + "with status 75 (JACCL_TIMEOUT_ACTION=teardown-exit).") != 1) { + child_mismatch("the reason or the exit notice is missing", e); + } + if (hook) { + if (count(e.out, "RELEASE ") != 1 || count(e.out, "RELEASE 1 ok ") != 1 || + count(e.err, "[jaccl] Memory released; exiting with status 75.") != 1) { + child_mismatch( + "the release hook did not run once after the group was released", e); + } + } else if ( + count(e.out, "RELEASE ") != 0 || + count( + e.err, + "[jaccl] No memory release registered; exiting with status 75.") != + 1) { + child_mismatch("a process without a release hook did not say so", e); + } + if (count(e.out, "THREW") != 0 || count(e.out, "RETURNED") != 0) { + child_mismatch("the failed call came back to the caller", e); + } + if (e.ms < at || e.ms > at + slack) { + child_mismatch("the exit is outside [at, at + slack] ms", e); + } + static bool shown = false; + if (!shown) { + std::cout << "INFO teardown exit:\n" << e.err; + shown = true; + } +} + +// The child kept running: the call threw `reason` and nothing was released. +void expect_throw(const Ended& e, const std::string& reason) { + if (e.status != 0 || count(e.out, "THREW " + reason) != 1 || + count(e.out, "RELEASE ") != 0 || + count(e.err, "exiting with status") != 0) { + child_mismatch("the call did not throw to the caller", e); + } +} + +void teardown_exit_checks(const char* program) { + limit = 250; + const std::string limit_text = std::to_string(limit); + const std::string no_progress = "[jaccl] mesh recv: no completion for "; + using Env = std::map<std::string, std::string>; + const Env ms = {{"JACCL_PROGRESS_TIMEOUT_MS", limit_text}}; + check("teardown exit is the default: a stalled mesh recv exits with 75", [&] { + expect_teardown_exit( + run_child(program, "mesh-recv", ms), no_progress, limit); + }); + check("teardown exit by name: a stalled mesh all_reduce exits with 75", [&] { + Env env = ms; + env["JACCL_TIMEOUT_ACTION"] = "teardown-exit"; + expect_teardown_exit( + run_child(program, "mesh-all-reduce", env), + "[jaccl] mesh all_reduce: no completion for ", + limit); + }); + check( + "teardown exit: a stalled ring recv on 2 wires exits after both wires stopped", + [&] { + expect_teardown_exit( + run_child(program, "ring-recv-2", ms), + "[jaccl] ring recv: no completion for ", + limit); + }); + check("teardown exit: a failed completion exits at once", [&] { + const Env env = {{"JACCL_PROGRESS_TIMEOUT_MS", "4000"}}; + const Ended e = run_child(program, "mesh-failed-completion", env); + expect_teardown_exit( + e, "[jaccl] mesh recv: a work completion failed with status 5", 0); + }); + check("teardown exit without a release hook still exits with 75", [&] { + expect_teardown_exit( + run_child(program, "no-hook", ms), no_progress, limit, false); + }); + check( + "teardown exit: a release hook that never returns is cut off after 10 s", + [&] { + const Ended e = run_child(program, "hung-hook", ms); + if (e.status != jaccl::TEARDOWN_EXIT_STATUS || + count( + e.err, + "[jaccl] The memory release did not finish in 10000 ms; " + "exiting.") != 1 || + e.ms < limit + jaccl::TEARDOWN_RELEASE_LIMIT_MS || + e.ms > limit + jaccl::TEARDOWN_RELEASE_LIMIT_MS + slack) { + child_mismatch("the release was not cut off at its limit", e); + } + }); + check( + "teardown exit: two groups that fail together give one release and one exit", + [&] { + expect_teardown_exit( + run_child(program, "two-groups", ms), no_progress, limit); + }); + check("an unknown action keeps the default (teardown exit)", [&] { + Env env = ms; + env["JACCL_TIMEOUT_ACTION"] = "abort"; + expect_teardown_exit( + run_child(program, "mesh-recv", env), no_progress, limit); + }); + check("JACCL_TIMEOUT_ACTION=throw is used before the alias", [&] { + Env env = ms; + env["JACCL_TIMEOUT_ACTION"] = "throw"; + env["MLX_JACCL_TIMEOUT_ACTION"] = "teardown-exit"; + expect_throw(run_child(program, "mesh-recv", env), no_progress); + }); + check("MLX_JACCL_TIMEOUT_ACTION=throw is read when the name is unset", [&] { + Env env = ms; + env["MLX_JACCL_TIMEOUT_ACTION"] = "throw"; + expect_throw(run_child(program, "mesh-recv", env), no_progress); + }); +} + +// No variable at all: the 30 s default limit and the teardown exit. +void default_exit_check(const char* program) { + limit = 30000; + check( + "default: with no variable a stalled mesh recv exits with 75 after 30 s", + [&] { + const Ended e = run_child(program, "mesh-recv", {}); + expect_teardown_exit(e, "[jaccl] mesh recv: no completion for ", limit); + if (count(e.err, "(JACCL_PROGRESS_TIMEOUT_MS is 30000)") != 1) { + child_mismatch("the reason does not name the 30 s limit", e); + } + }); +} + +} // namespace + +// One mode in each process: +// checks all cases with a limit of 2000 ms +// disabled a limit of 0: a stalled call continues to wait +// alias the limit comes from MLX_JACCL_PROGRESS_TIMEOUT_MS +// precedence JACCL_PROGRESS_TIMEOUT_MS is used before the alias +// negative a negative value removes the limit +// not-a-number a value that is not a number keeps the default +// default no variable: the default limit (30 s) and action +// teardown-exit the failure action, each case in a child process +// default-exit no variable: a stalled call exits with 75 after 30 s +// All modes but the last three select JACCL_TIMEOUT_ACTION=throw. +int main(int count, char** arguments) { + const char* name = "JACCL_PROGRESS_TIMEOUT_MS"; + const char* alias = "MLX_JACCL_PROGRESS_TIMEOUT_MS"; + const std::string mode = count >= 2 ? arguments[1] : ""; + if (mode == "child" && count == 3) { + return child(arguments[2]); + } + // The guard reads the variables when the first call starts. + unsetenv(name); + unsetenv(alias); + unsetenv("JACCL_TIMEOUT_ACTION"); + unsetenv("MLX_JACCL_TIMEOUT_ACTION"); + if (mode != "default" && mode != "teardown-exit" && mode != "default-exit") { + setenv("JACCL_TIMEOUT_ACTION", "throw", 1); + } + if (mode == "checks") { + // Every case scales with the limit: below-limit gaps are limit / 2 and + // over-limit stalls must trip in [limit, limit + slack]. 2000 ms leaves a + // hosted runner 1 s of scheduling delay inside a below-limit gap. + setenv(name, "2000", 1); + value(2000); + silent_peer(); + lost_completion(); + failed_completion(); + refused_destroy(); + refused_deregister(); + mesh_wires_share_failure(); + below_limit(); + pool_wire_error(); + } else if (mode == "disabled") { + setenv(name, "0", 1); + value(0); + disabled(); + } else if (mode == "alias") { + setenv(alias, "400", 1); + value(400); + stall(); + } else if (mode == "precedence") { + setenv(name, "300", 1); + setenv(alias, "60000", 1); + value(300); + stall(); + } else if (mode == "negative") { + setenv(name, "-1", 1); + value(-1); + } else if (mode == "not-a-number") { + setenv(name, "30s", 1); + value(jaccl::DEFAULT_PROGRESS_TIMEOUT_MS); + } else if (mode == "default") { + value(30000); + check( + "the default limit is 30 s and the default action teardown-exit", [&] { + fixture::require( + jaccl::DEFAULT_PROGRESS_TIMEOUT_MS == 30000 && + jaccl::failure_action() == jaccl::FailureAction::TeardownExit, + "unexpected default limit or action"); + }); + } else if (mode == "teardown-exit") { + teardown_exit_checks(arguments[0]); + } else if (mode == "default-exit") { + default_exit_check(arguments[0]); + } else { + std::cout << "FAIL usage: progress_guard_tests checks | disabled | alias | " + "precedence | negative | not-a-number | default | " + "teardown-exit | default-exit\n"; + return 2; + } + const auto& ledger = fixture::ledger(); + check( + "every fake queue pair, completion queue and region was freed once", [&] { + fixture::require( + ledger.queue_pairs == 0 && ledger.completion_queues == 0 && + ledger.regions == 0, + "Fake verbs objects remain after the checks"); + }); + std::cout << (failures ? "FAIL " : "PASS ") << passes << " passed, " + << failures << " failed; limit " << limit + << " ms; simulated verbs\n"; + return failures ? 1 : 0; +}
diff --git ml-explore/mlx/tests/jaccl/send_frame_tests.cpp Layr-Labs/mlx/tests/jaccl/send_frame_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..849fbf8ffc6b01c5886135c56c4453369d4a6fb8 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/send_frame_tests.cpp @@ -0,0 +1,363 @@ +// Copyright © 2026 Apple Inc. + +// Tests of the send staging with simulated verbs. The scratch buffers start +// with a sentinel in each byte, and the fake endpoint keeps each posted frame. +// Each frame must hold the payload and then only zero bytes. + +#include <iostream> +#include <limits> + +#include "fixture.h" +#include "jaccl/send_frame.h" + +namespace { + +void staging_bounds() { + alignas(double) std::array<char, 32> frame; + const std::array<uint32_t, 2> input{0x01020304, 0x05060708}; + frame.fill(char(fixture::sentinel)); + jaccl::stage_send_frame(std::span<char>(frame), input.data(), 2); + fixture::require( + std::memcmp(frame.data(), input.data(), 8) == 0, + "Typed payload bytes changed"); + fixture::zero_tail( + {0, 0, 0, std::vector<char>(frame.begin(), frame.end())}, 8); + jaccl::stage_send_frame( + std::span<char>(frame), static_cast<const uint32_t*>(nullptr), 0); + fixture::zero_tail( + {0, 0, 0, std::vector<char>(frame.begin(), frame.end())}, 0); + for (int64_t count : + {int64_t(-1), int64_t(9), std::numeric_limits<int64_t>::max()}) { + frame.fill(char(fixture::sentinel)); + bool refused = false; + try { + jaccl::stage_send_frame(std::span<char>(frame), input.data(), count); + } catch (const std::invalid_argument&) { + refused = true; + } + fixture::require( + refused && + std::all_of( + frame.begin(), + frame.end(), + [](char value) { + return static_cast<unsigned char>(value) == fixture::sentinel; + }), + "Invalid count must refuse before any scratch write"); + } + bool refused = false; + try { + jaccl::stage_send_frame( + std::span<char>(frame), static_cast<const char*>(nullptr), 1); + } catch (const std::invalid_argument&) { + refused = true; + } + fixture::require(refused, "Null nonempty source refused"); +} + +void mesh_point_to_point() { + fixture::MeshPair pair; + const int64_t maximum = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + for (int64_t count : + {int64_t(1), + int64_t(24), + int64_t(4096), + int64_t(17), + int64_t(4097), + maximum * 3 + 17}) { + pair.fabric.frames.clear(); + std::vector<char> input(count, 0x53), output(count + 1, 0x29); + fixture::both( + [&] { pair.nodes[0]->send(input.data(), count, 1); }, + [&] { pair.nodes[1]->recv(output.data(), count, 0); }); + fixture::require( + std::equal(input.begin(), input.end(), output.begin()) && + output.back() == 0x29, + "Mesh receive changed payload or wrote past end"); + pair.fabric.require_drained(); + fixture::payload_frames(fixture::selected(pair.fabric, 0, 0, 0), input); + } +} + +void ring_point_to_point() { + const int64_t maximum = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + for (int wires : {1, 2}) { + fixture::RingPair pair(wires); + for (int64_t count : + {int64_t(1), int64_t(4096), int64_t(17), maximum * 3 * wires + 13}) { + pair.fabric.frames.clear(); + std::vector<char> input(count, 0x64), output(count + 1, 0x29); + fixture::both( + [&] { pair.nodes[0]->send(input.data(), count, 1, wires); }, + [&] { pair.nodes[1]->recv(output.data(), count, 0, wires); }); + fixture::require( + std::equal(input.begin(), input.end(), output.begin()) && + output.back() == 0x29, + "Ring receive changed payload or wrote past end"); + pair.fabric.require_drained(); + const size_t per_wire = (count + wires - 1) / wires; + for (int wire = 0; wire < wires; ++wire) { + const size_t start = std::min(size_t(count), wire * per_wire); + const size_t end = std::min(size_t(count), (wire + 1) * per_wire); + auto frames = fixture::selected(pair.fabric, 0, 1, wire); + fixture::payload_frames( + frames, std::span<const char>(input).subspan(start, end - start)); + } + } + } +} + +std::span<const char> byte_view( + const std::vector<float>& values, + size_t count) { + return {reinterpret_cast<const char*>(values.data()), count * sizeof(float)}; +} + +void all_equal(const std::vector<float>& values, size_t count, float expected) { + fixture::require( + std::all_of( + values.begin(), + values.begin() + count, + [&](float value) { return value == expected; }), + "Collective logical output changed"); + fixture::require( + values[count] == -19, "Collective wrote outside logical output"); +} + +void mesh_collectives() { + const size_t count = + (FRAME_SIZE * (1 << (BUFFER_SIZES - 1)) * 3) / sizeof(float) + 7; + for (int operation : {0, 1, 2}) { + fixture::MeshPair pair; + std::array<std::vector<float>, 2> input, output; + for (int rank = 0; rank < 2; ++rank) { + input[rank].assign(count * 2, float(rank + 1)); + output[rank].assign(count * 2 + 1, -19); + } + auto run = [&](int rank) { + if (operation == 0) { + pair.nodes[rank]->all_reduce( + input[rank].data(), output[rank].data(), count, fixture::Add{}); + } else if (operation == 1) { + pair.nodes[rank]->all_gather( + reinterpret_cast<const char*>(input[rank].data()), + reinterpret_cast<char*>(output[rank].data()), + count * sizeof(float), + count * sizeof(float)); + } else { + pair.nodes[rank]->sum_scatter( + input[rank].data(), + output[rank].data(), + count, + count, + fixture::Add{}); + } + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + pair.fabric.require_drained(); + for (int rank = 0; rank < 2; ++rank) { + if (operation == 1) { + fixture::require( + std::all_of( + output[rank].begin(), + output[rank].begin() + count, + [](float value) { return value == 1; }), + "Gather rank0 payload changed"); + fixture::require( + std::all_of( + output[rank].begin() + count, + output[rank].begin() + count * 2, + [](float value) { return value == 2; }) && + output[rank].back() == -19, + "Gather rank1 payload or output bound changed"); + } else { + all_equal(output[rank], count, 3); + } + fixture::payload_frames( + fixture::selected(pair.fabric, rank, rank, 0), + byte_view(input[rank], count)); + } + } +} + +void ring_collectives() { + // A chunk of 1 gives slices with no payload. The long chunk fills each + // pipeline slot again. buffer_size_from_message selects the frame sizes. + const int64_t maximum = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + for (bool scatter : {false, true}) { + for (int64_t chunk : + {int64_t(1), maximum * 3 / int64_t(sizeof(float)) * 4 + 7}) { + const int wires = 2; + fixture::RingPair pair(wires); + const int64_t count = scatter ? chunk * 2 : chunk; + const int64_t stage_chunk = scatter ? chunk : (count + 1) / 2; + const int64_t per_wire = (stage_chunk + 2 * wires - 1) / (2 * wires); + const int64_t capacity = + buffer_size_from_message(per_wire * sizeof(float)).second; + const int64_t elements = capacity / sizeof(float); + const int64_t steps = (per_wire + elements - 1) / elements; + std::array<std::vector<float>, 2> input, output; + for (int rank = 0; rank < 2; ++rank) { + input[rank].assign(count, float(rank + 1)); + output[rank].assign((scatter ? chunk : count) + 32, -19); + } + auto run = [&](int rank) { + if (scatter) { + pair.nodes[rank]->reduce_scatter( + input[rank].data(), + output[rank].data(), + count, + wires, + fixture::Add{}); + } else { + pair.nodes[rank]->all_reduce<2>( + input[rank].data(), + output[rank].data(), + count, + wires, + fixture::Add{}); + } + }; + fixture::both([&] { run(0); }, [&] { run(1); }); + pair.fabric.require_drained(); + for (int rank = 0; rank < 2; ++rank) { + all_equal(output[rank], scatter ? chunk : count, 3); + for (int direction = 0; direction < 2; ++direction) { + for (int wire = 0; wire < wires; ++wire) { + auto frames = fixture::selected(pair.fabric, rank, direction, wire); + const int passes = scatter ? 1 : 2; + fixture::require( + frames.size() == size_t(steps * passes), + "Ring completion/frame count changed"); + const int64_t offset = + direction * wires * per_wire + wire * per_wire; + const int64_t end = std::min(stage_chunk, offset + per_wire); + for (int pass = 0; pass < passes; ++pass) { + const int64_t source_offset = + (pass == 0 ? rank : 1 - rank) * stage_chunk; + const int64_t limit = scatter + ? end + : std::min(end, std::max<int64_t>(0, count - source_offset)); + for (int64_t step = 0; step < steps; ++step) { + const int64_t valid = std::max<int64_t>( + 0, std::min(elements, limit - offset - step * elements)); + const auto& frame = frames[pass * steps + step]; + fixture::require( + frame.bytes.size() == size_t(capacity), + "Ring posted SGE length changed"); + fixture::zero_tail(frame, valid * sizeof(float)); + } + } + } + } + } + } + } +} + +// Ring all gather with different data on each rank. A gather of equal data +// cannot find a region that was not transferred. +void ring_gather() { + const int64_t maximum = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); + for (int wires : {1, 2}) { + for (int64_t bytes : + {int64_t(1), + int64_t(7), + int64_t(4096), + int64_t(4097), + maximum * 3 * wires + 13}) { + fixture::RingPair pair(wires); + std::array<std::vector<char>, 2> input, output; + for (int rank = 0; rank < 2; ++rank) { + input[rank].resize(bytes); + for (int64_t index = 0; index < bytes; ++index) { + input[rank][index] = char((index * 31 + rank * 101 + 7) % 251); + } + output[rank].assign(bytes * 2 + 1, 0x29); + } + fixture::both( + [&] { + pair.nodes[0]->all_gather( + input[0].data(), output[0].data(), bytes, wires); + }, + [&] { + pair.nodes[1]->all_gather( + input[1].data(), output[1].data(), bytes, wires); + }); + pair.fabric.require_drained(); + for (int rank = 0; rank < 2; ++rank) { + for (int source = 0; source < 2; ++source) { + fixture::require( + std::equal( + input[source].begin(), + input[source].end(), + output[rank].begin() + source * bytes), + "Ring all gather lost or misplaced a rank region"); + } + fixture::require( + output[rank].back() == 0x29, + "Ring all gather wrote past the output"); + } + } + } +} + +// Run all groups, so that a failure does not hide the next ones. +bool group(void (*check)(), const char* name) { + try { + check(); + std::cout << "PASS " << name << '\n'; + return true; + } catch (const std::exception& error) { + std::cout << "FAIL " << name << ": " << error.what() << '\n'; + return false; + } +} + +} // namespace + +int main() { + bool passed = + group(staging_bounds, "bounded typed staging and zero-logical frame"); + passed &= group( + mesh_point_to_point, + "mesh short/full/reused/multiframe and actual receive"); + passed &= group( + ring_point_to_point, + "ring one/two-wire short/full/reused/multiframe receive"); + passed &= group( + mesh_collectives, "mesh gather/reduce/scatter valid payload and tail"); + passed &= group( + ring_collectives, "ring reduction/scatter full/partial/zero slices"); + passed &= + group(ring_gather, "ring all_gather distinct rank data, one/two wires"); + // The completion queues of the groups have COMPLETION_QUEUE_DEPTH entries, + // four times the work a queue pair can have outstanding. Report how many + // completions this traffic queued at the same time; it must stay within the + // outstanding bound, so that the headroom is real. + static_assert(COMPLETION_QUEUE_DEPTH == 4 * (MAX_SEND_WR + MAX_RECV_WR)); + const size_t depth = fixture::ledger().completion_high_water; + const size_t outstanding = MAX_SEND_WR + MAX_RECV_WR; + if (depth <= outstanding) { + std::cout << "PASS completion queue high-water mark " << depth << " of " + << COMPLETION_QUEUE_DEPTH << " entries (outstanding bound " + << outstanding << ")\n"; + } else { + std::cout << "FAIL completion queue high-water mark " << depth + << " exceeds the outstanding bound " << outstanding << '\n'; + passed = false; + } + const auto& ledger = fixture::ledger(); + if (ledger.queue_pairs == 0 && ledger.completion_queues == 0 && + ledger.regions == 0) { + std::cout + << "PASS every fake queue pair, completion queue and region was freed once\n"; + } else { + std::cout << "FAIL fake verbs objects remain after the checks\n"; + passed = false; + } + if (!passed) { + return 1; + } + return 0; +}
diff --git ml-explore/mlx/tests/jaccl/startup_wait_budget_api_tests.cpp Layr-Labs/mlx/tests/jaccl/startup_wait_budget_api_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28bd34336f2c7a2e4e9d4916d0f416ab6b268cdb --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/startup_wait_budget_api_tests.cpp @@ -0,0 +1,75 @@ +// Copyright © 2026 Apple Inc. +#include <iostream> +#include <type_traits> +#include "jaccl/group.h" +#include "mlx/distributed/distributed_impl.h" + +using mlx::core::array; +using mlx::core::Stream; +using mlx::core::StreamOrDevice; +using mlx::core::distributed::Group; +using mlx::core::distributed::detail::GroupImpl; +static_assert(std::is_same_v< + decltype(&Group::begin_startup_wait_budget), + void (Group::*)(int64_t) const>); +static_assert(std::is_same_v< + decltype(&Group::end_startup_wait_budget), + void (Group::*)() const>); +class Unsupported : public GroupImpl { + public: + Stream communication_stream(StreamOrDevice) override { + throw std::runtime_error("unused"); + } + int rank() override { + return 0; + } + int size() override { + return 1; + } + std::shared_ptr<GroupImpl> split(int, int) override { + return nullptr; + } + void all_sum(const array&, array&, Stream) override {} + void all_max(const array&, array&, Stream) override {} + void all_min(const array&, array&, Stream) override {} + void all_gather(const array&, array&, Stream) override {} + void sum_scatter(const array&, array&, Stream) override {} + void send(const array&, int, Stream) override {} + void recv(array&, int, Stream) override {} +}; +class UnsupportedStandalone : public jaccl::Group { + public: + int rank() override { + return 0; + } + int size() override { + return 1; + } + void all_sum(const void*, void*, size_t, int) override {} + void all_max(const void*, void*, size_t, int) override {} + void all_min(const void*, void*, size_t, int) override {} + void all_gather(const void*, void*, size_t) override {} + void sum_scatter(const void*, void*, size_t, int) override {} + void send(const void*, size_t, int) override {} + void recv(void*, size_t, int) override {} + void barrier() override {} +}; +template <typename Fn> +void refuses(Fn fn) { + try { + fn(); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error("unsupported backend accepted startup budget"); +} +int main() { + Unsupported group; + UnsupportedStandalone standalone; + refuses([&] { group.begin_startup_wait_budget(1000); }); + refuses([&] { group.end_startup_wait_budget(); }); + refuses([&] { standalone.begin_startup_wait_budget(1000); }); + refuses([&] { standalone.end_startup_wait_budget(); }); + std::cout + << "PASS exact public const API types\nPASS unsupported GroupImpl begin/end\nPASS unsupported standalone begin/end\npassed=3 failed=0 skipped=0 native_rdma=0\n"; +}
diff --git ml-explore/mlx/tests/jaccl/startup_wait_budget_group_tests.cpp Layr-Labs/mlx/tests/jaccl/startup_wait_budget_group_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3aab8d04e10c7645d796a9155015bf8c805cbe79 --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/startup_wait_budget_group_tests.cpp @@ -0,0 +1,123 @@ +// Copyright © 2026 Apple Inc. +// CPU simulated verbs only. Real MeshImpl/RingImpl call and cleanup paths. +#include <iostream> +#include <thread> +#include "fixture.h" + +void require(bool value) { + fixture::require(value, "startup group assertion failed"); +} +template <typename Fn> +void refuses(Fn fn, const std::string& text) { + try { + fn(); + } catch (const std::exception& e) { + require(std::string(e.what()).find(text) != std::string::npos); + return; + } + throw std::runtime_error("expected refusal"); +} +void mesh_success_end() { + fixture::MeshPair pair; + for (auto& node : pair.nodes) { + node->begin_startup_wait_budget(10000); + } + char input = 42, output = 0; + fixture::both( + [&] { pair.nodes[0]->send(&input, 1, 1); }, + [&] { pair.nodes[1]->recv(&output, 1, 0); }); + require(input == output); + pair.fabric.require_drained(); + for (auto& node : pair.nodes) { + node->end_startup_wait_budget(); + refuses([&] { node->begin_startup_wait_budget(10000); }, "only begin once"); + } + fixture::both( + [&] { pair.nodes[0]->send(&input, 1, 1); }, + [&] { pair.nodes[1]->recv(&output, 1, 0); }); + pair.fabric.require_drained(); +} +void ring_success_end(int wires) { + fixture::RingPair pair(wires); + for (auto& node : pair.nodes) { + node->begin_startup_wait_budget(10000); + } + std::vector<char> input(99, 42), output(99, 0); + fixture::both( + [&] { pair.nodes[0]->send(input.data(), 99, 1, wires); }, + [&] { pair.nodes[1]->recv(output.data(), 99, 0, wires); }); + require(input == output); + pair.fabric.require_drained(); + for (auto& node : pair.nodes) { + node->end_startup_wait_budget(); + } + fixture::both( + [&] { pair.nodes[0]->send(input.data(), 99, 1, wires); }, + [&] { pair.nodes[1]->recv(output.data(), 99, 0, wires); }); + pair.fabric.require_drained(); +} +// The guard samples the startup deadline once in PROGRESS_SAMPLE_POLLS empty +// polls. With the default 1 ms idle wait per empty poll, that is 1024 sleeps, +// which a hosted runner stretches past the fake poll's 8 s deadline. The +// expiry cases poll without a sleep, as the hardware does. +void spin(fixture::Fabric& fabric) { + fabric.idle_wait = std::chrono::milliseconds(0); +} +void mesh_expiry_cleanup() { + fixture::MeshPair pair; + spin(pair.fabric); + auto& node = *pair.nodes[0]; + node.begin_startup_wait_budget(1); + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + char output = 0; + const auto qp = fixture::ledger().destroy_queue_pair_calls.load(); + const auto cq = fixture::ledger().destroy_completion_queue_calls.load(); + const auto mr = fixture::ledger().deregister_calls.load(); + refuses([&] { node.recv(&output, 1, 1); }, "absolute startup"); + require(fixture::ledger().destroy_queue_pair_calls == qp + 1); + require(fixture::ledger().destroy_completion_queue_calls == cq + 1); + require(fixture::ledger().deregister_calls > mr); + refuses([&] { node.end_startup_wait_budget(); }, "closed"); + refuses([&] { node.begin_startup_wait_budget(10000); }, "closed"); + refuses([&] { node.recv(&output, 1, 1); }, "closed"); +} +void ring_expiry_cleanup(int wires) { + fixture::RingPair pair(wires); + spin(pair.fabric); + auto& node = *pair.nodes[0]; + node.begin_startup_wait_budget(1); + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + std::vector<char> output(99, 0); + const auto qp = fixture::ledger().destroy_queue_pair_calls.load(); + const auto cq = fixture::ledger().destroy_completion_queue_calls.load(); + const auto mr = fixture::ledger().deregister_calls.load(); + refuses([&] { node.recv(output.data(), 99, 1, wires); }, "absolute startup"); + require(fixture::ledger().destroy_queue_pair_calls == qp + 2 * wires); + require(fixture::ledger().destroy_completion_queue_calls == cq + 2 * wires); + require(fixture::ledger().deregister_calls > mr); + refuses([&] { node.end_startup_wait_budget(); }, "closed"); + refuses([&] { node.begin_startup_wait_budget(10000); }, "closed"); + refuses([&] { node.recv(output.data(), 99, 1, wires); }, "closed"); +} +int main() { + jaccl::set_memory_release(nullptr); + require(jaccl::failure_action() == jaccl::FailureAction::Throw); + mesh_success_end(); + std::cout << "PASS mesh success/end/later-serving\n"; + for (int wires : {1, 2}) { + ring_success_end(wires); + std::cout << "PASS ring success/end/later-serving wires=" << wires << "\n"; + } + mesh_expiry_cleanup(); + std::cout << "PASS mesh expiry/cleanup/closed\n"; + for (int wires : {1, 2}) { + ring_expiry_cleanup(wires); + std::cout << "PASS ring expiry/cleanup/closed wires=" << wires << "\n"; + } + require( + fixture::ledger().queue_pairs == 0 && + fixture::ledger().completion_queues == 0 && + fixture::ledger().regions == 0); + std::cout + << "PASS fake resource ledger empty\npassed=7 failed=0 skipped=0 native_rdma=0\n"; +}
diff --git ml-explore/mlx/tests/jaccl/startup_wait_budget_tests.cpp Layr-Labs/mlx/tests/jaccl/startup_wait_budget_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67114bb0ed2b6d2a085e1258514cfda3a824363a --- /dev/null +++ Layr-Labs/mlx/tests/jaccl/startup_wait_budget_tests.cpp @@ -0,0 +1,441 @@ +// Copyright © 2026 Apple Inc. +// Standalone CPU policy tests: use the real policy and guard with a fake clock. +#include <atomic> +#include <chrono> +#include <cstdint> +#include <functional> +#include <iostream> +#include <limits> +#include <stdexcept> +#include <string> +#include <thread> +#include <vector> + +struct FakeClock { + using duration = std::chrono::nanoseconds; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point<FakeClock>; + static constexpr bool is_steady = true; + static inline std::atomic<int64_t> ticks{0}; + static time_point now() { + return time_point(duration(ticks.load())); + } + static void ms(int64_t n) { + ticks.store(n * 1000000); + } +}; + +#include "jaccl/progress_guard.h" + +using Policy = jaccl::BasicStartupWaitBudget<FakeClock>; +using Guard = jaccl::BasicProgressGuard<FakeClock>; +using namespace std::chrono_literals; + +void require(bool ok) { + if (!ok) { + throw std::runtime_error("assertion failed"); + } +} +template <typename E = std::exception, typename Fn> +void refuses(Fn fn, const std::string& message = "") { + try { + fn(); + } catch (const E& e) { + require( + message.empty() || + std::string(e.what()).find(message) != std::string::npos); + return; + } + throw std::runtime_error("expected refusal"); +} +void sample(Guard& g) { + for (int i = 0; i < jaccl::PROGRESS_SAMPLE_POLLS; ++i) { + g.check(nullptr, 0); + } +} +ibv_wc success{}; + +void default_idle() { + std::atomic<bool> failed{false}; + Guard g("default", failed); + sample(g); + FakeClock::ms(30000); + sample(g); + require(!failed); + FakeClock::ms(30001); + refuses([&] { sample(g); }, "no completion for 30001"); + require(failed); +} +void default_progress_resets_idle() { + std::atomic<bool> failed{false}; + Policy p; + Guard g("default group", failed, &p); + sample(g); + FakeClock::ms(29000); + g.check(&success, 1); + sample(g); + FakeClock::ms(59000); + sample(g); + require(!failed); + FakeClock::ms(59001); + refuses([&] { sample(g); }); +} +void startup_deadline() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(120000, failed); + Guard g("startup", failed, &p); + sample(g); + FakeClock::ms(30001); + sample(g); + FakeClock::ms(119999); + sample(g); + require(!failed); + FakeClock::ms(120000); + refuses([&] { sample(g); }, "absolute startup"); + require(failed); +} +void progress_cannot_renew() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(60000, failed); + Guard g("progress", failed, &p); + for (int i = 1; i < 60; ++i) { + FakeClock::ms(i * 1000); + g.check(&success, 1); + } + FakeClock::ms(60000); + refuses([&] { g.check(&success, 1); }, "absolute startup"); + require(failed); +} +void deadline_shared_across_calls() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(60000, failed); + { + Guard first("first", failed, &p); + FakeClock::ms(40000); + first.check(&success, 1); + } + Guard second("second", failed, &p); + FakeClock::ms(60000); + refuses([&] { second.check(&success, 1); }); +} +void end_restores_idle() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(120000, failed); + { + Guard startup("startup", failed, &p); + FakeClock::ms(40000); + startup.check(&success, 1); + } + p.end(failed); + Guard serving("serving", failed, &p); + sample(serving); + FakeClock::ms(70000); + sample(serving); + require(!failed); + FakeClock::ms(70001); + refuses([&] { sample(serving); }, "no completion"); +} +void invalid_does_not_consume() { + std::atomic<bool> failed{false}; + Policy p; + for (int64_t n : + {int64_t(-1), + int64_t(0), + int64_t(900001), + std::numeric_limits<int64_t>::max(), + std::numeric_limits<int64_t>::min()}) { + refuses<std::invalid_argument>([&] { p.begin(n, failed); }); + } + p.begin(1, failed); + Guard g("minimum", failed, &p); + FakeClock::ms(1); + refuses([&] { g.check(&success, 1); }); +} +void maximum_budget() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(900000, failed); + Guard g("maximum", failed, &p); + FakeClock::ms(899999); + g.check(&success, 1); + FakeClock::ms(900000); + refuses([&] { g.check(&success, 1); }); +} +void checked_overflow() { + std::atomic<bool> failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits<int64_t>::max() - 999999); + refuses<std::overflow_error>([&] { p.begin(1, failed); }); + FakeClock::ms(0); + p.begin(1, failed); + p.end(failed); +} +void exact_clock_limit() { + std::atomic<bool> failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits<int64_t>::max() - 1000000); + p.begin(1, failed); + Guard g("clock limit", failed, &p); + FakeClock::ticks.store(std::numeric_limits<int64_t>::max()); + refuses([&] { g.check(&success, 1); }); +} +void negative_clock_epoch() { + std::atomic<bool> failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits<int64_t>::min()); + p.begin(900000, failed); + p.end(failed); +} +void one_shot() { + std::atomic<bool> failed{false}; + Policy p; + refuses<std::logic_error>([&] { p.end(failed); }); + p.begin(1000, failed); + refuses<std::logic_error>([&] { p.begin(900000, failed); }); + p.end(failed); + refuses<std::logic_error>([&] { p.end(failed); }); + refuses<std::logic_error>([&] { p.begin(1000, failed); }); +} +void expired_end_refuses() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(1000, failed); + FakeClock::ms(1000); + refuses<std::logic_error>([&] { p.end(failed); }, "expired"); + refuses<std::logic_error>([&] { p.begin(1000, failed); }); + Guard g("still expired", failed, &p); + refuses([&] { g.check(&success, 1); }); + require(failed); +} +void closed_group_stays_closed() { + std::atomic<bool> failed{true}; + Policy p; + refuses([&] { p.begin(1000, failed); }); + require(failed); + std::atomic<bool> another_failed{false}; + Policy q; + q.begin(1000, another_failed); + another_failed = true; + refuses([&] { q.end(another_failed); }); + refuses([&] { q.begin(1000, another_failed); }); + require(another_failed); +} +void transitions_refuse_running_calls() { + std::atomic<bool> failed{false}; + Policy p; + { + Guard g("default live", failed, &p); + refuses<std::logic_error>([&] { p.begin(1000, failed); }, "idle"); + } + p.begin(1000, failed); + { + Guard g("startup live", failed, &p); + refuses<std::logic_error>([&] { p.end(failed); }, "idle"); + } + p.end(failed); +} +void two_groups() { + std::atomic<bool> a_failed{false}, b_failed{false}; + Policy a, b; + a.begin(120000, a_failed); + Guard ga("A", a_failed, &a), gb("B", b_failed, &b); + sample(ga); + sample(gb); + FakeClock::ms(30001); + sample(ga); + refuses([&] { sample(gb); }); + require(!a_failed && b_failed); +} +void two_active_groups() { + std::atomic<bool> a_failed{false}, b_failed{false}; + Policy a, b; + a.begin(1000, a_failed); + b.begin(2000, b_failed); + Guard ga("active A", a_failed, &a), gb("active B", b_failed, &b); + FakeClock::ms(1000); + refuses([&] { ga.check(&success, 1); }); + gb.check(&success, 1); + require(!b_failed); + FakeClock::ms(2000); + refuses([&] { gb.check(&success, 1); }); +} +void shared_wires() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(60000, failed); + Guard a("wire A", failed, &p), b("wire B", failed, &p); + FakeClock::ms(60000); + refuses([&] { a.check(&success, 1); }, "absolute startup"); + refuses<jaccl::WireStopped>([&] { sample(b); }); +} +void late_wire_keeps_failure_kind() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(1000, failed); + failed = true; + Guard late("late wire", failed, &p); + refuses<jaccl::WireStopped>([&] { late.check(&success, 1); }); +} + +void concurrent_begin() { + std::atomic<bool> failed{false}; + Policy p; + std::atomic<int> won{0}, refused{0}; + std::vector<std::thread> threads; + for (int i = 0; i < 16; ++i) { + threads.emplace_back([&] { + try { + p.begin(1000, failed); + ++won; + } catch (const std::logic_error&) { + ++refused; + } + }); + } + for (auto& t : threads) { + t.join(); + } + require(won == 1 && refused == 15); + p.end(failed); +} +void concurrent_transition_and_wires() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(1000, failed); + std::atomic<int> ready{0}; + std::atomic<bool> release{false}; + std::vector<std::thread> threads; + for (int i = 0; i < 8; ++i) { + threads.emplace_back([&] { + Guard g("wire", failed, &p); + ++ready; + while (!release.load()) { + std::this_thread::yield(); + } + g.check(&success, 1); + }); + } + while (ready != 8) { + std::this_thread::yield(); + } + refuses<std::logic_error>([&] { p.end(failed); }, "idle"); + release = true; + for (auto& t : threads) { + t.join(); + } + p.end(failed); +} +void hardware_error_preserved() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(1000, failed); + Guard g("hardware", failed, &p); + ibv_wc wc{}; + wc.status = IBV_WC_WR_FLUSH_ERR; + refuses([&] { g.check(&wc, 1); }, "work completion failed"); + require(failed); +} +void poll_error_preserved() { + std::atomic<bool> failed{false}; + Policy p; + p.begin(1000, failed); + Guard g("poll", failed, &p); + refuses([&] { g.check(nullptr, -1); }, "could not be polled"); + require(failed); +} + +int environment_policy() { + std::atomic<bool> failed{false}; + Policy p; + const int64_t timeout = jaccl::progress_timeout_ms(); + { + Guard g("environment default", failed, &p); + sample(g); + FakeClock::ms(1000000); + if (timeout > 0) { + refuses([&] { sample(g); }); + } else { + sample(g); + require(!failed); + } + } + failed = false; + FakeClock::ms(0); + Policy startup; + startup.begin(1000, failed); + { + Guard g("environment startup", failed, &startup); + FakeClock::ms(500); + g.check(&success, 1); + FakeClock::ms(1000); + refuses([&] { g.check(&success, 1); }, "absolute startup"); + } + failed = false; + FakeClock::ms(0); + Policy ended; + ended.begin(1000, failed); + ended.end(failed); + { + Guard g("environment ended", failed, &ended); + sample(g); + FakeClock::ms(1000000); + if (timeout > 0) { + refuses([&] { sample(g); }); + } else { + sample(g); + require(!failed); + } + } + std::cout << "PASS environment default/startup/end timeout=" << timeout + << "\n"; + return 0; +} + +int main(int argc, char**) { + if (argc > 1) { + return environment_policy(); + } + const std::vector<std::pair<const char*, std::function<void()>>> tests = { + {"default_idle", default_idle}, + {"default_progress_resets_idle", default_progress_resets_idle}, + {"startup_deadline", startup_deadline}, + {"progress_cannot_renew", progress_cannot_renew}, + {"deadline_shared_across_calls", deadline_shared_across_calls}, + {"end_restores_idle", end_restores_idle}, + {"invalid_does_not_consume", invalid_does_not_consume}, + {"maximum_budget", maximum_budget}, + {"checked_overflow", checked_overflow}, + {"exact_clock_limit", exact_clock_limit}, + {"negative_clock_epoch", negative_clock_epoch}, + {"one_shot", one_shot}, + {"expired_end_refuses", expired_end_refuses}, + {"closed_group_stays_closed", closed_group_stays_closed}, + {"transitions_refuse_running_calls", transitions_refuse_running_calls}, + {"two_groups", two_groups}, + {"two_active_groups", two_active_groups}, + {"shared_wires", shared_wires}, + {"late_wire_keeps_failure_kind", late_wire_keeps_failure_kind}, + {"concurrent_begin", concurrent_begin}, + {"concurrent_transition_and_wires", concurrent_transition_and_wires}, + {"hardware_error_preserved", hardware_error_preserved}, + {"poll_error_preserved", poll_error_preserved}, + }; + int passed = 0; + for (const auto& [name, test] : tests) { + FakeClock::ms(0); + try { + test(); + ++passed; + std::cout << "PASS " << name << "\n"; + } catch (const std::exception& e) { + std::cerr << "FAIL " << name << ": " << e.what() << "\n"; + return 1; + } + } + std::cout << "passed=" << passed << " failed=0 skipped=0 native_rdma=0\n"; +}

The embedding program installs an authenticated frame codec for a two-rank floating-point all-sum. The CPU communication stream seals each partial, gathers the frames, opens the peer frame and adds in rank order. Missing codecs and authentication failures refuse evaluation without a plaintext fallback. The distributed primitive retains its temporary arrays until the queued work completes. On a two-rank JACCL mesh the sum streams in 256 KiB pieces, each with its own AES-256-GCM tag, over MeshImpl::exchange: a piece is sent as soon as it is sealed and opened and added as soon as it lands. Other groups keep the seal-gather-open path. Non-Apple builds use synchronous piece sealing and opening without Apple dispatch or QoS APIs, preserving the authenticated wire format and rank-ordered arithmetic. Apple keeps its existing parallel path.

diff --git ml-explore/mlx/mlx/distributed/CMakeLists.txt Layr-Labs/mlx/mlx/distributed/CMakeLists.txt index 807fd0fbdb791211d6517ded4f57857c2841eb92..dba62b2720cea74bf97d2989705a7a6e682c80c5 100644 --- ml-explore/mlx/mlx/distributed/CMakeLists.txt +++ Layr-Labs/mlx/mlx/distributed/CMakeLists.txt @@ -2,7 +2,8 @@ target_sources( mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/primitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ops.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/distributed.cpp) + ${CMAKE_CURRENT_SOURCE_DIR}/distributed.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sealed.cpp)   if(MLX_BUILD_CPU AND NOT WIN32) target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp)
diff --git ml-explore/mlx/mlx/distributed/primitives.h Layr-Labs/mlx/mlx/distributed/primitives.h index 18a0d65f5f30881eb06f1de6ddeae03b09b0c6ba..ea72abce4dc7c8ab297251871499ccde8104cf74 100644 --- ml-explore/mlx/mlx/distributed/primitives.h +++ Layr-Labs/mlx/mlx/distributed/primitives.h @@ -2,8 +2,10 @@ // Copyright © 2024 Apple Inc.   #pragma once   +#include <atomic> #include "mlx/distributed/distributed.h" #include "mlx/distributed/distributed_impl.h" +#include "mlx/distributed/sealed.h" #include "mlx/primitives.h"   namespace mlx::core::distributed { @@ -65,6 +67,71 @@ }   private: ReduceType reduce_type_; +}; + +/// The sealed all-sum (`all_sum_sealed`, sealed.h): seal, all-gather the two +/// frames, open the peer's, add in rank order. With a streamed codec on a +/// group that can exchange, one task does this piece by piece +/// (sealed_stream.h). `counter_` advances per evaluation; both ranks +/// evaluate the same graph in the same order. +class SealedAllSum : public DistPrimitive { + public: + SealedAllSum(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + void eval_gpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + + const char* name() const override { + return "SealedAllSum"; + } + + private: + void eval_streamed(const array& in, array& out); + + SealCodec codec_; +}; + +/// The sealed reduce-scatter and all-gather (`reduce_scatter_sealed`, +/// `all_gather_sealed`, sealed.h): the all-sum's frames and counters, half +/// the bytes each. Every sealed collective draws its counter from one +/// sequence (`detail::next_sealed_counter`), in evaluation order. +class SealedReduceScatter : public DistPrimitive { + public: + SealedReduceScatter(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + void eval_gpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + + const char* name() const override { + return "SealedReduceScatter"; + } + + private: + SealCodec codec_; +}; + +class SealedAllGather : public DistPrimitive { + public: + SealedAllGather(Stream stream, Group group, SealCodec codec) + : DistPrimitive(stream, group), codec_(codec) {} + + void eval_cpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + void eval_gpu(const std::vector<array>& inputs, std::vector<array>& outputs) + override; + + const char* name() const override { + return "SealedAllGather"; + } + + private: + SealCodec codec_; };   class AllGather : public DistPrimitive {
diff --git ml-explore/mlx/mlx/distributed/sealed.cpp Layr-Labs/mlx/mlx/distributed/sealed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b09c3d53f3c88469698efd1bd6328f7d0df5188 --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/sealed.cpp @@ -0,0 +1,608 @@ +// Copyright © 2026 Darkbloom. + +#ifdef __APPLE__ +#include <dispatch/dispatch.h> +#endif +#include <algorithm> +#include <cstring> +#include <mutex> +#include <stdexcept> +#include <string> + +#include "mlx/allocator.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/distributed/distributed_impl.h" +#include "mlx/distributed/primitives.h" +#include "mlx/distributed/sealed.h" +#include "mlx/distributed/sealed_stream.h" + +namespace mlx::core::distributed { + +namespace { +std::mutex codec_mutex; +std::optional<SealCodec> installed_codec; +// One counter for every sealed collective, advanced per evaluation; both +// ranks evaluate the same graph in the same order. +std::atomic<uint64_t> sealed_counter{0}; +uint64_t next_sealed_counter() { + return sealed_counter++; +} +} // namespace + +void set_seal_codec(SealCodec codec) { + if (codec.seal != nullptr && codec.open != nullptr && + (codec.seal_piece != nullptr || codec.open_piece != nullptr)) { + if (!codec.streamed() || codec.piece_bytes < 4096 || + codec.piece_bytes > (size_t(16) << 20) || codec.piece_bytes % 16 != 0) { + throw std::invalid_argument( + "[set_seal_codec] a streamed codec needs both piece callbacks and " + "piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]"); + } + } + std::lock_guard<std::mutex> lock(codec_mutex); + if (codec.seal == nullptr || codec.open == nullptr) { + installed_codec.reset(); + } else { + installed_codec = codec; + } +} + +std::optional<SealCodec> seal_codec() { + std::lock_guard<std::mutex> lock(codec_mutex); + return installed_codec; +} + +array all_sum_sealed( + const array& x, + std::optional<Group> group_, + StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + if (group.size() != 2) { + throw std::invalid_argument("[all_sum_sealed] needs exactly two ranks"); + } + if (x.dtype() != float32 && x.dtype() != bfloat16 && x.dtype() != float16) { + throw std::invalid_argument( + "[all_sum_sealed] sums float32, bfloat16 or float16 partials only"); + } + auto codec = seal_codec(); + if (!codec.has_value()) { + throw std::runtime_error( + "[all_sum_sealed] no seal codec is installed: a partial never crosses the link in the clear"); + } + auto stream = detail::communication_stream(group, s); + return array( + x.shape(), + x.dtype(), + std::make_shared<SealedAllSum>(stream, group, *codec), + {x}); +} + +namespace { +// [1, T, ...] split on its second axis between two ranks. +void require_rows(const array& x, Group& group, const char* name, bool even) { + if (group.size() != 2) { + throw std::invalid_argument(std::string(name) + " needs exactly two ranks"); + } + if (x.dtype() != float32 && x.dtype() != bfloat16 && x.dtype() != float16) { + throw std::invalid_argument( + std::string(name) + " moves float32, bfloat16 or float16 only"); + } + if (x.ndim() < 2 || x.shape(0) != 1 || x.shape(1) < 1 || + (even && x.shape(1) % 2 != 0)) { + throw std::invalid_argument( + std::string(name) + " needs [1, T, ...]" + + (even ? " with T even" : "")); + } +} +SealCodec require_codec(const char* name) { + auto codec = seal_codec(); + if (!codec.has_value()) { + throw std::runtime_error( + std::string(name) + + " no seal codec is installed: a partial never crosses the link in the clear"); + } + return *codec; +} +} // namespace + +array reduce_scatter_sealed( + const array& x, + std::optional<Group> group_, + StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + require_rows(x, group, "[reduce_scatter_sealed]", true); + auto codec = require_codec("[reduce_scatter_sealed]"); + auto shape = x.shape(); + shape[1] /= 2; + auto stream = detail::communication_stream(group, s); + return array( + std::move(shape), + x.dtype(), + std::make_shared<SealedReduceScatter>(stream, group, codec), + {x}); +} + +array all_gather_sealed( + const array& x, + std::optional<Group> group_, + StreamOrDevice s) { + auto group = group_.has_value() ? group_.value() : distributed::init(); + require_rows(x, group, "[all_gather_sealed]", false); + auto codec = require_codec("[all_gather_sealed]"); + auto shape = x.shape(); + shape[1] *= 2; + auto stream = detail::communication_stream(group, s); + return array( + std::move(shape), + x.dtype(), + std::make_shared<SealedAllGather>(stream, group, codec), + {x}); +} + +namespace { +template <typename T> +void add_span(const T* rank0, const T* rank1, T* out, size_t n) { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast<T>( + static_cast<float>(rank0[i]) + static_cast<float>(rank1[i])); + } +} +template <> +void add_span<float>( + const float* rank0, + const float* rank1, + float* out, + size_t n) { + for (size_t i = 0; i < n; ++i) { + out[i] = rank0[i] + rank1[i]; + } +} +// The same element-wise sum (one rounding, rank 0 + rank 1), split across +// cores for prefill-sized partials; small partials stay on this thread. +template <typename T> +void add_in_rank_order(const T* rank0, const T* rank1, T* out, size_t n) { + constexpr size_t kSpan = size_t(1) << 18; + if (n <= kSpan) { + add_span(rank0, rank1, out, n); + return; + } + size_t spans = (n + kSpan - 1) / kSpan; +#ifdef __APPLE__ + dispatch_apply(spans, DISPATCH_APPLY_AUTO, ^(size_t i) { + size_t begin = i * kSpan; + size_t count = std::min(kSpan, n - begin); + add_span(rank0 + begin, rank1 + begin, out + begin, count); + }); +#else + for (size_t i = 0; i < spans; ++i) { + size_t begin = i * kSpan; + size_t count = std::min(kSpan, n - begin); + add_span(rank0 + begin, rank1 + begin, out + begin, count); + } +#endif +} +} // namespace + +void SealedAllSum::eval_cpu( + const std::vector<array>& inputs, + std::vector<array>& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + if (codec_.streamed() && group().raw_group()->supports_exchange()) { + eval_streamed(in, out); + if (!inputs[0].flags().row_contiguous) { + cpu::get_command_encoder(stream()).add_temporary(in); + } + return; + } + size_t n = in.nbytes(); + size_t frame = n + codec_.overhead; + int sealed_len = detail::frame_extent(frame, "[all_sum_sealed]"); + int gathered_len = detail::frame_extent(2 * frame, "[all_sum_sealed]"); + array sealed({sealed_len}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(frame)); + array gathered({gathered_len}, uint8, nullptr, {}); + gathered.set_data(allocator::malloc(2 * frame)); + array peer(in.shape(), in.dtype(), nullptr, {}); + peer.set_data(allocator::malloc(n)); + + int rank = group().rank(); + uint64_t counter = next_sealed_counter(); + auto codec = codec_; + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(sealed); + encoder.dispatch([codec, + src = in.data<char>(), + dst = sealed.data<char>(), + n, + frame, + counter]() { + if (codec.seal(codec.ctx, src, n, dst, counter) != 0) { + // The gather after this task still runs: never send stale bytes. + std::memset(dst, 0, frame); + throw std::runtime_error( + "[all_sum_sealed] the codec refused to seal a partial"); + } + }); + distributed::detail::all_gather(group(), sealed, gathered, stream()); + encoder.set_input_array(gathered); + encoder.set_output_array(out); + encoder.dispatch([codec, + frames = gathered.data<char>(), + mine = in.data<char>(), + theirs = peer.data<char>(), + dst = out.data<char>(), + n, + frame, + counter, + rank, + dtype = in.dtype()]() { + const char* peer_frame = frames + (rank == 0 ? frame : 0); + if (codec.open(codec.ctx, peer_frame, n, theirs, counter, 1 - rank) != 0) { + throw std::runtime_error( + "[all_sum_sealed] a peer frame did not authenticate: refused"); + } + const char* r0 = rank == 0 ? mine : theirs; + const char* r1 = rank == 0 ? theirs : mine; + switch (dtype) { + case float32: + add_in_rank_order( + reinterpret_cast<const float*>(r0), + reinterpret_cast<const float*>(r1), + reinterpret_cast<float*>(dst), + n / sizeof(float)); + break; + case bfloat16: + add_in_rank_order( + reinterpret_cast<const bfloat16_t*>(r0), + reinterpret_cast<const bfloat16_t*>(r1), + reinterpret_cast<bfloat16_t*>(dst), + n / sizeof(bfloat16_t)); + break; + case float16: + add_in_rank_order( + reinterpret_cast<const float16_t*>(r0), + reinterpret_cast<const float16_t*>(r1), + reinterpret_cast<float16_t*>(dst), + n / sizeof(float16_t)); + break; + default: + throw std::runtime_error("[all_sum_sealed] unsupported dtype"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(gathered); + encoder.add_temporary(peer); + if (!inputs[0].flags().row_contiguous) { + encoder.add_temporary(in); + } +} + +// One CPU-stream task that seals, sends, opens and adds piece by piece +// (sealed_stream.h). Each rank receives only the peer's frame. +void SealedAllSum::eval_streamed(const array& in, array& out) { + detail::PieceLayout layout(in.nbytes(), codec_.piece_bytes); + if (layout.count > 0xFFFF) { + throw std::invalid_argument( + "[all_sum_sealed] a partial needs more than 65,535 sealed pieces"); + } + detail::AddPieceFn add; + switch (in.dtype()) { + case float32: + add = detail::add_piece<float>; + break; + case bfloat16: + add = detail::add_piece<bfloat16_t>; + break; + case float16: + add = detail::add_piece<float16_t>; + break; + default: + throw std::runtime_error("[all_sum_sealed] unsupported dtype"); + } + int frame_len = detail::frame_extent(layout.frame(), "[all_sum_sealed]"); + array sealed({frame_len}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(layout.frame())); + array received({frame_len}, uint8, nullptr, {}); + received.set_data(allocator::malloc(layout.frame())); + + int rank = group().rank(); + uint64_t counter = next_sealed_counter(); + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(out); + encoder.dispatch([codec = codec_, + layout, + counter, + rank, + add, + group = group().raw_group(), + src = in.data<char>(), + dst = out.data<char>(), + mine = sealed.data<char>(), + theirs = received.data<char>()]() { + detail::StreamedSum sum( + codec, layout, counter, rank, src, src, dst, mine, theirs, add); + bool ok = sum.run([&group]( + const char* send, + char* recv, + size_t n, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + group->exchange(send, recv, n, ready, arrived); + }); + if (!ok) { + throw std::runtime_error( + "[all_sum_sealed] a piece did not seal or a peer piece did not " + "authenticate: refused"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(received); +} + +void SealedAllSum::eval_gpu(const std::vector<array>&, std::vector<array>&) { + throw std::runtime_error( + "[SealedAllSum::eval_gpu] has no GPU implementation."); +} + +namespace { + +detail::AddPieceFn add_piece_for(Dtype dtype, const char* name) { + switch (dtype) { + case float32: + return detail::add_piece<float>; + case bfloat16: + return detail::add_piece<bfloat16_t>; + case float16: + return detail::add_piece<float16_t>; + default: + throw std::runtime_error(std::string(name) + " unsupported dtype"); + } +} + +// The streamed half-size exchange both new collectives run: `send` (n bytes) +// sealed and sent, the peer's n bytes opened into `out` and, with `add`, +// `addend` added in rank order. +void run_streamed( + const SealCodec& codec, + Group& group, + Stream stream, + const array& in, + array& out, + size_t n, + const char* send, + const char* addend, + char* dst, + detail::AddPieceFn add, + const char* name) { + detail::PieceLayout layout(n, codec.piece_bytes); + if (layout.count > 0xFFFF) { + throw std::invalid_argument( + std::string(name) + " a frame needs more than 65,535 sealed pieces"); + } + int frame_len = detail::frame_extent(layout.frame(), name); + array sealed({frame_len}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(layout.frame())); + array received({frame_len}, uint8, nullptr, {}); + received.set_data(allocator::malloc(layout.frame())); + int rank = group.rank(); + uint64_t counter = next_sealed_counter(); + auto& encoder = cpu::get_command_encoder(stream); + encoder.set_input_array(in); + encoder.set_output_array(out); + std::string label = name; + encoder.dispatch([codec, + layout, + counter, + rank, + add, + label, + raw = group.raw_group(), + send, + addend, + dst, + mine = sealed.data<char>(), + theirs = received.data<char>()]() { + detail::StreamedSum exchange( + codec, layout, counter, rank, send, addend, dst, mine, theirs, add); + bool ok = exchange.run([&raw]( + const char* sent, + char* recv, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + raw->exchange(sent, recv, bytes, ready, arrived); + }); + if (!ok) { + throw std::runtime_error( + label + + " a piece did not seal or a peer piece did not authenticate: refused"); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(received); +} + +// The same without an exchange: seal `send`, gather both frames, open the +// peer's into `dst` and, with `add`, add `addend` in rank order. +void run_gathered( + const SealCodec& codec, + Group& group, + Stream stream, + const array& in, + array& out, + size_t n, + const char* send, + const char* addend, + char* dst, + detail::AddPieceFn add, + const char* name) { + size_t frame = n + codec.overhead; + int sealed_len = detail::frame_extent(frame, name); + int gathered_len = detail::frame_extent(2 * frame, name); + array sealed({sealed_len}, uint8, nullptr, {}); + sealed.set_data(allocator::malloc(frame)); + array gathered({gathered_len}, uint8, nullptr, {}); + gathered.set_data(allocator::malloc(2 * frame)); + int rank = group.rank(); + uint64_t counter = next_sealed_counter(); + std::string label = name; + auto& encoder = cpu::get_command_encoder(stream); + encoder.set_input_array(in); + encoder.set_output_array(sealed); + encoder.dispatch( + [codec, send, dst = sealed.data<char>(), n, frame, counter, label]() { + if (codec.seal(codec.ctx, send, n, dst, counter) != 0) { + std::memset(dst, 0, frame); + throw std::runtime_error(label + " the codec refused to seal"); + } + }); + distributed::detail::all_gather(group, sealed, gathered, stream); + encoder.set_input_array(gathered); + encoder.set_output_array(out); + encoder.dispatch([codec, + frames = gathered.data<char>(), + addend, + dst, + n, + frame, + counter, + rank, + add, + label]() { + const char* peer_frame = frames + (rank == 0 ? frame : 0); + if (codec.open(codec.ctx, peer_frame, n, dst, counter, 1 - rank) != 0) { + throw std::runtime_error( + label + " a peer frame did not authenticate: refused"); + } + if (add != nullptr) { + add(rank, addend, dst, n); + } + }); + encoder.add_temporary(sealed); + encoder.add_temporary(gathered); +} + +} // namespace + +// Rank r keeps rows [r * T / 2, (r + 1) * T / 2): it sends the peer's half +// of its partial and adds the peer's partial of its own half to its own, in +// rank order (rank 0 + rank 1), as the all-sum does for every element. +void SealedReduceScatter::eval_cpu( + const std::vector<array>& inputs, + std::vector<array>& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + size_t half = out.nbytes(); + int rank = group().rank(); + const char* src = in.data<char>(); + const char* send = src + (rank == 0 ? half : 0); + const char* mine = src + (rank == 0 ? 0 : half); + auto add = add_piece_for(in.dtype(), "[reduce_scatter_sealed]"); + auto group = this->group(); + if (codec_.streamed() && group.raw_group()->supports_exchange()) { + run_streamed( + codec_, + group, + stream(), + in, + out, + half, + send, + mine, + out.data<char>(), + add, + "[reduce_scatter_sealed]"); + } else { + run_gathered( + codec_, + group, + stream(), + in, + out, + half, + send, + mine, + out.data<char>(), + add, + "[reduce_scatter_sealed]"); + } + if (!inputs[0].flags().row_contiguous) { + cpu::get_command_encoder(stream()).add_temporary(in); + } +} + +void SealedReduceScatter::eval_gpu( + const std::vector<array>&, + std::vector<array>&) { + throw std::runtime_error( + "[SealedReduceScatter::eval_gpu] has no GPU implementation."); +} + +// Rank 0's rows then rank 1's: this rank's rows are copied in place and the +// peer's arrive sealed. +void SealedAllGather::eval_cpu( + const std::vector<array>& inputs, + std::vector<array>& outputs) { + auto in = inputs[0].flags().row_contiguous + ? inputs[0] + : contiguous_copy_cpu(inputs[0], stream()); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + size_t n = in.nbytes(); + int rank = group().rank(); + char* own = out.data<char>() + (rank == 0 ? 0 : n); + char* theirs = out.data<char>() + (rank == 0 ? n : 0); + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(out); + encoder.dispatch( + [src = in.data<char>(), own, n]() { std::memcpy(own, src, n); }); + auto group = this->group(); + if (codec_.streamed() && group.raw_group()->supports_exchange()) { + run_streamed( + codec_, + group, + stream(), + in, + out, + n, + in.data<char>(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); + } else { + run_gathered( + codec_, + group, + stream(), + in, + out, + n, + in.data<char>(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); + } + if (!inputs[0].flags().row_contiguous) { + encoder.add_temporary(in); + } +} + +void SealedAllGather::eval_gpu(const std::vector<array>&, std::vector<array>&) { + throw std::runtime_error( + "[SealedAllGather::eval_gpu] has no GPU implementation."); +} + +} // namespace mlx::core::distributed
diff --git ml-explore/mlx/mlx/distributed/sealed.h Layr-Labs/mlx/mlx/distributed/sealed.h new file mode 100644 index 0000000000000000000000000000000000000000..655d8d308b009412cbec75cd0caf1e9881b6700e --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/sealed.h @@ -0,0 +1,120 @@ +// Copyright © 2026 Darkbloom. +// +// A sealed all-sum: the two ranks' partials cross the link only as +// authenticated, encrypted frames made and opened by a codec the embedding +// program registers (Darkbloom: AES-256-GCM with directional keys from its +// keyed data plane). Evaluated on the CPU stream inside the lazy graph, like +// the native all-sum, so the model thread never synchronizes the GPU for it. +// A frame that does not open is refused: the codec reports it and the +// evaluation fails; there is no plaintext fallback. + +#pragma once + +#include <cstddef> +#include <cstdint> +#include <optional> + +#include "mlx/api.h" +#include "mlx/distributed/distributed.h" +#include "mlx/utils.h" + +namespace mlx::core::distributed { + +// seal: plaintext (n bytes) -> frame (n + overhead bytes) for `counter`; +// open: the peer's frame -> plaintext (n bytes) for `counter` from `peer`. +// Both return 0 on success. `counter` advances by one per sealed all-sum, in +// evaluation order, identically on both ranks. +using SealFn = int (*)( + void* ctx, + const void* plaintext, + size_t n, + void* frame, + uint64_t counter); +using OpenFn = int (*)( + void* ctx, + const void* frame, + size_t n, + void* plaintext, + uint64_t counter, + int peer); + +// The streamed frame: piece k holds plaintext +// [k * piece_bytes, min(n, (k + 1) * piece_bytes)) as its ciphertext, then a +// kSealTagBytes tag; the pieces are in order. seal_piece writes +// len + kSealTagBytes bytes; open_piece reads them and writes len bytes. +// Calls for one counter can run at the same time, on any thread, in any +// order; `pieces` and `total` (n) are the same for each piece of a counter. +// Both return 0 on success. +constexpr size_t kSealTagBytes = 16; +using SealPieceFn = int (*)( + void* ctx, + const void* plaintext, + size_t len, + void* sealed, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total); +using OpenPieceFn = int (*)( + void* ctx, + const void* sealed, + size_t len, + void* plaintext, + uint64_t counter, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer); + +struct SealCodec { + SealFn seal = nullptr; + OpenFn open = nullptr; + void* ctx = nullptr; + size_t overhead = 0; + // Optional. A group that can exchange (two-rank JACCL mesh) then streams + // the pieces; other groups use seal and open. + SealPieceFn seal_piece = nullptr; + OpenPieceFn open_piece = nullptr; + size_t piece_bytes = 0; + bool streamed() const { + return seal_piece != nullptr && open_piece != nullptr; + } +}; + +// Installs (or, with a null seal, removes) the process's codec. A sealed +// all-sum without a codec is refused when the graph is built. A streamed +// codec needs piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]. +// +// The counter starts at 0 in each process, is shared by every group and is +// not reset by this call, so a codec must not reuse its keys across +// processes (the counters would repeat). Each sealed primitive keeps a copy +// of the codec it was built with: `ctx` must stay valid until every graph +// built with it has been evaluated or released. +MLX_API void set_seal_codec(SealCodec codec); +MLX_API std::optional<SealCodec> seal_codec(); + +// The sum of two ranks' arrays, crossing the link sealed. Two ranks only; +// float32, bfloat16 and float16; the sum is taken in rank order (rank 0 + +// rank 1) so both ranks hold the same bits. +MLX_API array all_sum_sealed( + const array& x, + std::optional<Group> group = std::nullopt, + StreamOrDevice s = {}); + +// Two ranks, `x` shaped [1, T, ...]. Rank r receives rows +// [r * T / 2, (r + 1) * T / 2) of the sum, added in rank order exactly as +// all_sum_sealed adds them (T even): each rank sends only the peer's half. +MLX_API array reduce_scatter_sealed( + const array& x, + std::optional<Group> group = std::nullopt, + StreamOrDevice s = {}); + +// Two ranks, `x` shaped [1, T, ...] (this rank's rows): [1, 2T, ...], rank +// 0's rows then rank 1's, each rank sending only its own. A copy: every +// element keeps its bits. +MLX_API array all_gather_sealed( + const array& x, + std::optional<Group> group = std::nullopt, + StreamOrDevice s = {}); + +} // namespace mlx::core::distributed
diff --git ml-explore/mlx/mlx/distributed/sealed_stream.h Layr-Labs/mlx/mlx/distributed/sealed_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..445613a81cae18f805990a476da207a968aab79f --- /dev/null +++ Layr-Labs/mlx/mlx/distributed/sealed_stream.h @@ -0,0 +1,336 @@ +// Copyright © 2026 Darkbloom. +// +// The streamed sealed sum. Worker threads seal the pieces in order; the +// exchange sends each frame when its pieces are sealed; each peer piece is +// opened and added when its bytes land. Only the head and the tail of the +// transfer wait for crypto. + +#pragma once + +#ifdef __APPLE__ +#include <dispatch/dispatch.h> +#include <pthread.h> +#include <pthread/qos.h> +#endif + +#include <algorithm> +#include <atomic> +#include <cstdlib> +#include <cstring> +#include <functional> +#include <limits> +#include <memory> +#include <stdexcept> +#include <string> + +#include "mlx/distributed/sealed.h" + +namespace mlx::core::distributed::detail { + +using ReadyFn = std::function<bool(size_t)>; +using ArrivedFn = std::function<void(size_t)>; +// exchange(send, recv, bytes, ready, arrived): see GroupImpl::exchange. +using ExchangeFn = std::function< + void(const char*, char*, size_t, const ReadyFn&, const ArrivedFn&)>; + +// The length of a uint8 frame array of `bytes` bytes. Array shapes are int, +// so a longer frame is refused instead of wrapping to a wrong length. +inline int frame_extent(size_t bytes, const char* name) { + if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) { + throw std::invalid_argument( + std::string(name) + " a sealed frame is longer than 2^31 - 1 bytes"); + } + return static_cast<int>(bytes); +} + +// The streamed frame of an n-byte partial. +struct PieceLayout { + size_t bytes; + size_t piece; + size_t count; + PieceLayout(size_t n, size_t piece_bytes) + : bytes(n), + piece(piece_bytes), + count(std::max<size_t>(1, (n + piece_bytes - 1) / piece_bytes)) {} + size_t plain(size_t k) const { + return k * piece; + } + size_t length(size_t k) const { + return std::min(piece, bytes - k * piece); + } + size_t sealed(size_t k) const { + return k * (piece + kSealTagBytes); + } + size_t sealed_end(size_t k) const { + return sealed(k) + length(k) + kSealTagBytes; + } + size_t frame() const { + return bytes + count * kSealTagBytes; + } +}; + +// `out` holds the peer's addend. It becomes rank 0's addend + rank 1's, both +// widened to float and rounded once, as the gathered path adds them. +template <typename T> +void add_peer_in_rank_order( + int rank, + const T* __restrict mine, + T* __restrict out, + size_t n) { + if (rank == 0) { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast<T>( + static_cast<float>(mine[i]) + static_cast<float>(out[i])); + } + } else { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast<T>( + static_cast<float>(out[i]) + static_cast<float>(mine[i])); + } + } +} + +using AddPieceFn = void (*)(int rank, const char* mine, char* out, size_t len); + +template <typename T> +void add_piece(int rank, const char* mine, char* out, size_t len) { + add_peer_in_rank_order( + rank, + reinterpret_cast<const T*>(mine), + reinterpret_cast<T*>(out), + len / sizeof(T)); +} + +// MLX_SEALED_QOS=0 keeps the caller's QoS (as the gathered path does). +inline bool raise_qos() { + static const bool on = [] { + const char* value = std::getenv("MLX_SEALED_QOS"); + return value == nullptr || std::strcmp(value, "0") != 0; + }(); + return on; +} + +// Threads that seal at the same time (MLX_SEALED_SEAL_LANES, 1..64). Eight +// stay ahead of the wire and leave cores to the GPU driver and the opens. +inline size_t seal_lanes() { + static const size_t lanes = [] { + const char* value = std::getenv("MLX_SEALED_SEAL_LANES"); + long parsed = value ? std::strtol(value, nullptr, 10) : 0; + return parsed >= 1 && parsed <= 64 ? size_t(parsed) : size_t(8); + }(); + return lanes; +} + +// One streamed sealed exchange, run on the calling thread (a CPU-stream +// task): `send` is sealed and sent piece by piece; each peer piece is opened +// into `out` and, with `add`, `addend` (this rank's own values for the same +// elements) is added to it in rank order. The all-sum sends and adds its +// whole partial; the reduce-scatter sends the peer's half and adds its own; +// the all-gather sends its own half and only opens. +class StreamedSum { + public: + StreamedSum( + const SealCodec& codec, + const PieceLayout& layout, + uint64_t counter, + int rank, + const char* send, + const char* addend, + char* out, + char* sealed, + char* received, + AddPieceFn add) + : codec_(codec), + layout_(layout), + counter_(counter), + rank_(rank), + mine_(send), + addend_(addend), + out_(out), + sealed_(sealed), + received_(received), + add_(add), + ready_(std::make_unique<std::atomic<bool>[]>(layout.count)) {} + + // False when a piece did not seal or a peer piece did not open. No worker + // runs after this returns or throws. + bool run(const ExchangeFn& exchange) { + if (layout_.count == 1) { + // One piece (decode): no worker hand-off. + seal(0); + exchange( + sealed_, + received_, + layout_.frame(), + [](size_t) { return true; }, + [this](size_t end) { + if (end == layout_.frame()) { + open_and_add(0); + } + }); + return !failed_.load(); + } +#ifdef __APPLE__ + QosOverride boost; + Workers workers; + StreamedSum* self = this; + size_t lanes = std::min(layout_.count, seal_lanes()); + for (size_t i = 0; i < lanes; ++i) { + workers.async(^{ + self->seal_in_order(); + }); + } +#else + // The portable path uses no background workers or platform QoS APIs. + for (size_t k = 0; k < layout_.count; ++k) { + seal(k); + } +#endif + size_t sealed_prefix = 0; + size_t dispatched = 0; + exchange( + sealed_, + received_, + layout_.frame(), + [&](size_t end) { + while (sealed_prefix < layout_.count && + ready_[sealed_prefix].load(std::memory_order_acquire)) { + ++sealed_prefix; + } + return sealed_prefix == layout_.count || + layout_.sealed(sealed_prefix) >= end; + }, + [&](size_t end) { + for (; dispatched < layout_.count && + layout_.sealed_end(dispatched) <= end; + ++dispatched) { + size_t k = dispatched; +#ifdef __APPLE__ + workers.async(^{ + self->open_and_add(k); + }); +#else + open_and_add(k); +#endif + } + }); +#ifdef __APPLE__ + workers.wait(); +#endif + return !failed_.load(); + } + + private: +#ifdef __APPLE__ + // Waits for every block before the frames and `out` can be released. + class Workers { + public: + Workers() + : group_(dispatch_group_create()), + queue_(dispatch_get_global_queue( + raise_qos() ? QOS_CLASS_USER_INTERACTIVE : qos_class_self(), + 0)) {} + Workers(const Workers&) = delete; + Workers& operator=(const Workers&) = delete; + ~Workers() { + wait(); + dispatch_release(group_); + } + void async(dispatch_block_t block) { + dispatch_group_async(group_, queue_, block); + } + void wait() { + dispatch_group_wait(group_, DISPATCH_TIME_FOREVER); + } + + private: + dispatch_group_t group_; + dispatch_queue_t queue_; + }; + + // The polling thread runs at the workers' QoS while they run. + class QosOverride { + public: + QosOverride() + : token_( + raise_qos() ? pthread_override_qos_class_start_np( + pthread_self(), + QOS_CLASS_USER_INTERACTIVE, + 0) + : nullptr) {} + QosOverride(const QosOverride&) = delete; + QosOverride& operator=(const QosOverride&) = delete; + ~QosOverride() { + if (token_ != nullptr) { + pthread_override_qos_class_end_np(token_); + } + } + + private: + pthread_override_t token_; + }; + +#endif + + void seal_in_order() { + for (size_t k; (k = next_seal_.fetch_add(1)) < layout_.count;) { + seal(k); + } + } + + void seal(size_t k) { + char* dst = sealed_ + layout_.sealed(k); + size_t len = layout_.length(k); + if (codec_.seal_piece( + codec_.ctx, + mine_ + layout_.plain(k), + len, + dst, + counter_, + static_cast<uint32_t>(k), + static_cast<uint32_t>(layout_.count), + layout_.bytes) != 0) { + // Never send stale bytes. The peer refuses the zero piece. + std::memset(dst, 0, len + kSealTagBytes); + failed_.store(true); + } + ready_[k].store(true, std::memory_order_release); + } + + void open_and_add(size_t k) { + char* dst = out_ + layout_.plain(k); + size_t len = layout_.length(k); + if (codec_.open_piece( + codec_.ctx, + received_ + layout_.sealed(k), + len, + dst, + counter_, + static_cast<uint32_t>(k), + static_cast<uint32_t>(layout_.count), + layout_.bytes, + 1 - rank_) != 0) { + failed_.store(true); + return; + } + if (add_ != nullptr) { + add_(rank_, addend_ + layout_.plain(k), dst, len); + } + } + + const SealCodec codec_; + const PieceLayout layout_; + const uint64_t counter_; + const int rank_; + const char* const mine_; + const char* const addend_; + char* const out_; + char* const sealed_; + char* const received_; + const AddPieceFn add_; + std::unique_ptr<std::atomic<bool>[]> ready_; + std::atomic<size_t> next_seal_{0}; + std::atomic<bool> failed_{false}; +}; + +} // namespace mlx::core::distributed::detail
diff --git ml-explore/mlx/tests/distributed_sealed_stream_tests.cpp Layr-Labs/mlx/tests/distributed_sealed_stream_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f1121f9d80abd8346a9c81281817b3c8a1dcc4d --- /dev/null +++ Layr-Labs/mlx/tests/distributed_sealed_stream_tests.cpp @@ -0,0 +1,265 @@ +// Copyright © 2026 Darkbloom. + +#include <algorithm> +#include <atomic> +#include <chrono> +#include <cstring> +#include <limits> +#include <stdexcept> +#include <thread> +#include <vector> + +#include "doctest/doctest.h" +#include "mlx/distributed/sealed_stream.h" + +namespace { +namespace sealed = mlx::core::distributed; +namespace detail = mlx::core::distributed::detail; + +// A deterministic test codec, not encryption. Tags bind all callback fields. +struct Codec { + int rank; + size_t total; + int fail_seal = -1; + std::atomic<int> active{0}; + std::atomic<int> seals{0}; + std::atomic<int> opens{0}; + std::atomic<bool> bad_identity{false}; + std::atomic<bool> changed_thread{false}; + const std::thread::id caller = std::this_thread::get_id(); + static constexpr uint64_t counter = 19; + + bool identity( + size_t bytes, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t whole) { + const size_t expected_pieces = std::max(size_t(1), (total + 4095) / 4096); + bool valid = count == counter && whole == total && + pieces == expected_pieces && piece < expected_pieces && + size_t(piece) * 4096 <= total; + valid = + valid && bytes == std::min(size_t(4096), total - size_t(piece) * 4096); + if (!valid) + bad_identity = true; + if (caller != std::this_thread::get_id()) + changed_thread = true; + return valid; + } + + static unsigned char tag( + uint64_t counter, + int rank, + uint32_t piece, + uint32_t pieces, + size_t total, + size_t index) { + return static_cast<unsigned char>( + counter + rank + piece + pieces + total + index); + } + + static int seal( + void* context, + const void* input, + size_t bytes, + void* output, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t total) { + auto& self = *static_cast<Codec*>(context); + ++self.active; + ++self.seals; + if (!self.identity(bytes, count, piece, pieces, total) || + int(piece) == self.fail_seal) { + --self.active; + return 1; + } + auto in = static_cast<const unsigned char*>(input); + auto out = static_cast<unsigned char*>(output); + for (size_t i = 0; i < bytes; ++i) + out[i] = in[i] ^ (self.rank + 41); + for (size_t i = 0; i < sealed::kSealTagBytes; ++i) + out[bytes + i] = tag(count, self.rank, piece, pieces, total, i); + --self.active; + return 0; + } + + static int open( + void* context, + const void* input, + size_t bytes, + void* output, + uint64_t count, + uint32_t piece, + uint32_t pieces, + size_t total, + int peer) { + auto& self = *static_cast<Codec*>(context); + ++self.active; + ++self.opens; + auto in = static_cast<const unsigned char*>(input); + auto out = static_cast<unsigned char*>(output); + bool valid = self.identity(bytes, count, piece, pieces, total) && + peer == 1 - self.rank; + for (size_t i = 0; i < sealed::kSealTagBytes; ++i) + valid &= in[bytes + i] == tag(count, peer, piece, pieces, total, i); + if (valid) + for (size_t i = 0; i < bytes; ++i) + out[i] = in[i] ^ (peer + 41); + --self.active; + return valid ? 0 : 1; + } + + sealed::SealCodec value() { + sealed::SealCodec result; + result.ctx = this; + result.seal_piece = seal; + result.open_piece = open; + result.piece_bytes = 4096; + return result; + } +}; + +struct Fixture { + Codec local; + Codec peer; + detail::PieceLayout layout; + std::vector<float> send, addend, remote, output; + std::vector<char> sent_frame, received_frame, peer_frame; + + Fixture(int rank, size_t count) + : local{rank, count * sizeof(float)}, + peer{1 - rank, count * sizeof(float)}, + layout(count * sizeof(float), 4096), + send(std::max(size_t(1), count)), + addend(std::max(size_t(1), count)), + remote(std::max(size_t(1), count)), + output(std::max(size_t(1), count), -100), + sent_frame(layout.frame(), char(0x5a)), + received_frame(layout.frame()), + peer_frame(layout.frame()) { + for (size_t i = 0; i < count; ++i) { + send[i] = float(i % 31) / 8; + addend[i] = float(i % 17) / 4; + remote[i] = float(i % 13) / 2; + } + for (size_t k = 0; k < layout.count; ++k) + Codec::seal( + &peer, + reinterpret_cast<const char*>(remote.data()) + layout.plain(k), + layout.length(k), + peer_frame.data() + layout.sealed(k), + Codec::counter, + uint32_t(k), + uint32_t(layout.count), + layout.bytes); + } + + bool run(bool add, bool throw_exchange = false) { + detail::StreamedSum sum( + local.value(), + layout, + Codec::counter, + local.rank, + reinterpret_cast<const char*>(send.data()), + reinterpret_cast<const char*>(addend.data()), + reinterpret_cast<char*>(output.data()), + sent_frame.data(), + received_frame.data(), + add ? detail::add_piece<float> : nullptr); + return sum.run([&](const char*, + char* received, + size_t bytes, + const detail::ReadyFn& ready, + const detail::ArrivedFn& arrived) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!ready(bytes)) { + if (std::chrono::steady_clock::now() >= deadline) + throw std::runtime_error("test readiness timeout"); + std::this_thread::yield(); + } + std::memcpy(received, peer_frame.data(), bytes); + for (size_t k = 0; k < layout.count; ++k) { + arrived(layout.sealed_end(k) - 1); + CHECK(local.opens <= int(k)); + arrived(layout.sealed_end(k)); + if (throw_exchange) + throw std::runtime_error("test exchange failure"); + } + }); + } +}; +} // namespace + +TEST_CASE("sealed pieces preserve exact rank sum and gathered bytes") { + for (int rank : {0, 1}) { + for (size_t count : {size_t(0), size_t(17), size_t(4097)}) { + for (bool add : {false, true}) { + Fixture fixture(rank, count); + CHECK(fixture.run(add)); + std::vector<float> expected(count); + for (size_t i = 0; i < count; ++i) + expected[i] = !add ? fixture.remote[i] + : rank == 0 ? fixture.addend[i] + fixture.remote[i] + : fixture.remote[i] + fixture.addend[i]; + if (count != 0) + CHECK( + std::memcmp( + expected.data(), + fixture.output.data(), + count * sizeof(float)) == 0); + CHECK(fixture.local.active == 0); + CHECK(fixture.local.seals == fixture.layout.count); + CHECK(fixture.local.opens == fixture.layout.count); + CHECK_FALSE(fixture.local.bad_identity); +#ifndef __APPLE__ + CHECK_FALSE(fixture.local.changed_thread); +#endif + } + } + } +} + +TEST_CASE("sealed pieces refuse changed peer tags and zero failed seals") { + Fixture tampered(0, 4097); + tampered.peer_frame[tampered.layout.sealed_end(1) - 1] ^= 1; + CHECK_FALSE(tampered.run(true)); + CHECK(tampered.local.active == 0); + for (size_t i = tampered.layout.plain(1) / sizeof(float); i < + (tampered.layout.plain(1) + tampered.layout.length(1)) / sizeof(float); + ++i) + CHECK(tampered.output[i] == -100); + Fixture failed(1, 4097); + failed.local.fail_seal = 1; + CHECK_FALSE(failed.run(true)); + CHECK(failed.local.active == 0); + for (size_t i = failed.layout.sealed(1); i < failed.layout.sealed_end(1); ++i) + CHECK(failed.sent_frame[i] == 0); +} + +TEST_CASE("sealed exchange errors leave no callback owner running") { + Fixture fixture(0, 4097); + CHECK_THROWS_WITH(fixture.run(true, true), "test exchange failure"); + CHECK(fixture.local.active == 0); + CHECK(fixture.local.seals == fixture.layout.count); + CHECK(fixture.local.opens == 1); +} + +TEST_CASE("sealed frames longer than an int array shape are refused") { + const size_t longest = std::numeric_limits<int>::max(); + CHECK(detail::frame_extent(0, "[test]") == 0); + CHECK( + detail::frame_extent(longest, "[test]") == + std::numeric_limits<int>::max()); + CHECK_THROWS_WITH_AS( + detail::frame_extent(longest + 1, "[test]"), + "[test] a sealed frame is longer than 2^31 - 1 bytes", + std::invalid_argument); + // A float32 partial of 1 GiB gathers two frames of more than 1 GiB. + CHECK_THROWS_AS( + detail::frame_extent(2 * ((size_t(1) << 30) + 16), "[test]"), + std::invalid_argument); +}

An ordinary fast-synchronization GPU fence wait follows both pending command passes and earlier kernels in the current concurrent encoder. The in-pass buffer barrier matches the existing fenced-input consumer path. Without it, a spinning wait can run before a GPU producer needed by the CPU work it awaits. Arithmetic and command-buffer limits do not change. A standalone bounded test checks exact GPU-to-CPU-to-GPU chains, shared side roots, chains where two GPU streams feed the CPU, and request-array retirement at several buffer sizes. Fork Tests executes the three CTest processes on its Metal runner and rejects a missing test registration. This component coverage does not establish an installed RDMA model fix.

diff --git ml-explore/mlx/docs/src/usage/using_streams.rst Layr-Labs/mlx/docs/src/usage/using_streams.rst index 058bc59dea6e99673a1bd0b4f5d62c7bc8e34097..a4211c55b1b36d00db7abc82c257622834caad95 100644 --- ml-explore/mlx/docs/src/usage/using_streams.rst +++ Layr-Labs/mlx/docs/src/usage/using_streams.rst @@ -16,3 +16,26 @@ ``mx.default_stream(mx.default_device())``. The ``stream`` kwarg can also be a :obj:`Device` (e.g. ``stream=my_device``) in which case the operation is run on the default stream of the provided device ``mx.default_stream(my_device)``. + +Cross-device fence ordering +--------------------------- + +With fast Metal synchronization, a GPU consumer can wait for work on a CPU +stream. Its wait must follow both earlier command passes and earlier kernels +in the current concurrent pass. The CPU work can depend on those GPU kernels. +``Fence::wait`` therefore inserts both dependencies before the GPU wait. + +A GPU stream never spins on another GPU stream. The fast wait is a kernel that +spins until its producer's timestamp arrives, and Metal does not guarantee that +a second command queue runs while a pass of the first one spins: the producing +queue can starve and both stop. When an evaluation's graph spans two GPU +streams, a consumer on one waits for the other on a shared event, and so does a +GPU stream waiting for CPU work that can itself wait for another GPU stream. +The other CPU-to-GPU and GPU-to-CPU waits keep the fast path. + +The standalone ``metal_fence_chain`` test checks exact GPU-to-CPU-to-GPU chains +with shared side roots, chains where two GPU streams feed the CPU, and +request-array retirement. CTest runs separate +processes with fast synchronization and several command-buffer sizes, with a +60-second timeout per process. This component test does not qualify distributed +collective order, a transport, or an installed model service.
diff --git ml-explore/mlx/mlx/backend/metal/fence.cpp Layr-Labs/mlx/mlx/backend/metal/fence.cpp index 819e2bb1b2679c9d9fb417ba8a86dccd9def00de..b6f86e5fce2ad7e16c148e5cbe2bcbac1f28776a 100644 --- ml-explore/mlx/mlx/backend/metal/fence.cpp +++ Layr-Labs/mlx/mlx/backend/metal/fence.cpp @@ -4,30 +4,38 @@ #include <optional>   #include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/fenced_input.h" +#include "mlx/fast_primitives.h" #include "mlx/scheduler.h" #include "mlx/utils.h"   namespace mlx::core {   struct FenceImpl { - FenceImpl(Stream stream) { + FenceImpl(Stream stream, bool allow_fast = true) + : cpu_stream(stream.device == Device::cpu) { auto d = metal::device(stream.device).mtl_device(); if (!d->supportsFamily(MTL::GPUFamilyMetal3)) { use_fast = false; } else if (__builtin_available(macOS 15, iOS 18, *)) { - use_fast = env::metal_fast_synch(); + use_fast = allow_fast && env::metal_fast_synch(); }   if (!use_fast) { event = std::make_unique<Event>(stream); } else { - fence.emplace(allocator::malloc(sizeof(uint32_t))); + // The timestamp, then the fence_update_coherent arrival count. + fence.emplace(allocator::malloc(2 * sizeof(uint32_t))); cpu_value()[0] = 0; + cpu_value()[1] = 0; } }   bool use_fast{false}; + bool cpu_stream; uint32_t count{0}; + // Threadgroups that fence_update_coherent counted in (mod 2^32). + uint32_t arrivals{0}; std::optional<allocator::Data> fence; std::unique_ptr<Event> event;   @@ -40,8 +48,55 @@ return static_cast<std::atomic_uint*>(buffer()->contents()); } };   +namespace { + +std::vector<metal::FencedInput>& given_waits() { + static thread_local std::vector<metal::FencedInput> waits; + return waits; +} + +void encode_wait( + Stream stream, + const array& x, + const std::shared_ptr<void>& fence, + uint32_t value) { + auto& f = *static_cast<FenceImpl*>(fence.get()); + auto& d = metal::device(stream.device); + auto& compute_encoder = metal::get_command_encoder(stream); + + // Register outputs to ensure that no kernels which depends on the + // output starts before this one is done + compute_encoder.register_output_array(x); + // The spin must not start ahead of GPU work encoded before it: without + // hazard tracking Metal may run this pass before an earlier pass still in + // flight, and when that pass is what the awaited CPU work depends on (a + // GPU -> CPU -> GPU chain, e.g. a CPU-stream collective) the GPU spins + // forever. Waiting on every pending pass costs nothing here: the CPU work + // this spin waits for already follows them. + compute_encoder.wait_for_all_pending(); + // Order the spin after earlier GPU producers in this concurrent pass too. + compute_encoder.barrier(); + + auto kernel = d.get_kernel("fence_wait"); + MTL::Size kernel_dims = MTL::Size(1, 1, 1); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_buffer(f.buffer(), 0); + compute_encoder.set_bytes(value, 1); + compute_encoder.dispatch_threads(kernel_dims, kernel_dims); + + // The fence buffer must outlive the pass that spins on it. + compute_encoder.retain_until_completed(fence); +} + +} // namespace + Fence::Fence(Stream stream) { fence_ = std::make_shared<FenceImpl>(stream); +} + +Fence::Fence(Stream stream, bool fast) { + fence_ = std::make_shared<FenceImpl>(stream, fast); }   void Fence::wait(Stream stream, const array& x, uint32_t value) { @@ -63,26 +118,7 @@ }); return; }   - auto& d = metal::device(stream.device); - auto& compute_encoder = metal::get_command_encoder(stream); - - compute_encoder.end_encoding(); - - // Register outputs to ensure that no kernels which depends on the - // output starts before this one is done - compute_encoder.register_output_array(x); - - auto kernel = d.get_kernel("fence_wait"); - MTL::Size kernel_dims = MTL::Size(1, 1, 1); - compute_encoder.set_compute_pipeline_state(kernel); - - compute_encoder.set_buffer(f.buffer(), 0); - compute_encoder.set_bytes(value, 1); - compute_encoder.dispatch_threads(kernel_dims, kernel_dims); - compute_encoder.end_encoding(true); - - compute_encoder.get_command_buffer()->addCompletedHandler( - [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); + encode_wait(stream, x, fence_, value); }   uint32_t Fence::update(Stream stream, const array& x, bool cross_device) { @@ -106,6 +142,36 @@ auto& d = metal::device(stream.device); auto& compute_encoder = metal::get_command_encoder(stream);   + if (cross_device && env::metal_fused_fence_update()) { + uint32_t words = (x.data_size() * x.itemsize() + sizeof(uint32_t) - 1) / + sizeof(uint32_t); + constexpr uint32_t threads = 1024; + constexpr uint32_t words_per_group = threads * 8; + uint32_t groups = + std::max<uint32_t>(1, (words + words_per_group - 1) / words_per_group); + uint32_t target = 0; + if (groups > 1) { + f.arrivals += groups; + target = f.arrivals; + } + auto kernel = d.get_kernel("fence_update_coherent"); + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(x, 0); + compute_encoder.set_bytes(words, 1); + auto buf = f.buffer(); + compute_encoder.set_buffer(buf, 2); + compute_encoder.set_bytes(f.count, 3); + compute_encoder.set_buffer(buf, 4, sizeof(uint32_t)); + compute_encoder.set_bytes(target, 5); + // After every earlier kernel, as fence_update. This also keeps two + // updates of this fence from overlapping, which `arrivals` requires. + compute_encoder.barrier(); + compute_encoder.dispatch_threadgroups( + MTL::Size(groups, 1, 1), MTL::Size(threads, 1, 1)); + compute_encoder.retain_until_completed(fence_); + return f.count; + } + // Launch input visibility kernels if (cross_device) { auto kernel = d.get_kernel("input_coherent"); @@ -131,9 +197,54 @@ compute_encoder.set_buffer(f.buffer(), 0); compute_encoder.set_bytes(f.count, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims);   - compute_encoder.get_command_buffer()->addCompletedHandler( - [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); + // The fence buffer must outlive the pass that writes it. + compute_encoder.retain_until_completed(fence_); return f.count; } + +bool Fence::wait_in_consumer( + Stream stream, + const array& consumer, + int input, + uint32_t value) { + auto& f = *static_cast<FenceImpl*>(fence_.get()); + if (!env::metal_fenced_inputs() || !f.use_fast || !f.cpu_stream || + stream.device != Device::gpu) { + return false; + } + auto kernel = dynamic_cast<const fast::CustomKernel*>(&consumer.primitive()); + if (!kernel || !kernel->fenced_input(input)) { + return false; + } + given_waits().push_back({&consumer.primitive(), input, fence_, value}); + return true; +} + +namespace metal { + +std::vector<FencedInput> take_fenced_inputs(const Primitive* consumer) { + auto& waits = given_waits(); + std::vector<FencedInput> taken; + for (auto& w : waits) { + if (w.consumer == consumer) { + taken.push_back(std::move(w)); + } + } + waits.clear(); + return taken; +} + +void bind_fenced_input(CommandEncoder& enc, const FencedInput& w, int index) { + auto& f = *static_cast<FenceImpl*>(w.fence.get()); + enc.set_buffer(f.buffer(), index); + enc.set_bytes(w.count, index + 1); + enc.retain_until_completed(w.fence); +} + +void encode_fence_wait(Stream stream, const array& x, const FencedInput& w) { + encode_wait(stream, x, w.fence, w.count); +} + +} // namespace metal   } // namespace mlx::core
diff --git ml-explore/mlx/tests/metal_fence_chain.cpp Layr-Labs/mlx/tests/metal_fence_chain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c568ef2e573fdfca6e9e0f89f5d0f18b27b7d03 --- /dev/null +++ Layr-Labs/mlx/tests/metal_fence_chain.cpp @@ -0,0 +1,148 @@ +// Copyright © 2026 Eigen Labs Inc. +#include <cstdlib> +#include <iostream> +#include <stdexcept> +#include <vector> + +#include "mlx/memory.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +// Standalone so the caller can enforce a timeout if a fence stops progress. +int main(int argc, char** argv) { + try { + const bool cpu_only = argc == 2 && std::string(argv[1]) == "--cpu"; + if (argc > 1 && !cpu_only) { + throw std::invalid_argument("only --cpu is supported"); + } + if (!cpu_only && !gpu::is_available()) { + throw std::runtime_error("Metal is required"); + } + auto producer = new_stream(cpu_only ? Device::cpu : Device::gpu); + auto host = new_stream(Device::cpu); + constexpr int layers = 96; + constexpr int repeats = 3; + size_t comparisons = 0; + for (int width : {1, 2, 3, 4, 8}) { + for (int repeat = 0; repeat < repeats; ++repeat) { + { + auto x = zeros({width, 5120}, float32, producer); + std::vector<array> roots; + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + auto reduced = add(partial, array(2.0f), host); + x = add(reduced, array(3.0f), producer); + // Independent roots share GPU producers with the CPU chain. + if (layer % 3 == 0) { + roots.push_back(add(partial, array(17.0f), producer)); + } + } + roots.insert(roots.begin(), x); + eval(roots); + synchronize(producer); + synchronize(host); + for (size_t root = 0; root < roots.size(); ++root) { + float expected = + root == 0 ? layers * 6.0f : (root - 1) * 3 * 6.0f + 18.0f; + const float* values = roots[root].data<float>(); + for (size_t i = 0; i < roots[root].size(); ++i) { + if (values[i] != expected) { + throw std::runtime_error("exact chain/side-root mismatch"); + } + ++comparisons; + } + } + } + synchronize(producer); + synchronize(host); + clear_cache(); + if (get_active_memory() != 0) { + throw std::runtime_error("request arrays remain after checked drain"); + } + std::cout << "{\"event\":\"case\",\"width\":" << width + << ",\"repeat\":" << repeat << ",\"layers\":" << layers + << ",\"logical_active_bytes\":0}" << std::endl; + } + } + // A second GPU stream in the same chain: each layer's partial is read by + // the CPU and by another GPU stream, and the producer stream reads both + // results back. The producer waits for the other GPU stream on an event + // (a spinning wait there could starve that stream's queue). + if (!cpu_only) { + auto side = new_stream(Device::gpu); + for (int width : {1, 2, 4}) { + { + auto x = zeros({width, 5120}, float32, producer); + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + auto reduced = add(partial, array(2.0f), host); + auto gate = add(partial, array(4.0f), side); + // (x + 3) + (x + 5) - (x + 5) = x + 3, exact in float32. + x = subtract( + add(reduced, gate, producer), + add(x, array(5.0f), producer), + producer); + } + eval(x); + synchronize(producer); + synchronize(side); + synchronize(host); + const float* values = x.data<float>(); + for (size_t i = 0; i < x.size(); ++i) { + if (values[i] != layers * 3.0f) { + throw std::runtime_error("exact two-GPU-stream chain mismatch"); + } + ++comparisons; + } + } + synchronize(producer); + synchronize(side); + synchronize(host); + std::cout << "{\"event\":\"case\",\"streams\":\"two-gpu\",\"width\":" + << width << ",\"layers\":" << layers << "}" << std::endl; + } + // Both GPU streams feed the CPU in the same chain, so no GPU stream may + // spin on the CPU work: the producer waits for the CPU result on an + // event of the CPU stream, and the CPU stream waits for both. + for (int width : {1, 2, 4}) { + { + auto x = zeros({width, 5120}, float32, producer); + for (int layer = 0; layer < layers; ++layer) { + auto partial = add(x, array(1.0f), producer); + // (x - x) + 2 = 2, exact in float32. + auto gate = add(subtract(x, x, side), array(2.0f), side); + auto reduced = add(partial, gate, host); + x = add(reduced, array(3.0f), producer); + } + eval(x); + synchronize(producer); + synchronize(side); + synchronize(host); + const float* values = x.data<float>(); + for (size_t i = 0; i < x.size(); ++i) { + if (values[i] != layers * 6.0f) { + throw std::runtime_error("exact two-GPU-to-CPU chain mismatch"); + } + ++comparisons; + } + } + synchronize(producer); + synchronize(side); + synchronize(host); + std::cout << "{\"event\":\"case\",\"streams\":\"two-to-cpu\",\"width\":" + << width << ",\"layers\":" << layers << "}" << std::endl; + } + } + synchronize(producer); + synchronize(host); + clear_streams(); + std::cout << "{\"event\":\"passed\",\"cases\":" << (cpu_only ? 15 : 21) + << ",\"comparisons\":" << comparisons << ",\"device\":\"" + << (cpu_only ? "cpu" : "gpu") << "\"}" << std::endl; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << std::endl; + return 1; + } +}

With fast synch (MLX_METAL_FAST_SYNCH=1) a fence wait on the GPU is a one-thread kernel that spins until the producer’s timestamp arrives. That is safe when the producer is a CPU stream (a thread always progresses), but not when it is another GPU stream: Metal does not promise that a second command queue runs while a pass of the first one spins, so the producing queue can starve and both stop. An eval whose graph spans two GPU streams therefore waits for the other GPU stream on a shared event (the non-fast path), while CPU <-> GPU waits keep the fast path. An array read both by the CPU and by another GPU stream updates both fences, the fast fence first: its cross-device update can move the array (CUDA moves it to unified memory), and the event must be recorded after the move. MLX_EAGER_FENCE_COMMIT commits after both updates. Synchronization only: results do not change.

diff --git ml-explore/mlx/mlx/backend/cuda/fence.cpp Layr-Labs/mlx/mlx/backend/cuda/fence.cpp index 1b29044df66de7401c980cf91d0bb09a2656816b..bea4022bc50cb21dde34783f8c1b0e1e079b88b7 100644 --- ml-explore/mlx/mlx/backend/cuda/fence.cpp +++ Layr-Labs/mlx/mlx/backend/cuda/fence.cpp @@ -25,6 +25,8 @@ Fence::Fence(Stream s) { fence_ = std::make_shared<FenceImpl>(0, s); }   +Fence::Fence(Stream s, bool) : Fence(s) {} + void Fence::wait(Stream s, const array&, uint32_t value) { auto& f = cast<FenceImpl>(); if (value == 0) { @@ -39,6 +41,10 @@ auto& event = f.cpu_event; event.set_value(value); event.wait(); } +} + +bool Fence::wait_in_consumer(Stream, const array&, int, uint32_t) { + return false; }   uint32_t Fence::update(Stream s, const array& a, bool cross_device) {
diff --git ml-explore/mlx/mlx/backend/no_gpu/fence.cpp Layr-Labs/mlx/mlx/backend/no_gpu/fence.cpp index 2e027032d93131620fe207a8728ac5cf38f0bcee..566f575e6c53ac513f73d23fb3a38e22dc655841 100644 --- ml-explore/mlx/mlx/backend/no_gpu/fence.cpp +++ Layr-Labs/mlx/mlx/backend/no_gpu/fence.cpp @@ -16,10 +16,16 @@ Fence::Fence(Stream s) { fence_ = std::make_shared<FenceImpl>(0, s); }   +Fence::Fence(Stream s, bool) : Fence(s) {} + void Fence::wait(Stream s, const array&, uint32_t value) { auto event = cast<FenceImpl>().event; event.set_value(value); event.wait(s); +} + +bool Fence::wait_in_consumer(Stream, const array&, int, uint32_t) { + return false; }   uint32_t Fence::update(Stream s, const array&, bool) {
diff --git ml-explore/mlx/mlx/fence.h Layr-Labs/mlx/mlx/fence.h index fd6bc116a4b79c9a0eba92f535774d12a8bbb01b..80a05cf6d453d0ec4f56e34a69d93af5bb2ece25 100644 --- ml-explore/mlx/mlx/fence.h +++ Layr-Labs/mlx/mlx/fence.h @@ -25,9 +25,21 @@ class Fence { public: Fence() {}; explicit Fence(Stream stream); + // `fast` false synchronizes with events even when fast synchronization is + // enabled. Backends without fast synchronization ignore it. + Fence(Stream stream, bool fast);   uint32_t update(Stream stream, const array& x, bool cross_device); void wait(Stream stream, const array& x, uint32_t value); + + // Give the wait for `value` on input `input` of `consumer` to the consumer's + // own GPU kernel (a fenced input of a Metal custom kernel). Returns false + // when it cannot; call `wait` then. + bool wait_in_consumer( + Stream stream, + const array& consumer, + int input, + uint32_t value);   template <typename T> auto& cast() const {
diff --git ml-explore/mlx/mlx/transforms.cpp Layr-Labs/mlx/mlx/transforms.cpp index cad704bd4389b23432cf9bcd96df5715335aee25..a5460ae11ec2644c94cdd82dadc46fdba5e3c60c 100644 --- ml-explore/mlx/mlx/transforms.cpp +++ Layr-Labs/mlx/mlx/transforms.cpp @@ -24,8 +24,115 @@ namespace mlx::core {   static constexpr int MAX_ACTIVE_TASKS = 10;   +// At most MLX_MAX_ACTIVE_TASKS (default MAX_ACTIVE_TASKS) tasks in flight. +// MLX_MAX_ACTIVE_CPU_TASKS=n (n > 0) gives CPU-stream tasks their own limit +// n, and the first limit then counts GPU command buffers only. +static bool too_many_active_tasks() { + static const int max_tasks = + env::get_var("MLX_MAX_ACTIVE_TASKS", MAX_ACTIVE_TASKS); + static const int max_cpu_tasks = env::get_var("MLX_MAX_ACTIVE_CPU_TASKS", 0); + int n_tasks = scheduler::n_active_tasks(); + if (max_cpu_tasks <= 0) { + return n_tasks > max_tasks; + } + int n_cpu_tasks = scheduler::n_active_cpu_tasks(); + return n_tasks - n_cpu_tasks > max_tasks || n_cpu_tasks > max_cpu_tasks; +} + namespace {   +// Degree of each array id in eval_impl's graph walk: an open-addressing map +// (linear probing, deletion by backward shift) with the operations of the +// std::unordered_map it replaces. A decode step's graph has thousands of +// nodes; this avoids a heap node per entry and the rehash chain. +class DegreeMap { + public: + int* find(std::uintptr_t key) { + if (keys_.empty()) { + return nullptr; + } + for (size_t i = home(key);; i = (i + 1) & mask_) { + if (keys_[i] == key) { + return &values_[i]; + } + if (keys_[i] == 0) { + return nullptr; + } + } + } + // Inserts `value` when `key` is absent; the entry either way. + int& emplace(std::uintptr_t key, int value) { + if (2 * (size_ + 1) > keys_.size()) { + grow(); + } + size_t i = home(key); + for (; keys_[i] != 0; i = (i + 1) & mask_) { + if (keys_[i] == key) { + return values_[i]; + } + } + keys_[i] = key; + values_[i] = value; + ++size_; + return values_[i]; + } + int& operator[](std::uintptr_t key) { + return emplace(key, 0); + } + void erase(std::uintptr_t key) { + if (keys_.empty()) { + return; + } + size_t i = home(key); + for (; keys_[i] != key; i = (i + 1) & mask_) { + if (keys_[i] == 0) { + return; + } + } + for (size_t j = (i + 1) & mask_; keys_[j] != 0; j = (j + 1) & mask_) { + size_t h = home(keys_[j]); + bool stays = i <= j ? (i < h && h <= j) : (i < h || h <= j); + if (!stays) { + keys_[i] = keys_[j]; + values_[i] = values_[j]; + i = j; + } + } + keys_[i] = 0; + values_[i] = 0; + --size_; + } + bool empty() const { + return size_ == 0; + } + + private: + size_t home(std::uintptr_t key) const { + uint64_t k = key; + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + return static_cast<size_t>(k) & mask_; + } + void grow() { + std::vector<std::uintptr_t> keys(std::max<size_t>(64, 2 * keys_.size()), 0); + std::vector<int> values(keys.size(), 0); + std::swap(keys, keys_); + std::swap(values, values_); + mask_ = keys_.size() - 1; + size_ = 0; + for (size_t i = 0; i < keys.size(); ++i) { + if (keys[i] != 0) { + emplace(keys[i], values[i]); + } + } + } + std::vector<std::uintptr_t> keys_; + std::vector<int> values_; + size_t mask_ = 0; + size_t size_ = 0; +}; + // Create a tracer copy of a primal for use in vjp/jvp. If the primal is a // stale Copy from a previous transform call (not an active tracer), peel it // off to prevent copy-chain accumulation when containers feed tracers back. @@ -91,18 +198,40 @@ } return default_stream(default_device()); }();   - struct FenceInfo { - int stream_index; - bool cross_device; - uint32_t value{0}; + // Arrays read on another stream: the stream they are computed on, whether + // a reader waits on the fence (`fast`, a spinning wait under fast synch) or + // on an event fence (`event`), and whether a reader is on another device. + struct FenceNeed { + uint32_t stream; + bool producer_gpu; + bool cross_device{false}; + bool fast{false}; + bool event{false}; + // The values that the fence updates returned (see Fence::update). + uint32_t fast_value{0}; + uint32_t event_value{0}; }; - std::unordered_map<uintptr_t, FenceInfo> needs_fence; + std::unordered_map<uintptr_t, FenceNeed> needs_fence; + // GPU streams that read a CPU array, per CPU array (decided after the walk). + std::unordered_map<uintptr_t, std::vector<uint32_t>> cpu_to_gpu_readers; + + // GPU streams with an array that a CPU primitive reads + std::unordered_set<uint32_t> gpu_to_cpu;   auto synchronizer = array( {}, bool_, std::make_shared<Synchronizer>(stream), std::move(outputs));   // Stream fences for inter-stream synchronization std::unordered_map<uint32_t, Fence> fences; + // Event fences for readers that must not spin. Under fast synch a GPU + // fence wait is a kernel that spins until its producer's timestamp + // arrives, and Metal does not guarantee that another command queue runs + // while a pass of this queue spins. So a GPU stream never spins on another + // GPU stream, nor on CPU work that can itself wait for another GPU stream + // (the starved queue would hold back the timestamp the spin waits for). + // Both wait on a shared event instead. CPU waits keep the fast path: a CPU + // stream is a thread and always progresses. + std::unordered_map<uint32_t, Fence> event_fences;   // Stream events for synchronization after eval std::unordered_map<uint32_t, Event> events; @@ -115,7 +244,7 @@ }   { // Record the degree of each input - std::unordered_map<std::uintptr_t, int> cache; + DegreeMap cache;   std::stack<std::pair<std::reference_wrapper<array>, int>> dfs; dfs.emplace(synchronizer, 0); @@ -150,25 +279,41 @@ } if (a.primitive().stream() != in.primitive().stream()) { bool device_switch = a.primitive().stream().device != in.primitive().stream().device; - auto [it, inserted] = needs_fence.emplace( - in.id(), - FenceInfo{in.primitive().stream().index, device_switch}); - if (!inserted) { - it->second.cross_device |= device_switch; + auto& need = needs_fence + .emplace( + in.id(), + FenceNeed{ + static_cast<uint32_t>( + in.primitive().stream().index), + in.primitive().device() == Device::gpu}) + .first->second; + need.cross_device |= device_switch; + bool gpu_reader = a.primitive().device() == Device::gpu; + if (in.primitive().device() == Device::gpu) { + // Another GPU stream waits on an event; the CPU spins. + (gpu_reader ? need.event : need.fast) = true; + } else if (gpu_reader) { + cpu_to_gpu_readers[in.id()].push_back( + static_cast<uint32_t>(a.primitive().stream().index)); + } else { + need.fast = true; + } + if (device_switch && in.primitive().device() == Device::gpu) { + gpu_to_cpu.insert(in.primitive().stream().index); } } }   // All siblings have the same degree auto cache_it = cache.find(in.id()); - if (cache_it == cache.end()) { + if (cache_it == nullptr) { dfs.emplace(in, 0); - cache.insert({in.id(), 1}); + cache.emplace(in.id(), 1); for (auto& s : in.siblings()) { - cache.insert({s.id(), 1}); + cache.emplace(s.id(), 1); } } else { - cache_it->second++; + (*cache_it)++; for (auto& s : in.siblings()) { cache[s.id()]++; } @@ -183,6 +328,17 @@ } dfs.pop(); }   + // A GPU stream may spin on CPU work only when that CPU work can wait for + // no GPU stream but this one. + for (auto& [id, readers] : cpu_to_gpu_readers) { + auto& need = needs_fence.at(id); + for (auto reader : readers) { + bool alone = gpu_to_cpu.empty() || + (gpu_to_cpu.size() == 1 && gpu_to_cpu.count(reader) == 1); + (alone ? need.fast : need.event) = true; + } + } + // Build the tape in BFS order with a width limit int max_width = env::bfs_max_width(); dfs = std::stack<std::pair<std::reference_wrapper<array>, int>>(); @@ -210,9 +366,9 @@ break; }   auto it = cache.find(in.id()); - it->second -= 1; + *it -= 1;   - if (it->second != 0) { + if (*it != 0) { for (auto& s : in.siblings()) { cache[s.id()] -= 1; } @@ -220,7 +376,7 @@ continue; }   // Remove input and siblings from cache - cache.erase(it); + cache.erase(in.id()); for (auto& s : in.siblings()) { cache.erase(s.id()); } @@ -252,13 +408,33 @@ s.attach_event(e->second); } }   - for (auto& in : arr.inputs()) { + // A kernel can wait for its CPU-stream input itself when that CPU work + // can depend on no GPU stream other than this one. + bool one_gpu_stream = gpu_to_cpu.empty() || + (gpu_to_cpu.size() == 1 && gpu_to_cpu.count(stream.index) == 1); + for (int i = 0; i < arr.inputs().size(); ++i) { + auto& in = arr.inputs()[i]; if (auto it = needs_fence.find(in.id()); it != needs_fence.end()) { // Use fence to wait within a single eval // Get the input array's stream fence and wait on the // output arrays stream - auto& info = it->second; - fences.at(info.stream_index).wait(stream, in, info.value); + auto& need = it->second; + // On the producer's own stream, wait on the fence its update used + // (as before: the update precedes in this stream). Across streams, + // a GPU stream waits on the event for another GPU stream's array, + // or for CPU work that can wait for another GPU stream: never spin. + bool same_stream = need.stream == static_cast<uint32_t>(stream.index); + if (same_stream ? !need.fast + : (stream.device == Device::gpu && + (need.producer_gpu || !one_gpu_stream))) { + event_fences.at(need.stream).wait(stream, in, need.event_value); + continue; + } + auto& fence = fences.at(need.stream); + if (!one_gpu_stream || + !fence.wait_in_consumer(stream, arr, i, need.fast_value)) { + fence.wait(stream, in, need.fast_value); + } } else if (in.event().valid()) { if (in.event().is_signaled()) { in.detach_event(); @@ -275,7 +451,7 @@ } else { cpu::eval(arr); }   - if (scheduler::n_active_tasks() > MAX_ACTIVE_TASKS || + if (too_many_active_tasks() || (get_active_memory() > get_memory_limit() && scheduler::n_active_tasks() > 0)) { // Commit any open streams @@ -291,17 +467,40 @@ scheduler::wait_for_one(); } }   - auto maybe_update_fence = - [&fences, &needs_fence, stream](const array& a) { - if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) { - auto it = fences.find(stream.index); - if (it == fences.end()) { - it = fences.emplace(stream.index, Fence{stream}).first; - } - nf->second.value = - it->second.update(stream, a, nf->second.cross_device); + auto maybe_update_fence = [&fences, &event_fences, &needs_fence, stream]( + const array& a) { + if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) { + // The fast update comes first: with cross_device it can move `a` + // (CUDA moves it to unified memory), and the event update must + // come after that move so that event waiters see the moved data. + if (nf->second.fast) { + auto it = fences.find(stream.index); + if (it == fences.end()) { + it = fences.emplace(stream.index, Fence{stream}).first; } - }; + nf->second.fast_value = + it->second.update(stream, a, nf->second.cross_device); + } + if (nf->second.event) { + auto it = event_fences.find(stream.index); + if (it == event_fences.end()) { + it = event_fences + .emplace(stream.index, Fence{stream, /* fast */ false}) + .first; + } + nf->second.event_value = it->second.update(stream, a, false); + } + // MLX_EAGER_FENCE_COMMIT=1: commit the GPU work now, after both + // updates, so the CPU stream starts when `a` is ready, not when + // the buffer is full. + static const bool eager_commit = + env::get_var("MLX_EAGER_FENCE_COMMIT", 0); + if (eager_commit && nf->second.fast && nf->second.cross_device && + stream.device == Device::gpu) { + gpu::finalize(stream); + } + } + };   arr.set_status(array::Status::evaluated); // TODO Maybe always want the fence coherent kernel in the same cbuf @@ -375,6 +574,9 @@ })) { return; }   + // A stream task can fail while async_eval still enqueues later tasks. + // synchronize raises that error, not async_eval. + scheduler::DeferStreamErrors defer; eval_impl(std::move(outputs), true); }

quantized_matmul cast x, scales and biases, gather and scatter broadcast their indices, the gather matmuls cast their indices, and affine_quantize selected its scales on the thread’s default stream instead of the stream the caller passed. mlx-swift passes its own process-wide stream to every op, so each of these helpers put a second GPU stream into the graph: a 4-bit projection with float32 input and bfloat16 scales crossed streams twice, and every crossing is a fence wait. They now use the caller’s stream. Where an op runs does not change what it computes.

diff --git ml-explore/mlx/mlx/ops.cpp Layr-Labs/mlx/mlx/ops.cpp index 45c4d2f4be602cbb9ca91da8a1bb17c5416173d3..bb7053d0e06803285bd502370427fa06584ab3c4 100644 --- ml-explore/mlx/mlx/ops.cpp +++ Layr-Labs/mlx/mlx/ops.cpp @@ -3775,7 +3775,7 @@ "[gather] Got indices with invalid dtype. Indices must be integral."); }   // Broadcast and cast indices if necessary - auto inputs = broadcast_arrays(indices); + auto inputs = broadcast_arrays(indices, s); for (auto& idx : inputs) { idx = astype(idx, dtype, s); } @@ -4054,7 +4054,7 @@ "[scatter] Number of index arrays does not match number of axes."); }   // Broadcast and cast indices if necessary - auto inputs = broadcast_arrays(indices); + auto inputs = broadcast_arrays(indices, s);   Shape idx_shape; if (!inputs.empty()) { @@ -4967,8 +4967,14 @@ throw std::invalid_argument(msg.str()); } std::vector<array> inputs; if (qmode == QuantizationMode::Affine) { + // On the caller's stream: a cast on the thread's default stream is a + // second GPU stream whenever the caller passed its own (mlx-swift's + // Stream.gpu), and every cast then crosses streams through fences. inputs = { - astype(x, dtype), w, astype(scales, dtype), astype(*biases, dtype)}; + astype(x, dtype, s), + w, + astype(scales, dtype, s), + astype(*biases, dtype, s)}; } else { inputs = {x, w, scales}; } @@ -5106,6 +5112,12 @@ // validate inputs validate_qqmm_inputs( x, w, scales_w, group_size, bits, global_scale_x, global_scale_w, qmode); + // The CPU kernel has no global scale input. Refuse rather than ignore it. + if ((global_scale_x.has_value() || global_scale_w.has_value()) && + stream.device != Device::gpu) { + throw std::invalid_argument( + "[qqmm] Global scale is only supported on the GPU."); + } // validate and extract shapes auto [w_inner_dims, w_outer_dims] = extract_qqmm_dims(x, w, scales_w, group_size, bits); @@ -5232,7 +5244,7 @@ scales = maximum(divide(subtract(w_max, w_min, s), n_bins, s), eps, s); scales = where(mask, scales, negative(scales, s), s); array edge = where(mask, w_min, w_max, s); array q0 = round(divide(edge, scales, s), s); - scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales); + scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales, s); biases = where(equal(q0, zero, s), zero, edge, s); }

Opt-in (MLX_METAL_FUSED_FENCE_UPDATE=1, fast synch only). A GPU array that the CPU reads in the same eval is made coherent and its fence timestamp is written in one dispatch (fence_update_coherent) instead of input_coherent then fence_update. Every word is still rewritten with system-coherent stores before a system-scope fence. The last threadgroup to finish writes the timestamp. The fence buffer carries an arrival count that only increases, so an unfinished earlier dispatch can delay a timestamp but cannot release it early. Synchronization only: results do not change.

diff --git ml-explore/mlx/mlx/backend/metal/kernels/fence.metal Layr-Labs/mlx/mlx/backend/metal/kernels/fence.metal index cd5f9016b991719ebedb06aeb92479db0864a0d1..44e5b29dc06e1a12fdd935664e698d6661fbc221 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/fence.metal +++ Layr-Labs/mlx/mlx/backend/metal/kernels/fence.metal @@ -36,6 +36,55 @@ metal::memory_order_seq_cst, metal::thread_scope_system); }   +// input_coherent and fence_update in one dispatch. The last threadgroup to +// finish its words writes the timestamp. `arrivals` only increases: this +// dispatch moves it from target - groups to target (mod 2^32), so an +// unfinished earlier dispatch can stop the timestamp but never release it +// early. One threadgroup does not use `arrivals`. +[[kernel]] void fence_update_coherent( + volatile coherent(system) device uint* input [[buffer(0)]], + const constant uint& size [[buffer(1)]], + volatile coherent(system) device uint* timestamp [[buffer(2)]], + constant uint& value [[buffer(3)]], + device metal::atomic_uint* arrivals [[buffer(4)]], + constant uint& target [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], + uint groups [[threadgroups_per_grid]], + uint index [[thread_index_in_threadgroup]], + uint threads [[threads_per_threadgroup]]) { + for (uint i = group * threads + index; i < size; i += groups * threads) { + input[i] = input[i]; + } + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + metal::threadgroup_barrier(metal::mem_flags::mem_device); + if (index != 0) { + return; + } + if (groups > 1) { + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + uint previous = metal::atomic_fetch_add_explicit( + arrivals, 1u, metal::memory_order_relaxed); + if (previous + 1u != target) { + return; + } + } + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); + timestamp[0] = value; + metal::atomic_thread_fence( + metal::mem_flags::mem_device, + metal::memory_order_seq_cst, + metal::thread_scope_system); +} + // single thread kernel to spin wait for timestamp value [[kernel]] void fence_wait( volatile coherent(system) device uint* timestamp [[buffer(0)]],

Opt-in (MLX_METAL_FENCED_INPUTS=1, fast synch only). metal_kernel_with_fenced_inputs declares inputs that can come from a CPU stream in the same eval, such as a CPU-stream all-sum. The source calls MLX_FENCED_INPUT_WAIT(name) before it reads such an input. MLX then gives the CPU fence and the value of the update it waits for to the kernel instead of a fence_wait dispatch, and thread 0 of each threadgroup spins on it. The kernel starts after every pass and kernel encoded before it (wait_for_all_pending and a barrier), as the fence_wait pass does, so the CPU work it waits for never waits for it. MLX keeps the separate wait when the input is copied first, when another GPU stream feeds the CPU in the same eval, and while exporting. A fenced input is always in the device address space, never constant, because the GPU may load a small constant buffer before the kernel’s wait. The kernel takes its waits before any argument check can throw, so no wait is left for a later kernel. The declaration is not part of the exported schema. Synchronization only: results do not change.

The fence_wait dispatch itself makes its pass wait for every pass in flight (wait_for_all_pending), and a buffer barrier orders it after the earlier kernels of the same pass. Upstream (ml-explore/mlx#4689) gets the same order with a pass of its own for each wait (end_encoding() before the dispatch, end_encoding(true) after it). The fork keeps the wait in the current pass, so a wait adds no encoder boundary; end_encoding(true) stays available and waits as wait_for_all_pending does. Fence waits use the value that the producer’s update returned, as upstream does since ml-explore/mlx#4552.

diff --git ml-explore/mlx/mlx/backend/metal/fenced_input.h Layr-Labs/mlx/mlx/backend/metal/fenced_input.h new file mode 100644 index 0000000000000000000000000000000000000000..fb3f5e5cbe502134590a7ea5991d09107a23f647 --- /dev/null +++ Layr-Labs/mlx/mlx/backend/metal/fenced_input.h @@ -0,0 +1,32 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include <cstdint> +#include <memory> +#include <vector> + +#include "mlx/array.h" +#include "mlx/backend/metal/device.h" + +namespace mlx::core::metal { + +// The wait of a custom kernel on a fenced input from a CPU stream, given to +// the kernel by Fence::wait_in_consumer instead of a fence_wait dispatch. +struct FencedInput { + const Primitive* consumer; + int input; + std::shared_ptr<void> fence; + uint32_t count; +}; + +// Remove the waits given to `consumer` and return them. Discard all others. +std::vector<FencedInput> take_fenced_inputs(const Primitive* consumer); + +// Bind the timestamp buffer at `index` and the count at `index + 1`. +void bind_fenced_input(CommandEncoder& enc, const FencedInput& f, int index); + +// Encode the wait as Fence::wait does, for an input read before the kernel. +void encode_fence_wait(Stream stream, const array& x, const FencedInput& f); + +} // namespace mlx::core::metal

Host time only: generated sources, kernel names, buffers and dispatch order do not change. Custom-kernel primitives share the cached generated source and resolve the pipeline once per source; repeat launches skip rebuilding the name, template string and cache key, and bind inputs directly when none needs a contiguous copy. Graph teardown dedups node inputs with a small vector, eval_impl’s per-node map is a flat open-addressing map, and allocation reads the device’s maximum buffer length once.

diff --git ml-explore/mlx/mlx/array.cpp Layr-Labs/mlx/mlx/array.cpp index cf49a0fe5f1d5f75c85fbf0ad3db619ee6dea7c4..4e2fa92b914167256cbfb7c54f1a636235de2bc7 100644 --- ml-explore/mlx/mlx/array.cpp +++ Layr-Labs/mlx/mlx/array.cpp @@ -1,6 +1,7 @@ // Copyright © 2023-2024 Apple Inc. #include <functional> #include <unordered_map> +#include <unordered_set>   #include "mlx/array.h" #include "mlx/ops.h" @@ -283,18 +284,50 @@ }   std::vector<std::shared_ptr<ArrayDesc>> for_deletion;   + // The distinct inputs (and their siblings) of `ad`, one reference each. + // A graph node has a few inputs, so a vector with a linear search does + // the work of a hash map without allocating a node per input; large + // input lists also get a hash index. auto append_deletable_inputs = [&for_deletion](ArrayDesc& ad) { - std::unordered_map<std::uintptr_t, array> input_map; + constexpr size_t linear_max = 32; + // Ids are kept beside the arrays: a moved-out array has no id. + std::vector<std::pair<std::uintptr_t, array>> distinct; + std::unordered_set<std::uintptr_t> index; + auto contains = [&](std::uintptr_t id) { + if (distinct.size() <= linear_max) { + for (auto& x : distinct) { + if (x.first == id) { + return true; + } + } + return false; + } + return index.count(id) > 0; + }; + auto insert = [&](const array& x) { + if (contains(x.id())) { + return; + } + distinct.emplace_back(x.id(), x); + if (distinct.size() == linear_max + 1) { + for (auto& y : distinct) { + index.insert(y.first); + } + } else if (distinct.size() > linear_max + 1) { + index.insert(x.id()); + } + }; + distinct.reserve(ad.inputs.size()); for (array& a : ad.inputs) { if (a.array_desc_) { - input_map.insert({a.id(), a}); + insert(a); for (auto& s : a.siblings()) { - input_map.insert({s.id(), s}); + insert(s); } } } ad.inputs.clear(); - for (auto& [_, a] : input_map) { + for (auto& [_, a] : distinct) { bool is_deletable = (a.array_desc_.use_count() <= a.siblings().size() + 1); // An array with siblings is deletable only if all of its siblings @@ -303,7 +336,7 @@ for (auto& s : a.siblings()) { if (!is_deletable) { break; } - int is_input = (input_map.find(s.id()) != input_map.end()); + int is_input = contains(s.id()); is_deletable &= s.array_desc_.use_count() <= a.siblings().size() + is_input; }
diff --git ml-explore/mlx/mlx/backend/cuda/custom_kernel.cpp Layr-Labs/mlx/mlx/backend/cuda/custom_kernel.cpp index c230656d80a7271e24c85dc678c3337709e87f56..6fede0dbbc6276bfb81bdd2f8dfd96e8ac39d422 100644 --- ml-explore/mlx/mlx/backend/cuda/custom_kernel.cpp +++ Layr-Labs/mlx/mlx/backend/cuda/custom_kernel.cpp @@ -310,14 +310,15 @@ // Compile the custom kernel std::string kernel_name = (is_precompiled_) ? name_ : "mlx::core::cu::" + name_; + const std::string& source = source_->source; std::string module_name = - fmt::format("{}_{:x}", name_, std::hash<std::string>{}(source_)); + fmt::format("{}_{:x}", name_, std::hash<std::string>{}(source)); cu::JitModule& mod = cu::get_jit_module( encoder.device(), module_name, [&]() { return std::make_tuple( - is_precompiled_, source_, std::vector{kernel_name}); + is_precompiled_, source, std::vector{kernel_name}); }, false);

Sorted gathered matrix products use the remaining reduction width for a partial activation tile. Safe affine and floating-quantized weight loaders check row and packed-column bounds on both legacy and NAX paths before reading weights or scales, then zero invalid lanes. This prevents finite tails from reading the next row, including a following NaN row. Exact Python regressions cover affine, MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. Each affine/floating-point, legacy/NAX loader has a distinct type name. Their layouts or bodies differ; sharing a name corrupts MXFP4 results when the offline Metal linker combines the translation units. The incompatible affine/FP pack-factor helpers and legacy/NAX vector loaders also use distinct names. Aligned dispatch and accumulation precision remain unchanged.

diff --git ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized_nax.h Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized_nax.h index 817519a4d37663bcaadf8cbe286bdced59f61101..98d59469151611d6b9491445c1773eb703cc4d33 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/fp_quantized_nax.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -18,7 +18,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4;   template <int wsize = 8, int bits> -inline constexpr short get_pack_factor() { +inline constexpr short get_fp_pack_factor() { return wsize / bits; }   @@ -79,8 +79,8 @@ short tgp_size, short group_size, short bits, bool has_global_scale = false> -struct QuantizedBlockLoader { - MLX_MTL_CONST short pack_factor = get_pack_factor<8, bits>(); +struct FPQuantizedNAXBlockLoader { + MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -110,7 +110,7 @@ // nvfp4 tensor scale, folded into the group scale as fp_dequantize does. // Kept in float: it is ~1e-5, so in fp16 small scales lose most bits. float inv_scale_enc = 1.0f;   - QuantizedBlockLoader( + FPQuantizedNAXBlockLoader( const device uint8_t* src_, const device uint8_t* scales_, const int src_ld_, @@ -136,11 +136,131 @@ inv_scale_enc = *global_scale / (F8E4M3_MAX * F4E2M1_MAX); } }   + void fetch_nvfp4(thread uint2* q_buf, thread uint8_t* s_buf) const thread { + if constexpr (n_steps_per_read == 2) { + const uint4 q4 = *(const device uint4*)src; + q_buf[0] = q4.xy; + q_buf[1] = q4.zw; + const uchar2 s2 = *(const device uchar2*)scales; + s_buf[0] = s2.x; + s_buf[1] = s2.y; + } else { + const device uint2* src_u2 = (const device uint2*)src; + for (int i = 0; i < n_steps_per_read; i++) { + q_buf[i] = src_u2[i]; + s_buf[i] = scales[i]; + } + } + } + + void store_nvfp4( + threadgroup T* ws_base, + const thread uint2* q_buf, + const thread uint8_t* s_buf) const thread { + threadgroup vec<T, 8>* dst_v8 = + (threadgroup vec<T, 8>*)(ws_base + bi * dst_ld + bj * pack_factor); + for (int i = 0; i < n_steps_per_read; i++) { + const half scale = dequantize_scale<half, 16>(s_buf[i]); + const uint2 q = q_buf[i]; + { + const uint lo0 = (q.x & 0x000f) | ((q.x & 0x00f0) << 12); + const uint hi0 = ((q.x >> 8) & 0x000f) | ((q.x & 0xf000) << 4); + half2 a0 = + (as_type<half2>( + ((lo0 & 0x00070007) << 9) | ((lo0 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b0 = + (as_type<half2>( + ((hi0 & 0x00070007) << 9) | ((hi0 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + + const uint qx1 = q.x >> 16; + const uint lo1 = (qx1 & 0x000f) | ((qx1 & 0x00f0) << 12); + const uint hi1 = ((qx1 >> 8) & 0x000f) | ((qx1 & 0xf000) << 4); + half2 a1 = + (as_type<half2>( + ((lo1 & 0x00070007) << 9) | ((lo1 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b1 = + (as_type<half2>( + ((hi1 & 0x00070007) << 9) | ((hi1 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + dst_v8[2 * i + 0] = vec<T, 8>( + T(a0.x), + T(a0.y), + T(b0.x), + T(b0.y), + T(a1.x), + T(a1.y), + T(b1.x), + T(b1.y)); + } + { + const uint lo2 = (q.y & 0x000f) | ((q.y & 0x00f0) << 12); + const uint hi2 = ((q.y >> 8) & 0x000f) | ((q.y & 0xf000) << 4); + half2 a2 = + (as_type<half2>( + ((lo2 & 0x00070007) << 9) | ((lo2 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b2 = + (as_type<half2>( + ((hi2 & 0x00070007) << 9) | ((hi2 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + + const uint qy1 = q.y >> 16; + const uint lo3 = (qy1 & 0x000f) | ((qy1 & 0x00f0) << 12); + const uint hi3 = ((qy1 >> 8) & 0x000f) | ((qy1 & 0xf000) << 4); + half2 a3 = + (as_type<half2>( + ((lo3 & 0x00070007) << 9) | ((lo3 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b3 = + (as_type<half2>( + ((hi3 & 0x00070007) << 9) | ((hi3 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + dst_v8[2 * i + 1] = vec<T, 8>( + T(a2.x), + T(a2.y), + T(b2.x), + T(b2.y), + T(a3.x), + T(a3.y), + T(b3.x), + T(b3.y)); + } + } + } + void load_unsafe() const thread { if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; }   + // sizeof(T) == 2 checks the 16-bit threadgroup tile storage width (Wtype, + // which is bfloat across fp_qmm_t_nax / fp_gather_qmm_t_nax / + // fp_gather_qmm_rhs_nax regardless of activation dtype, and activation T + // in fp_qmm_n_impl) so vec<T, 8> stores remain 16-byte aligned. + if constexpr ( + bits == 4 && group_size == 16 && !has_global_scale && sizeof(T) == 2 && + n_reads_per_scale == 8) { + if ((src_ld & 31) == 0 && (reinterpret_cast<uintptr_t>(src) & 15) == 0 && + (reinterpret_cast<uintptr_t>(scales) & 1) == 0) { + uint2 q_buf[n_steps_per_read]; + uint8_t s_buf[n_steps_per_read]; + fetch_nvfp4(q_buf, s_buf); + store_nvfp4(dst - (bi * dst_ld + bj * pack_factor), q_buf, s_buf); + return; + } + } + int k = 0; for (int i = 0; i < n_steps_per_read; i++) { float scale = @@ -167,11 +287,19 @@ }   int k = 0; for (int i = 0; i < n_steps_per_read; i++) { - float scale = - float(dequantize_scale<T, group_size>(scales[i])) * inv_scale_enc; + const bool scale_in_bounds = (bj + k) * pack_factor < src_tile_dim.x; + float scale = scale_in_bounds + ? float(dequantize_scale<T, group_size>(scales[i])) * inv_scale_enc + : 0.0f; for (int j = 0; j < n_reads_per_scale; j++) { - dequantize<T, bits>( - src[k * bytes_per_pack], scale, dst + k * pack_factor); + if ((bj + k) * pack_factor < src_tile_dim.x) { + dequantize<T, bits>( + src[k * bytes_per_pack], scale, dst + k * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[k * pack_factor + p] = T(0); + } + } k++; } } @@ -200,7 +328,8 @@ const int BK = 64, const int BN = 64, const int WM = 2, const int WN = 2, - typename Wtype = bfloat> + typename Wtype = bfloat, + const bool double_buffer_ws = false> METAL_FUNC void fp_qmm_t_impl( const device uint32_t* w, const device uint8_t* scales, @@ -220,13 +349,13 @@ static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE");   (void)lid;   - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack();   constexpr int BK_padded = (BK + 16 / sizeof(Wtype));   // Instantiate Loader - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, BN, BK, @@ -284,43 +413,184 @@ x += tm * K;   dispatch_bool(!is_unaligned_sm, [&](auto kAlignedM) { dispatch_bool(aligned_N || !is_unaligned_bn, [&](auto kAlignedN) { - for (int k = 0; k < K; k += BK) { - threadgroup_barrier(mem_flags::mem_threadgroup); - if constexpr (kAlignedN.value) { - loader_w.load_unsafe(); - } else { - loader_w.load_safe(short2(BK, tgp_bn)); - } + const bool fast_nvfp4 = (K > 0) && ((K & 31) == 0) && + ((reinterpret_cast<uintptr_t>(wl) & 15) == 0) && + ((reinterpret_cast<uintptr_t>(scales) & 1) == 0); + // sizeof(Wtype) == 2 checks the 16-bit threadgroup weight-tile storage + // width (bfloat in fp_qmm_t_nax and fp_gather_qmm_t_nax for all + // activation dtypes) so vec<Wtype, 8> stores remain 16-byte aligned. + if constexpr ( + kAlignedN.value && bits == 4 && group_size == 16 && + !has_global_scale && sizeof(Wtype) == 2 && + loader_w_t::n_reads_per_scale == 8 && + loader_w_t::BCOLS_PACKED * BN >= WM * WN * SIMD_SIZE) { + if (fast_nvfp4) { + constexpr int ws_tile_size = BN * BK_padded; + uint2 q_buf[loader_w_t::n_steps_per_read]; + uint8_t s_buf[loader_w_t::n_steps_per_read]; + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + if constexpr (double_buffer_ws) { + loader_w.store_nvfp4(Ws, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + int stage = 0; + for (int k = 0; k < K; k += BK) { + if (k + BK < K) { + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + } + + threadgroup Wtype* Ws_cur = Ws + stage * ws_tile_size; + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, TN, TK> Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + }   - threadgroup_barrier(mem_flags::mem_threadgroup); + Btile.template load<Wtype, BK_padded, 1>( + Ws_cur + tn * BK_padded + kk1);   - STEEL_PRAGMA_NO_UNROLL - for (int kk1 = 0; kk1 < BK; kk1 += SK) { - NAXTile<T, TM, TK> Atile; - NAXTile<Wtype, TN, TK> Btile; + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<transpose_a>{}, + Btile, + metal::bool_constant<transpose_b>{}); + + (void)compiler_barrier; + }   - volatile int compiler_barrier; + if (k + BK < K) { + loader_w.store_nvfp4( + Ws + (1 - stage) * ws_tile_size, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + stage = 1 - stage; + }   - if constexpr (kAlignedM.value) { - Atile.load(x + kk1, K); + x += BK; + } } else { - Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_w.store_nvfp4(Ws, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (k + BK < K) { + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + } + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, TN, TK> Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load<Wtype, BK_padded, 1>( + Ws + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<transpose_a>{}, + Btile, + metal::bool_constant<transpose_b>{}); + + (void)compiler_barrier; + } + + x += BK; + } } + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup);   - Btile.template load<Wtype, BK_padded, 1>(Ws + tn * BK_padded + kk1); + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, TN, TK> Btile;   - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant<transpose_a>{}, - Btile, - metal::bool_constant<transpose_b>{}); + volatile int compiler_barrier;   - (void)compiler_barrier; + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load<Wtype, BK_padded, 1>( + Ws + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<transpose_a>{}, + Btile, + metal::bool_constant<transpose_b>{}); + + (void)compiler_barrier; + } + + x += BK; + loader_w.next(); + } } + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if constexpr (kAlignedN.value) { + loader_w.load_unsafe(); + } else { + loader_w.load_safe(short2(BK, tgp_bn)); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, TN, TK> Btile;   - x += BK; - loader_w.next(); + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load<Wtype, BK_padded, 1>(Ws + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<transpose_a>{}, + Btile, + metal::bool_constant<transpose_b>{}); + + (void)compiler_barrier; + } + + x += BK; + loader_w.next(); + } }   // Store results to device memory @@ -368,6 +638,21 @@ Wtype(float(b.y) * scale)); } }   +template <typename Wtype> +METAL_FUNC vec<Wtype, 4> dequantize_fp4_x4_scaled(uint q, half scale) { + const uint lo = (q & 0x000f) | ((q & 0x00f0) << 12); + const uint hi = ((q >> 8) & 0x000f) | ((q & 0xf000) << 4); + half2 a = + (as_type<half2>(((lo & 0x00070007) << 9) | ((lo & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b = + (as_type<half2>(((hi & 0x00070007) << 9) | ((hi & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + return vec<Wtype, 4>(Wtype(a.x), Wtype(a.y), Wtype(b.x), Wtype(b.y)); +} + template < typename T, const int group_size, @@ -399,12 +684,12 @@ (void)lid; (void)M;   - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack();   constexpr int BN_padded = (BN + 16 / sizeof(T));   - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< T, BK, BN, @@ -617,8 +902,11 @@ uint simd_lid [[thread_index_in_simdgroup]]) { (void)lid;   constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); + constexpr bool kDoubleBuf = + (bits == 4 && group_size == 16 && !has_global_scale && + sizeof(Wtype) == 2);   - threadgroup Wtype Ws[BN * BK_padded]; + threadgroup Wtype Ws[(kDoubleBuf ? 2 : 1) * BN * BK_padded];   if (batched) { adjust_matrix_offsets( @@ -647,7 +935,8 @@ BK, BN, WM, WN, - Wtype>( + Wtype, + kDoubleBuf>( w, scales, global_scale, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); }   @@ -886,12 +1175,12 @@ const constant int& num_groups, uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<8, bits>(); + constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); constexpr int BN_padded = (BN + 16 / sizeof(Wtype));   - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = FPQuantizedNAXBlockLoader< Wtype, transpose ? BN : BK, transpose ? BK : BN, @@ -959,8 +1248,6 @@ constexpr short BR = transpose ? TN : TK; constexpr short BC = transpose ? TK : TN;   using AccumType = float; - - const bool sg_active = sgp_sm > 0;   NAXTile<AccumType, TM, TN> Dtile; Dtile.clear(); @@ -992,35 +1279,31 @@ threadgroup_barrier(mem_flags::mem_threadgroup);   STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile<T, TM, TK> Atile; - NAXTile<Wtype, BR, BC> Btile; + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, BR, BC> Btile;   - volatile int compiler_barrier; + volatile int compiler_barrier;   - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); + }   - if constexpr (transpose) { - Btile.template load<Wtype, BK_padded, 1>( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load<Wtype, BN_padded, 1>( - Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load<Wtype, BK_padded, 1>(Ws + tn * BK_padded + kk1); + } else { + Btile.template load<Wtype, BN_padded, 1>(Ws + tn + kk1 * BN_padded); + }   - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant<false>{}, - Btile, - metal::bool_constant<transpose>{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<false>{}, + Btile, + metal::bool_constant<transpose>{});   - (void)compiler_barrier; - } + (void)compiler_barrier; }   xn += BK; @@ -1034,32 +1317,28 @@ threadgroup_barrier(mem_flags::mem_threadgroup);   STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile<T, TM, TK> Atile; - NAXTile<Wtype, BR, BC> Btile; + NAXTile<T, TM, TK> Atile; + NAXTile<Wtype, BR, BC> Btile;   - volatile int compiler_barrier; + volatile int compiler_barrier;   - const short psk = min(int(SK), max(0, (k_remain - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + const short psk = min(int(SK), max(0, (k_remain - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm));   - if constexpr (transpose) { - Btile.template load<Wtype, BK_padded, 1>( - Ws + tn * BK_padded + kk1); - } else { - Btile.template load<Wtype, BN_padded, 1>( - Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load<Wtype, BK_padded, 1>(Ws + tn * BK_padded + kk1); + } else { + Btile.template load<Wtype, BN_padded, 1>(Ws + tn + kk1 * BN_padded); + }   - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant<false>{}, - Btile, - metal::bool_constant<transpose>{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<false>{}, + Btile, + metal::bool_constant<transpose>{});   - (void)compiler_barrier; - } + (void)compiler_barrier; } }   @@ -1130,80 +1409,265 @@ NAXTile<float, 1, TN> Dtile; Dtile.clear();   - for (int k = simd_gid * BK; k < K; k += WK * BK) { - vec<T, 8> xs[2][4]; - STEEL_PRAGMA_UNROLL - for (short r = 0; r < 2; r++) { - STEEL_PRAGMA_UNROLL - for (short i = 0; i < 4; i++) { - xs[r][i] = x_rows[r] - ? *(const device vec<T, 8>*)(x + r * 8 * static_cast<int64_t>(K) + - k + 8 * i) - : vec<T, 8>(0); + if constexpr (bits == 4 && group_size == 16) { + if (M <= 8) { + const bool x_row0 = fm < M; + uint4 ws_cur[TN][2]; + ushort ss_cur[TN][2]; + const int k0 = simd_gid * BK; + if (k0 < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws_cur[t][r] = + *(const device uint4*)(wl + + row * static_cast<int64_t>(row_bytes) + + k0 / 2); + ss_cur[t][r] = + *(const device ushort*)(scales + + row * static_cast<int64_t>(row_scales) + + k0 / 16); + } + } + } + + for (int k = k0; k < K; k += WK * BK) { + vec<T, 8> xs0[4]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + xs0[i] = + x_row0 ? *(const device vec<T, 8>*)(x + k + 8 * i) : vec<T, 8>(0); + } + + uint4 ws_next[TN][2]; + ushort ss_next[TN][2]; + const int kn = k + WK * BK; + if (kn < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws_next[t][r] = + *(const device uint4*)(wl + + row * static_cast<int64_t>(row_bytes) + + kn / 2); + ss_next[t][r] = *( + const device ushort*)(scales + + row * static_cast<int64_t>(row_scales) + + kn / 16); + } + } + } + + half sc0[TN][2]; + half sc1[TN][2]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + sc0[t][r] = dequantize_scale<half, 16>(uint8_t(ss_cur[t][r])); + sc1[t][r] = dequantize_scale<half, 16>(uint8_t(ss_cur[t][r] >> 8)); + } + } + + STEEL_PRAGMA_UNROLL + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t<T> a; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[j] = xs0[f / 2][4 * (f % 2) + j]; + a[4 + j] = T(0); + } + typename Frag::template dtype_frag_t<Wtype> b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const uint q = ws_cur[t][r][f / 2] >> (16 * (f % 2)); + const half sc = (f < 4) ? sc0[t][r] : sc1[t][r]; + const vec<Wtype, 4> v = dequantize_fp4_x4_scaled<Wtype>(q, sc); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant<false>{}, + b[t], + b[t + 1], + metal::bool_constant<true>{}); + } + } + + if (kn < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + ws_cur[t][r] = ws_next[t][r]; + ss_cur[t][r] = ss_next[t][r]; + } + } + } } - } - uint4 ws[TN][2][loads]; - scale_bits_t ss[TN][2]; - STEEL_PRAGMA_UNROLL - for (short t = 0; t < TN; t++) { - STEEL_PRAGMA_UNROLL - for (short r = 0; r < 2; r++) { - const int row = 16 * t + 8 * r; - const device uint8_t* wt = - wl + row * static_cast<int64_t>(row_bytes) + k / pack_factor; - const device uint8_t* st = - scales + row * static_cast<int64_t>(row_scales) + k / group_size; + } else { + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec<T, 8> xs[2][4]; STEEL_PRAGMA_UNROLL - for (short l = 0; l < loads; l++) { - ws[t][r][l] = *(const device uint4*)(wt + 16 * l); + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + xs[r][i] = x_rows[r] + ? *(const device vec<T, 8>*)(x + + r * 8 * static_cast<int64_t>(K) + + k + 8 * i) + : vec<T, 8>(0); + } } - ss[t][r] = *(const device scale_bits_t*)st; + uint4 ws[TN][2]; + ushort ss[TN][2]; + half sc0[TN][2]; + half sc1[TN][2]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws[t][r] = + *(const device uint4*)(wl + + row * static_cast<int64_t>(row_bytes) + + k / 2); + ss[t][r] = + *(const device ushort*)(scales + + row * static_cast<int64_t>(row_scales) + + k / 16); + sc0[t][r] = dequantize_scale<half, 16>(uint8_t(ss[t][r])); + sc1[t][r] = dequantize_scale<half, 16>(uint8_t(ss[t][r] >> 8)); + } + } + STEEL_PRAGMA_UNROLL + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t<T> a; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + } + } + typename Frag::template dtype_frag_t<Wtype> b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const uint q = ws[t][r][f / 2] >> (16 * (f % 2)); + const half sc = (f < 4) ? sc0[t][r] : sc1[t][r]; + const vec<Wtype, 4> v = dequantize_fp4_x4_scaled<Wtype>(q, sc); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant<false>{}, + b[t], + b[t + 1], + metal::bool_constant<true>{}); + } + } } } - - STEEL_PRAGMA_UNROLL - for (short f = 0; f < TK; f++) { - typename Frag::template dtype_frag_t<T> a; + } else { + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec<T, 8> xs[2][4]; STEEL_PRAGMA_UNROLL for (short r = 0; r < 2; r++) { STEEL_PRAGMA_UNROLL - for (short j = 0; j < 4; j++) { - a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + for (short i = 0; i < 4; i++) { + xs[r][i] = x_rows[r] + ? *(const device vec<T, 8>*)(x + r * 8 * static_cast<int64_t>(K) + + k + 8 * i) + : vec<T, 8>(0); } } - typename Frag::template dtype_frag_t<Wtype> b[TN]; + uint4 ws[TN][2][loads]; + scale_bits_t ss[TN][2]; STEEL_PRAGMA_UNROLL for (short t = 0; t < TN; t++) { STEEL_PRAGMA_UNROLL for (short r = 0; r < 2; r++) { - uint q; - if constexpr (bits == 4) { - q = ws[t][r][0][f / 2] >> (16 * (f % 2)); - } else { - q = ws[t][r][f / 4][f % 4]; - } - uint8_t s = ss[t][r]; - if constexpr (group_size == 16) { - s = ss[t][r] >> (8 * (f / 4)); - } - const vec<Wtype, 4> v = - dequantize_fp_x4<Wtype, group_size, bits>(q, s); + const int row = 16 * t + 8 * r; + const device uint8_t* wt = + wl + row * static_cast<int64_t>(row_bytes) + k / pack_factor; + const device uint8_t* st = + scales + row * static_cast<int64_t>(row_scales) + k / group_size; STEEL_PRAGMA_UNROLL - for (short j = 0; j < 4; j++) { - b[t][4 * r + j] = v[j]; + for (short l = 0; l < loads; l++) { + ws[t][r][l] = *(const device uint4*)(wt + 16 * l); } + ss[t][r] = *(const device scale_bits_t*)st; } } + STEEL_PRAGMA_UNROLL - for (short t = 0; t < TN; t += 2) { - Frag::mma( - Dtile.frag_at(0, t), - Dtile.frag_at(0, t + 1), - a, - metal::bool_constant<false>{}, - b[t], - b[t + 1], - metal::bool_constant<true>{}); + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t<T> a; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + } + } + typename Frag::template dtype_frag_t<Wtype> b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + uint q; + if constexpr (bits == 4) { + q = ws[t][r][0][f / 2] >> (16 * (f % 2)); + } else { + q = ws[t][r][f / 4][f % 4]; + } + uint8_t s = ss[t][r]; + if constexpr (group_size == 16) { + s = ss[t][r] >> (8 * (f / 4)); + } + const vec<Wtype, 4> v = + dequantize_fp_x4<Wtype, group_size, bits>(q, s); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant<false>{}, + b[t], + b[t + 1], + metal::bool_constant<true>{}); + } } } }
diff --git ml-explore/mlx/mlx/backend/metal/kernels/quantized_nax.h Layr-Labs/mlx/mlx/backend/metal/kernels/quantized_nax.h index c75f6a39745d5d6b8871de01cb5b4fc5ad8d9d72..035d0da2ef509a408c5335115bd748f9000b171c 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/quantized_nax.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/quantized_nax.h @@ -9,6 +9,7 @@ constant bool align_M [[function_constant(200)]]; constant bool align_N [[function_constant(201)]]; constant bool align_K [[function_constant(202)]]; +constant bool use_ksplit [[function_constant(203)]];   using namespace metal;   @@ -18,7 +19,7 @@ MLX_MTL_CONST int SIMD_SIZE = 32; MLX_MTL_CONST int QUAD_SIZE = 4;   template <int bits, int wsize = 8> -inline constexpr short get_pack_factor() { +inline constexpr short get_affine_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); }   @@ -29,7 +30,7 @@ return power_of_2_bits ? (wsize / 8) : (bits == 5 ? 5 : 3); }   template <typename T, typename U, int values_per_thread, int bits> -inline U load_vector(const device T* x, thread U* x_thread) { +inline U nax_load_vector(const device T* x, thread U* x_thread) { static_assert( bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -123,7 +124,7 @@ return sum; }   template <typename T, typename U, int values_per_thread, int bits> -inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { +inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -685,7 +686,7 @@ short reduction_dim, short tgp_size, short group_size, short bits> -struct QuantizedBlockLoader { +struct AffineQuantizedNAXBlockLoader { static_assert( BCOLS <= group_size, "The group size should be larger than the columns"); @@ -697,7 +698,7 @@ bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}");   - MLX_MTL_CONST short pack_factor = get_pack_factor<bits, 8>(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor<bits, 8>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -718,7 +719,7 @@ const device uint8_t* src; const device T* scales; const device T* biases;   - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -759,7 +760,7 @@ if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; }   - if (bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -769,11 +770,17 @@ T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize<T, pack_factor, bits>( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize<T, pack_factor, bits>( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } }   @@ -806,7 +813,7 @@ short dst_ld, short reduction_dim, short tgp_size, short bits> -struct QuantizedBlockLoader< +struct AffineQuantizedNAXBlockLoader< T, BROWS, BCOLS, @@ -825,7 +832,7 @@ bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}");   - MLX_MTL_CONST short pack_factor = get_pack_factor<bits, 8>(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor<bits, 8>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = @@ -851,7 +858,7 @@ const device uint8_t* src; const device T* scales; const device T* biases;   - QuantizedBlockLoader( + AffineQuantizedNAXBlockLoader( const device uint8_t* src_, const device T* scales_, const device T* biases_, @@ -892,7 +899,7 @@ if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; }   - if (bi >= src_tile_dim.y) { + if (bi >= src_tile_dim.y || bj * pack_factor >= src_tile_dim.x) { for (int i = 0; i < n_reads * pack_factor; i++) { dst[i] = T(0); } @@ -902,11 +909,17 @@ T scale = *scales; T bias = *biases; for (int i = 0; i < n_reads; i++) { - dequantize<T, pack_factor, bits>( - (device uint8_t*)(src + i * bytes_per_pack), - scale, - bias, - dst + i * pack_factor); + if ((bj + i) * pack_factor < src_tile_dim.x) { + dequantize<T, pack_factor, bits>( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } else { + for (int p = 0; p < pack_factor; p++) { + dst[i * pack_factor + p] = T(0); + } + } } }   @@ -1024,10 +1037,11 @@ } y += tid.z * output_stride; }   -// QuantizedBlockLoader's thread mapping split into two steps: fetch() reads the -// packed words and the group's scale and bias for one BK step into registers, -// store() dequantizes them into threadgroup memory. Fetching step k + 1 before -// the MMAs of step k hides the device reads behind the matrix work. +// AffineQuantizedNAXBlockLoader's thread mapping split into two steps: fetch() +// reads the packed words and the group's scale and bias for one BK step into +// registers, store() dequantizes them into threadgroup memory. Fetching step +// k + 1 before the MMAs of step k hides the device reads behind the matrix +// work. template < typename T, short BROWS, @@ -1037,7 +1051,7 @@ short tgp_size, short group_size, short bits> struct QuantizedBlockLoaderStaged { - MLX_MTL_CONST short pack_factor = get_pack_factor<bits, 8>(); + MLX_MTL_CONST short pack_factor = get_affine_pack_factor<bits, 8>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>(); MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; MLX_MTL_CONST short n_reads = (BCOLS_PACKED * BROWS) / tgp_size; @@ -1112,6 +1126,178 @@ } } };   +// With M <= SM, qmm_t_nax_staged_impl leaves every simdgroup but the first +// without rows. Here all simdgroups take the same rows, and simdgroup g takes +// the 16 columns [16 g, 16 g + 16) of every BK step, so each one issues a +// quarter of the MMAs. The partial tiles are added in simdgroup order in +// threadgroup memory at the end (fp32 throughout; only the summation order +// differs from the staged impl). +template < + typename T, + int group_size, + int bits, + typename U, + int BM, + int BK, + int BN, + int SM> +METAL_FUNC void qmm_t_nax_staged_ksplit_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device U* y, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const constant int& M, + const int k_end, + uint3 tid, + uint simd_gid, + uint simd_lid) { + constexpr int WM = BM / SM; + static_assert(WM * 16 == BK, "One 16-column K slice per simdgroup"); + + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); + constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int tile_size = BN * BK_padded; + constexpr int n_frags = BN / 16; + constexpr int frag_elems = BaseNAXFrag::kElemsPerFrag; + static_assert( + (WM - 1) * n_frags * SIMD_SIZE * frag_elems * sizeof(float) <= + 2 * tile_size * sizeof(T), + "The partial tiles fit the weight buffers"); + + using loader_w_t = QuantizedBlockLoaderStaged< + T, + BN, + BK, + BK_padded, + WM * SIMD_SIZE, + group_size, + bits>; + using frag_t = typename BaseNAXFrag::template dtype_frag_t<T>; + + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + + loader_w_t loader_w( + (const device uint8_t*)w + y_col * K_w, + scales + y_col * K_g, + biases + y_col * K_g, + K, + simd_gid, + simd_lid); + + const int tile_rows = min(BM, M - y_row); + const int ks = 16 * int(simd_gid); + const short2 sc = BaseNAXFrag::get_coord(); + const int r0 = min(int(sc.y), tile_rows - 1); + const int r1 = min(int(sc.y) + 8, tile_rows - 1); + const device T* x0 = x + (y_row + r0) * static_cast<int64_t>(K) + ks + sc.x; + const device T* x1 = x + (y_row + r1) * static_cast<int64_t>(K) + ks + sc.x; + + NAXTile<float, 1, BN / 16> Dtile; + Dtile.clear(); + + loader_w.fetch(0); + loader_w.store(Ws); + vec<T, 4> a_cur0 = *(const device vec<T, 4>*)x0; + vec<T, 4> a_cur1 = *(const device vec<T, 4>*)x1; + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int k = 0, it = 0; k < k_end; k += BK, it++) { + const bool more = k + BK < k_end; + if (more) { + loader_w.fetch(k + BK); + } + const int kn = more ? k + BK : k; + const vec<T, 4> a_next0 = *(const device vec<T, 4>*)(x0 + kn); + const vec<T, 4> a_next1 = *(const device vec<T, 4>*)(x1 + kn); + frag_t a; + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + a[c] = a_cur0[c]; + a[4 + c] = a_cur1[c]; + } + const threadgroup T* ws = + Ws + (it & 1) * tile_size + sc.y * BK_padded + sc.x + ks; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < BN / 16; j += 2) { + const threadgroup T* p0 = ws + (j * 16) * BK_padded; + const threadgroup T* p1 = p0 + 16 * BK_padded; + frag_t b0; + frag_t b1; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const vec<T, 4> u0 = + *(const threadgroup vec<T, 4>*)(p0 + h * 8 * BK_padded); + const vec<T, 4> u1 = + *(const threadgroup vec<T, 4>*)(p1 + h * 8 * BK_padded); + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + b0[h * 4 + c] = u0[c]; + b1[h * 4 + c] = u1[c]; + } + } + BaseNAXFrag::mma( + Dtile.frag_at(0, j), + Dtile.frag_at(0, j + 1), + a, + metal::bool_constant<false>{}, + b0, + b1, + metal::bool_constant<true>{}); + } + a_cur0 = a_next0; + a_cur1 = a_next1; + if (more) { + loader_w.store(Ws + ((it + 1) & 1) * tile_size); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // The loop's last barrier ends every read of Ws: it holds the partials. + threadgroup float* part = (threadgroup float*)Ws; + if (simd_gid > 0) { + threadgroup float* p = part + + ((int(simd_gid) - 1) * n_frags * SIMD_SIZE + simd_lid) * frag_elems; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < n_frags; f++) { + STEEL_PRAGMA_UNROLL + for (short e = 0; e < frag_elems; e++) { + p[f * SIMD_SIZE * frag_elems + e] = Dtile.frag_at(0, f)[e]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_gid > 0) { + return; + } + STEEL_PRAGMA_UNROLL + for (short g = 0; g < WM - 1; g++) { + const threadgroup float* p = + part + (g * n_frags * SIMD_SIZE + simd_lid) * frag_elems; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < n_frags; f++) { + STEEL_PRAGMA_UNROLL + for (short e = 0; e < frag_elems; e++) { + Dtile.frag_at(0, f)[e] += p[f * SIMD_SIZE * frag_elems + e]; + } + } + } + + y += y_row * static_cast<int64_t>(N) + y_col; + if (tile_rows == SM) { + Dtile.store(y, N); + } else { + Dtile.store_safe(y, N, short2(BN, tile_rows)); + } +} + // Each simdgroup computes SM rows and prefetches the next activation tile. // Weights use two threadgroup buffers with one barrier between K steps. template < @@ -1142,7 +1328,7 @@ static_assert(SM > 0 && SM % 16 == 0 && BM % SM == 0, "Whole row fragments"); static_assert( sizeof(T) == 2, "Two tiles fit threadgroup memory for 16-bit T");   - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int tile_size = BN * BK_padded; @@ -1157,6 +1343,17 @@ group_size, bits>; using frag_t = typename BaseNAXFrag::template dtype_frag_t<T>;   + // At most SM rows in all: split each BK step over the simdgroups instead + // unless disabled by the host (MLX_NAX_KSPLIT=0 or + // MLX_QMV_BATCH_INVARIANT=1). + if constexpr ((BM / SM) * 16 == BK) { + if ((!is_function_constant_defined(use_ksplit) || use_ksplit) && M <= SM) { + qmm_t_nax_staged_ksplit_impl<T, group_size, bits, U, BM, BK, BN, SM>( + w, scales, biases, x, y, Ws, K, N, M, k_end, tid, simd_gid, simd_lid); + return; + } + } + const int K_w = K * bytes_per_pack / pack_factor; const int K_g = K / group_size; const int y_row = tid.y * BM; @@ -1318,12 +1515,12 @@ static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE");   (void)lid;   - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   constexpr int BK_padded = (BK + 16 / sizeof(T));   - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BN, BK, @@ -1462,12 +1659,12 @@ static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE");   - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   constexpr int BN_padded = (BN + 16 / sizeof(T));   - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, BK, BN, @@ -1656,7 +1853,7 @@ uint lid [[thread_index_in_threadgroup]], uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { constexpr int BK_padded = (BK + 16 / sizeof(T)); - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>();   threadgroup T Ws[(WN == 1 ? 2 : 1) * BN * BK_padded]; @@ -1936,12 +2133,12 @@ const constant int& num_groups [[buffer(9)]], uint3 tid [[threadgroup_position_in_grid]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint simd_lane_id [[thread_index_in_simdgroup]]) { - constexpr int pack_factor = get_pack_factor<bits, 8>(); + constexpr int pack_factor = get_affine_pack_factor<bits, 8>(); constexpr int bytes_per_pack = get_bytes_per_pack<bits>(); constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int BN_padded = (BN + 16 / sizeof(T));   - using loader_w_t = QuantizedBlockLoader< + using loader_w_t = AffineQuantizedNAXBlockLoader< T, transpose ? BN : BK, transpose ? BK : BN, @@ -2011,8 +2208,6 @@ constexpr short BC = transpose ? TK : TN;   using AccumType = float;   - const bool sg_active = sgp_sm > 0; - NAXTile<AccumType, TM, TN> Dtile; Dtile.clear();   @@ -2043,33 +2238,31 @@ threadgroup_barrier(mem_flags::mem_threadgroup);   STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile<T, TM, TK> Atile; - NAXTile<T, BR, BC> Btile; + NAXTile<T, TM, TK> Atile; + NAXTile<T, BR, BC> Btile;   - volatile int compiler_barrier; + volatile int compiler_barrier;   - if constexpr (kAlignedM.value) { - Atile.load(xn + kk1, K); - } else { - Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); - } + if constexpr (kAlignedM.value) { + Atile.load(xn + kk1, K); + } else { + Atile.load_safe(xn + kk1, K, short2(SK, sgp_sm)); + }   - if constexpr (transpose) { - Btile.template load<T, BK_padded, 1>(Ws + tn * BK_padded + kk1); - } else { - Btile.template load<T, BN_padded, 1>(Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load<T, BK_padded, 1>(Ws + tn * BK_padded + kk1); + } else { + Btile.template load<T, BN_padded, 1>(Ws + tn + kk1 * BN_padded); + }   - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant<false>{}, - Btile, - metal::bool_constant<transpose>{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<false>{}, + Btile, + metal::bool_constant<transpose>{});   - (void)compiler_barrier; - } + (void)compiler_barrier; }   xn += BK; @@ -2083,30 +2276,28 @@ threadgroup_barrier(mem_flags::mem_threadgroup);   STEEL_PRAGMA_NO_UNROLL for (int kk1 = 0; kk1 < BK; kk1 += SK) { - if (sg_active) { - NAXTile<T, TM, TK> Atile; - NAXTile<T, BR, BC> Btile; + NAXTile<T, TM, TK> Atile; + NAXTile<T, BR, BC> Btile;   - volatile int compiler_barrier; + volatile int compiler_barrier;   - const short psk = min(int(SK), max(0, (k_remain - kk1))); - Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + const short psk = min(int(SK), max(0, (k_remain - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm));   - if constexpr (transpose) { - Btile.template load<T, BK_padded, 1>(Ws + tn * BK_padded + kk1); - } else { - Btile.template load<T, BN_padded, 1>(Ws + tn + kk1 * BN_padded); - } + if constexpr (transpose) { + Btile.template load<T, BK_padded, 1>(Ws + tn * BK_padded + kk1); + } else { + Btile.template load<T, BN_padded, 1>(Ws + tn + kk1 * BN_padded); + }   - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant<false>{}, - Btile, - metal::bool_constant<transpose>{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant<false>{}, + Btile, + metal::bool_constant<transpose>{});   - (void)compiler_barrier; - } + (void)compiler_barrier; } }
diff --git ml-explore/mlx/python/tests/test_quantized.py Layr-Labs/mlx/python/tests/test_quantized.py index 429d583f62c3899ebd98832515a9b875d95f539b..289d29c0157f8c5607df6d0d4a344a0a6baca9b2 100644 --- ml-explore/mlx/python/tests/test_quantized.py +++ Layr-Labs/mlx/python/tests/test_quantized.py @@ -449,6 +449,18 @@ global_scale=global_scale_w, )   expected = x_hat @ mx.swapaxes(w_hat, -1, -2) + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.qqmm( + x, + w_q, + scales, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + continue actual = mx.qqmm( x, w_q, @@ -1055,6 +1067,18 @@ global_scale=global_scale_x, dtype=dtype, ) expected = x_hat.astype(mx.float32) @ w_hat.T + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.qqmm( + x, + q, + s, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + continue actual = mx.qqmm( x, q, @@ -2361,6 +2385,80 @@ self.assertTrue(mx.allclose(y1, y2, atol=tol)) self.assertTrue(mx.allclose(y1, y3, atol=tol)) self.assertTrue(mx.allclose(y1, y4, atol=tol))   + def test_cpu_quantized_accumulation_modes_and_orientations(self): + with mx.stream(mx.cpu): + for mode, dtype, transpose, k in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.bfloat16, mx.float16, mx.float32], + [False, True], + [96, 3072], + ): + with self.subTest(mode=mode, dtype=dtype, transpose=transpose, k=k): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + x = mx.full((1, k), 3, dtype=dtype) + weights = mx.full((32, k) if transpose else (k, 32), 2, dtype=dtype) + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 code 64 is exactly 2. + packed = ( + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 8), + 0x22222222, + dtype=mx.uint32, + ), + mx.full( + (*weights.shape[:-1], weights.shape[-1] // 16), + 64, + dtype=mx.uint8, + ), + ) + else: + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + dequantized = mx.dequantize( + *packed, group_size=group_size, bits=bits, mode=mode + ) + reference = x @ (dequantized.T if transpose else dequantized) + expected = mx.full((1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + actual = mx.quantized_matmul( + x, + *packed, + transpose=transpose, + group_size=group_size, + bits=bits, + mode=mode, + ) + self.assertTrue(mx.array_equal(actual, expected)) + + def test_affine_qmm_cpu_low_precision_accumulation(self): + with mx.stream(mx.cpu): + for dtype, bits, k in product( + [mx.bfloat16, mx.float16, mx.float32], [3, 4, 6], [96, 128] + ): + with self.subTest(dtype=dtype, bits=bits, k=k): + x = mx.full((1, 1, k), 3, dtype=dtype) + weights = mx.full((1, 32, k), 2, dtype=dtype) + packed = mx.quantize(weights, group_size=32, bits=bits) + reference = x @ mx.swapaxes( + mx.dequantize(*packed, group_size=32, bits=bits), -1, -2 + ) + expected = mx.full((1, 1, 32), 6 * k, dtype=dtype) + self.assertTrue(mx.array_equal(reference, expected)) + for sorted_indices in [False, True]: + actual = mx.gather_qmm( + x, + *packed, + rhs_indices=mx.array([0], dtype=mx.uint32), + group_size=32, + bits=bits, + sorted_indices=sorted_indices, + ) + self.assertTrue(mx.array_equal(actual, expected)) + actual = mx.quantized_matmul(x, *packed, group_size=32, bits=bits) + self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_gather_qmm_sorted_nax_large_m(self): E, N, K, group_size = 16, 64, 64, 32 @@ -2405,6 +2503,68 @@ self.assertLess(float(max_error.item()), 5e-2) del y_q, max_error   @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") + @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") + def test_gather_qmm_sorted_partial_tiles(self): + # Exact sums expose reading a following row as reduction-tile padding. + counts = [17, 3, 31, 14] + indices = [expert for expert, count in enumerate(counts) for _ in range(count)] + rhs = mx.array(indices, dtype=mx.uint32) + experts = [0.25, 0.5, 1.0, 2.0] + for mode, dtype, k, n in product( + ["affine", "mxfp4", "mxfp8", "nvfp4"], + [mx.float16, mx.bfloat16], + [32, 64, 96, 128], + [32, 96], + ): + with self.subTest(mode=mode, dtype=dtype, k=k, n=n): + group_size = 16 if mode == "nvfp4" else 32 + bits = 8 if mode == "mxfp8" else 4 + if mode == "nvfp4": + # E2M1 code 2 is 1; E4M3 scales are 1/4, 1/2, 1, 2. + wq = mx.full((4, n, k // 8), 0x22222222, dtype=mx.uint32) + scales = mx.broadcast_to( + mx.array([40, 48, 56, 64], dtype=mx.uint8)[:, None, None], + (4, n, k // 16), + ) + packed = (wq, scales) + else: + weights = mx.broadcast_to( + mx.array(experts, dtype=dtype)[:, None, None], (4, n, k) + ) + packed = mx.quantize( + weights, group_size=group_size, bits=bits, mode=mode + ) + for poison in [False, True]: + rows = [ + float("nan") if poison and i % 2 else float(i % 3 + 1) + for i in range(len(indices)) + ] + x = mx.broadcast_to( + mx.array(rows, dtype=dtype)[:, None, None], (len(indices), 1, k) + ) + actual = mx.gather_qmm( + mx.contiguous(x), + *packed, + rhs_indices=rhs, + transpose=True, + group_size=group_size, + bits=bits, + mode=mode, + sorted_indices=True, + ) + expected = mx.array( + [ + rows[row] * k * experts[expert] + for row, expert in enumerate(indices) + ], + dtype=dtype, + )[:, None, None] + self.assertEqual(actual.shape, (len(indices), 1, n)) + equal = (actual == expected) | ( + mx.isnan(actual) & mx.isnan(expected) + ) + self.assertTrue(mx.all(equal).item(), f"poison={poison}") + def test_gather_qmm_sorted_sliced_weight(self): E, R, D, N = 8, 64, 256, 64 dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 @@ -2709,6 +2869,12 @@ mode="nvfp4", sorted_indices=sort, )   + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.gather_qmm(x, wq, s, global_scale=gs, **kwargs) + continue + out = mx.gather_qmm(x, wq, s, global_scale=gs, **kwargs) tol = ( 1e-5 if dtype == mx.float32 and not mx.cuda.is_available() else 3e-2 @@ -2732,15 +2898,18 @@ indices = mx.array([3, 0, 5, 3, 1, 0], mx.uint32) x = (mx.random.normal((2, 1, K)) / K**0.5).astype(mx.bfloat16) lhs = mx.array([0, 1, 0, 1, 0, 1], mx.uint32) expected = x[lhs] @ w_hat[indices].swapaxes(-1, -2) - out = mx.gather_qmm( - x, - wq, - s, + kwargs = dict( lhs_indices=lhs, rhs_indices=indices, mode="nvfp4", global_scale=gs, ) + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.gather_qmm(x, wq, s, **kwargs) + continue + out = mx.gather_qmm(x, wq, s, **kwargs) self.assertLess(rel_err(out, expected), 3e-2)   def test_quantize_strided(self):

Scalar affine, MXFP4, MXFP8 and NVFP4 matrix products accumulate in FP32 and convert once when writing each output. Both matrix orientations and the FP group sum preserve partial sums instead of rounding every addition to BF16 or FP16. Exact CPU regressions compare constant products with dequantized matmul, including sorted and unsorted gathered affine paths. Quantization, packing, indexing and Metal kernels remain unchanged.

diff --git ml-explore/mlx/mlx/backend/cpu/quantized.cpp Layr-Labs/mlx/mlx/backend/cpu/quantized.cpp index f029561c7832ecb93c4eba70a84962243af5f98b..3f03608c85fde6a4d6318d5c432ec1a91ed79502 100644 --- ml-explore/mlx/mlx/backend/cpu/quantized.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/quantized.cpp @@ -108,15 +108,16 @@ constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int bytes_per_pack = get_bytes_per_pack(bits); constexpr int packs_in_group = group_size / pack_factor;   + std::vector<float> sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const T* scales_local = scales; const T* biases_local = biases;   - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0);   for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++;   for (int n = 0; n < N; n += group_size) { @@ -147,6 +148,7 @@ } } }   + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -174,7 +176,7 @@ const T* biases_local = biases;   for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = *scales_local++; T bias = *biases_local++; @@ -463,14 +465,15 @@ int K) { constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor;   + std::vector<float> sums(N); for (int m = 0; m < M; m++) { const uint8_t* w_local = (const uint8_t*)w; const uint8_t* scales_local = scales;   - std::fill(result, result + N, 0); + std::fill(sums.begin(), sums.end(), 0);   for (int k = 0; k < K; k++) { - T* result_local = result; + float* result_local = sums.data(); T xi = *x++;   for (int n = 0; n < N; n += group_size) { @@ -489,6 +492,7 @@ w_local++; } } } + std::copy(sums.begin(), sums.end(), result); result += N; } } @@ -511,11 +515,11 @@ const uint8_t* scales_local = scales;   for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; for (int k = 0; k < K; k += group_size) { T scale = dequantize_scale<T, group_size>(*scales_local++);   - T gsum = 0; + float gsum = 0; for (int kw = 0; kw < packs_in_group; kw++) { if constexpr (bits == 4) { gsum += (*x_local++) * static_cast<T>(FP4_LUT[w_local[0] & 0xf]);

The fork reverts one upstream change in two NAX kernels: the simdgroup skip of ml-explore/mlx#4352 (c7ff35d9, kept by ml-explore/mlx#4572 as sg_active = sgp_sm > 0). fp_gather_qmm_rhs_nax and affine_gather_qmm_rhs_nax run the MMA in every simdgroup. With the skip, mixture-of-experts serving on a two-Mac JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB wired until a reboot. Stores stay bounded by sgp_sm, so the output does not change. Keep the revert at every upstream merge. Upstream added the row-tile scheduling of #4567 and #4572, which the fork had carried as a backport in PR #27, so only this revert remains.

Two M5-series NAX quantized Metal kernel optimizations ported from the Muse Glimmer 30B challenge line (Layr-Labs/mlxfast-muse-glimmer-30b-engine commits 80b35945 and 9976cc74): - qmm_t_nax_staged_ksplit_impl in quantized_nax.h: when M <= SM (M <= 16, reachable at 8 <= M <= 16 on M5+ NAX via qmm_splitk_nax and qmm_nax) and (BM / SM) * 16 == BK (BM=64, BK=64, BN=64, WM=4, WN=1), splits each BK step into 16-column slices across all 4 simdgroups instead of leaving 3 simdgroups idle, then reduces FP32 partial tiles in simdgroup order in threadgroup memory (FP32 throughout; changes only K-reduction summation order for 8 <= M <= 16 affine 16-bit products on NAX). Gated via Metal function constant use_ksplit (index 203) through use_qmm_nax_ksplit(allow_ksplit) (MLX_NAX_KSPLIT, opt-in default 0; disabled when MLX_QMV_BATCH_INVARIANT=1 or allow_ksplit=false for prefill-row invariance coordination with #71). - FPQuantizedNAXBlockLoader::fetch_nvfp4 / store_nvfp4, double-buffered Ws in fp_qmm_t_impl / fp_qmm_t_nax, and bit-manipulation dequantize_fp4_x4_scaled + 6 <= M <= 8 (M <= 8) peeled 1-ahead prefetch in fp_qmv_nax (fp_quantized_nax.h): vectorizes NVFP4 (bits == 4, group_size == 16, !has_global_scale, 16-bit Ws storage width Wtype = bfloat across fp_qmm_t_nax, fp_gather_qmm_t_nax, and fp_gather_qmm_rhs_nax for all activation dtypes, plus 16-bit fp_qmm_n_nax when instantiated) weight/scale loads and half2 E2M1 dequantization (0-ULP bit-identical to stock over all 4,096 (fp8_e4m3, fp4_e2m1) pairs), guarded by K > 0, K % 32 == 0, and 16B wl / 2B scales alignment checks. - tests/nax_quantized_kernel_tests.cpp logs GPU architecture and NAX status, covers M5-routed affine K-split (split-K and direct staged, asserting bitwise prefix parity when K-split is off and bitwise K-split dispatch on NAX when MLX_NAX_KSPLIT=1 via the nax_ksplit_enabled ctest entry), unbatched/batched double-buffered NVFP4 GEMM, 6 <= M <= 8 peeled QMV, NVFP4 MoE gather (fp_gather_qmm_t_nax and fp_gather_qmm_rhs_nax), and genuinely misaligned 4B/1B offset fallback bitwise parity.

diff --git ml-explore/mlx/tests/nax_quantized_kernel_tests.cpp Layr-Labs/mlx/tests/nax_quantized_kernel_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fd1ddaec411471f2fdb82c185d298857ee51a47 --- /dev/null +++ Layr-Labs/mlx/tests/nax_quantized_kernel_tests.cpp @@ -0,0 +1,434 @@ +// Copyright © 2026 Eigen Labs. +#include <cstdlib> +#include <optional> +#include <string> +#include <utility> +#include <vector> + +#include "doctest/doctest.h" +#include "mlx/backend/metal/device.h" +#include "mlx/mlx.h" +#include "mlx/utils.h" + +using namespace mlx::core; + +namespace { + +bool same_bytes(const array& a, const array& b) { + auto bytes = [](const array& x) { + auto type = x.dtype() == float32 ? uint32 : uint16; + return view(contiguous(x, false, Device::gpu), type, Device::gpu); + }; + return array_equal(bytes(a), bytes(b), Device::cpu).item<bool>(); +} + +// Returns a row-contiguous view of `src` shifted by `elem_offset` elements in +// a freshly allocated 1D buffer so byte alignment is strictly non-multiple of +// 16 (for uint32 with elem_offset=1 -> 4B) or 2 (for uint8 with +// elem_offset=1 -> 1B). +array offset_view(const array& src, int elem_offset) { + auto flat = reshape(contiguous(src, false, Device::cpu), {-1}, Device::cpu); + auto pad = zeros({elem_offset}, src.dtype(), Device::cpu); + auto buf = concatenate({pad, flat}, 0, Device::cpu); + eval(buf); + auto shifted = slice( + buf, + {elem_offset}, + {elem_offset + static_cast<int>(src.size())}, + Device::cpu); + auto out = reshape(shifted, src.shape(), Device::cpu); + eval(out); + return out; +} + +} // namespace + +TEST_CASE("NAX affine K-split split-K and direct staged routes") { + const char* ksplit_env = std::getenv("MLX_NAX_KSPLIT"); + bool expected_ksplit = ksplit_env != nullptr && std::atoi(ksplit_env) != 0; + REQUIRE(env::nax_ksplit() == expected_ksplit); + + const bool has_nax = metal::is_nax_available(); + const auto& arch = metal::device(Device::gpu).get_architecture(); + const bool ksplit_enabled = env::nax_ksplit() && !env::qmv_batch_invariant(); + MESSAGE( + "GPU arch: ", + arch, + ", is_nax_available=", + has_nax, + ", MLX_NAX_KSPLIT=", + env::nax_ksplit(), + ", MLX_QMV_BATCH_INVARIANT=", + env::qmv_batch_invariant()); + + // Route 1: split-K NAX staged (M in 8..16, N=2048, K=2048, biases present). + // Route 2: direct qmm_nax staged (M in 13..16, N=K=4160 = 65*64 so + // K % 64 == 0, K % 128 != 0, vector_limit = 13/12, split_k = 1). + struct Shape { + int N; + int K; + std::vector<int> rows; + }; + std::vector<Shape> shapes = { + {2048, 2048, {8, 12, 16, 17}}, + {4160, 4160, {13, 16, 17}}, + }; + + for (const auto& shape : shapes) { + for (auto dtype : {bfloat16, float16}) { + CAPTURE(shape.N); + CAPTURE(shape.K); + CAPTURE(dtype); + + auto w = astype( + random::uniform( + -0.5f, + 0.5f, + {shape.N, shape.K}, + float32, + random::key(101 + shape.N), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 64, 4, "affine", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + q[2], + 64, + 4, + "affine", + std::nullopt, + float32, + Device::cpu); + eval(q[0], q[1], q[2], dq); + + int max_m = shape.rows.back(); + auto x_all = astype( + random::uniform( + -0.5f, + 0.5f, + {max_m, shape.K}, + float32, + random::key(202 + shape.N), + Device::cpu), + dtype, + Device::cpu); + eval(x_all); + + auto out_max = quantized_matmul( + x_all, q[0], q[1], q[2], true, 64, 4, "affine", Device::gpu); + eval(out_max); + + double tol = dtype == bfloat16 ? 8e-2 : 2e-2; + for (int m : shape.rows) { + CAPTURE(m); + auto x = slice(x_all, {0, 0}, {m, shape.K}, Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], q[2], true, 64, 4, "affine", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item<bool>()); + + if (m < max_m) { + auto expected_rows = + slice(out_max, {0, 0}, {m, shape.N}, Device::gpu); + if (!ksplit_enabled) { + // When K-split is disabled (default MLX_NAX_KSPLIT=0 or + // MLX_QMV_BATCH_INVARIANT=1), the direct staged route (N=K=4160, + // M >= 13) uses the identical unsplit staged kernel for M <= 16 + // and M = 17, so prefix rows must match bitwise. On NAX with + // !MLX_QMV_BATCH_INVARIANT, split-K (N=K=2048) also keeps the same + // split_k and unsplit staged loop across M=8..17. + if (shape.N == 4160 || + (has_nax && !env::qmv_batch_invariant() && shape.N == 2048)) { + CHECK(same_bytes(actual, expected_rows)); + } + } else if (has_nax) { + // On NAX hardware with MLX_NAX_KSPLIT=1 and batch invariance off, + // M <= 16 must dispatch qmm_t_nax_staged_ksplit_impl (4-way K-split + // reduction order), which differs bitwise from the M = 17 unsplit + // staged loop and proves the NAX K-split kernel actually ran. + CHECK_FALSE(same_bytes(actual, expected_rows)); + } + } + } + } + } +} + +TEST_CASE( + "NAX NVFP4 double-buffered GEMM, peeled QMV, gather MoE, and misaligned fallback") { + MESSAGE( + "GPU arch: ", + metal::device(Device::gpu).get_architecture(), + ", is_nax_available=", + metal::is_nax_available()); + for (auto dtype : {bfloat16, float16}) { + CAPTURE(dtype); + double tol = dtype == bfloat16 ? 1e-1 : 3e-2; + + // 1. Unbatched double-buffered fp_qmm_t_nax (M=512, N=1024 -> 512 tiles -> + // split_k <= 1 -> routes directly to qmm_nax on M5). + { + int M = 512, N = 1024, K = 256; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {N, K}, float32, random::key(301), Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, 0.5f, {M, K}, float32, random::key(302), Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item<bool>()); + } + + // 2. Batched double-buffered fp_qmm_t_nax (B=2, M=64, aligned N=128 and + // unaligned N=96) plus genuinely misaligned 4B weight / 1B scale offset + // fallback (must match the aligned fast path bitwise). + for (int N : {128, 96}) { + CAPTURE(N); + int B = 2, M = 64, K = 128; + auto w = astype( + random::uniform( + -0.5f, + 0.5f, + {B, N, K}, + float32, + random::key(401 + N), + Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {B, M, K}, + float32, + random::key(402 + N), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + swapaxes(dq, -1, -2, Device::cpu), + Device::cpu); + auto aligned_out = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + + auto w_mis = offset_view(q[0], 1); + auto s_mis = offset_view(q[1], 1); + REQUIRE(w_mis.offset() == 4); + REQUIRE(s_mis.offset() == 1); + REQUIRE(w_mis.flags().row_contiguous); + REQUIRE(s_mis.flags().row_contiguous); + + auto fallback_out = quantized_matmul( + x, w_mis, s_mis, std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, aligned_out, fallback_out); + CHECK(allclose( + astype(aligned_out, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item<bool>()); + CHECK(same_bytes(aligned_out, fallback_out)); + } + + // 3. Peeled fp_qmv_nax (6 <= M <= 8) and unpeeled fp_qmv_nax (M = 9). + { + int N = 2048, K = 2048; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {N, K}, float32, random::key(501), Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + eval(q[0], q[1], dq); + for (int m : {6, 7, 8, 9}) { + CAPTURE(m); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {m, K}, + float32, + random::key(510 + m), + Device::cpu), + dtype, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item<bool>()); + } + } + + // 4. NVFP4 MoE gather paths (fp_gather_qmm_t_nax for sorted=false, + // fp_gather_qmm_rhs_nax for sorted=true) + misaligned bitwise parity. + { + int E = 4, M = 64, N = 128, K = 128; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {E, N, K}, float32, random::key(601), Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {M, 1, 1, K}, + float32, + random::key(602), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + + auto w_mis = offset_view(q[0], 1); + auto s_mis = offset_view(q[1], 1); + REQUIRE(w_mis.offset() == 4); + REQUIRE(s_mis.offset() == 1); + + std::vector<uint32_t> idx_vals(M); + for (int i = 0; i < M; ++i) { + idx_vals[i] = static_cast<uint32_t>(i / (M / E)); + } + auto rhs_sorted = array(idx_vals.data(), {M, 1}, uint32); + auto rhs_unsorted = random::randint( + array(0), array(E), {M, 1}, uint32, random::key(603), Device::cpu); + eval(q[0], q[1], dq, x, w_mis, s_mis, rhs_sorted, rhs_unsorted); + + for (bool sorted : {false, true}) { + CAPTURE(sorted); + auto rhs = sorted ? rhs_sorted : rhs_unsorted; + auto out_aligned = gather_qmm( + x, + q[0], + q[1], + std::nullopt, + std::nullopt, + rhs, + true, + 16, + 4, + "nvfp4", + std::nullopt, + sorted, + Device::gpu); + auto out_fallback = gather_qmm( + x, + w_mis, + s_mis, + std::nullopt, + std::nullopt, + rhs, + true, + 16, + 4, + "nvfp4", + std::nullopt, + sorted, + Device::gpu); + auto w_gathered = + take(dq, squeeze(rhs, 1, Device::cpu), 0, Device::cpu); + auto ref = matmul( + reshape(astype(x, float32, Device::cpu), {M, 1, K}, Device::cpu), + swapaxes(w_gathered, -1, -2, Device::cpu), + Device::cpu); + ref = reshape(ref, {M, 1, 1, N}, Device::cpu); + eval(out_aligned, out_fallback, ref); + CHECK(allclose( + astype(out_aligned, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item<bool>()); + CHECK(same_bytes(out_aligned, out_fallback)); + } + } + } +}

Upstream’s head-dim split attention (attention_nax_dsplit, the NAX full-attention kernel for head dims 256 and 512) has no BV template parameter: its value width is BD. The precompiled instances (instantiate_attn_dsplit) leave BV out, but the run-time (JIT) build passed the template arguments of attention_nax, BV included, so every value after BD moved one parameter to the left and the source did not compile (“Unable to build metal library from source”). A JIT build (mlx-swift builds this way) therefore failed every head-dim 256 or 512 prefill that takes the NAX full-attention kernel. get_steel_attention_nax_kernel now leaves BV out for the split kernel. Builds with the precompiled library did not have the bug, and the kernel names do not change.

The JACCL ring computes each wire’s byte offset as lr * n_wires * size. Upstream multiplies lr and n_wires as int before the product widens to 64 bits, and compares size_ * 2 * n_conns_ as int. The fork widens the first operand to int64_t, so each product is computed in 64 bits. The values are small, so the result does not change. The vector SDPA path checks a query layout with strides[2] == shape[3] * shape[bidx], where the product is int and the stride is 64-bit. The fork widens shape[3] to int64_t there too. These changes close the CodeQL alerts cpp/integer-multiplication-cast-to-long in these files.

An empty-input CPU reduction fills its output with the operation’s identity before planning a reduction. A 4 GiB output previously reached a strided reduction whose 32-bit loop counter wrapped to zero and wrote past the buffer. The existing large-output regression and empty-array identity tests cover this.

diff --git ml-explore/mlx/mlx/backend/cpu/reduce.cpp Layr-Labs/mlx/mlx/backend/cpu/reduce.cpp index cd4911e898550f7e959126d6fa095d7e77e4a2da..d337626cc954e79c5ed3c6f9932a3c70bd3b5d84 100644 --- ml-explore/mlx/mlx/backend/cpu/reduce.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/reduce.cpp @@ -158,6 +158,12 @@ const array& x, array& out, const std::vector<int>& axes, U init) { + if (x.size() == 0) { + if (out.size() > 0) { + std::fill_n(out.data<U>(), out.size(), init); + } + return; + } ReductionPlan plan = get_reduction_plan(x, axes);   auto in_ptr = x.data<T>();

The CPU QQMatmul kernel has no global scale input. Upstream passes the scales to it, and the kernel ignores them, so qqmm with global_scale_x and global_scale_w on a CPU stream returns a wrong result with no error (upstream marks this as a TODO in test_quantized.py). The fork’s CPU test pass found it: the error was about 1000 against a tolerance of 1e-3. qqmm now raises “Global scale is only supported on the GPU” on a stream that is not a GPU stream, as gather_qmm already does.

The CPU backend calls BLAS gemm with beta = 0 in five places: the float32, float64 and complex64 matmul wrappers in gemms/cblas.cpp (used by Matmul, AddMM and SegmentedMM), BlockMaskedMM and GatherMM in masked_mm.cpp, and the two explicit-gemm convolutions in conv.cpp. BLAS must not read C when beta is 0, but Accelerate can (seen with M = 1). An output buffer from the allocator cache can hold old data, for example packed fp4 weights that read as NaN, and NaN * 0 is NaN. Upstream’s test_fp_gather_qmm_non_multiple_of_32 found it in the fork’s CPU test pass: its float32 reference x @ w_sel reused the 266240-byte buffer of the previous subtest’s packed weights. One helper, clear_gemm_output in gemm.h, fills the exact C region of each call (rows by columns, with its ldc) with zeros before the call. MLX’s own SIMD gemm already skips C when beta is 0. This is a latent upstream bug.

diff --git ml-explore/mlx/mlx/backend/cpu/conv.cpp Layr-Labs/mlx/mlx/backend/cpu/conv.cpp index 442629fbeae085c3151618b7f206c958a8151535..16b32e1c6bf1dc5d8af88f59b72447235d132b4e 100644 --- ml-explore/mlx/mlx/backend/cpu/conv.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/conv.cpp @@ -5,6 +5,7 @@ #include <numeric>   #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/gemm.h" #include "mlx/backend/cpu/lapack.h" #include "mlx/primitives.h" #include "mlx/utils.h" @@ -916,6 +917,8 @@ O_per_group, C_per_group]() { for (int g = 0; g < groups; ++g) { // Perform gemm + clear_gemm_output( + gemm_out_ptr + g * O_per_group, strided_reshape, O_per_group, O); cblas_sgemm( CblasRowMajor, CblasNoTrans, // no trans A @@ -1086,6 +1089,7 @@ gemm_out_ptr = gemm_out.data<float>(), strided_reshape = std::move(strided_reshape), O]() { // Perform gemm + clear_gemm_output(gemm_out_ptr, strided_reshape[0], O, O); cblas_sgemm( CblasRowMajor, CblasNoTrans, // no trans A
diff --git ml-explore/mlx/mlx/backend/cpu/gemm.h Layr-Labs/mlx/mlx/backend/cpu/gemm.h index d665cb91ffe037f3ef07422abbfcdff5fb4c25bb..b8689a41abfa26d2944b66de67e3a41e4aa73f4e 100644 --- ml-explore/mlx/mlx/backend/cpu/gemm.h +++ Layr-Labs/mlx/mlx/backend/cpu/gemm.h @@ -1,9 +1,21 @@ // Copyright © 2025 Apple Inc.   #pragma once +#include <algorithm> + #include "mlx/array.h"   namespace mlx::core { + +// A BLAS gemm with beta = 0 must not read C, but Accelerate can (seen with +// M = 1). A buffer from the allocator cache can hold NaN, and NaN * 0 is NaN. +// Call this on the C region of every BLAS gemm with beta = 0. +template <typename T> +inline void clear_gemm_output(T* c, size_t rows, size_t cols, size_t ldc) { + for (size_t r = 0; r < rows; ++r) { + std::fill_n(c + r * ldc, cols, T(0)); + } +}   template <typename T> void matmul(
diff --git ml-explore/mlx/mlx/backend/cpu/gemms/cblas.cpp Layr-Labs/mlx/mlx/backend/cpu/gemms/cblas.cpp index 765e9f539ac13f19b6bac9da635afc4d26faf195..f12542fbed07a16e8c5436866e0486b5212dbc10 100644 --- ml-explore/mlx/mlx/backend/cpu/gemms/cblas.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/gemms/cblas.cpp @@ -29,6 +29,9 @@ size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1];   for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -70,6 +73,9 @@ size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1];   for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_dgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -113,6 +119,9 @@ auto calpha = static_cast<complex64_t>(alpha); auto cbeta = static_cast<complex64_t>(beta);   for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_cgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA
diff --git ml-explore/mlx/mlx/backend/cpu/masked_mm.cpp Layr-Labs/mlx/mlx/backend/cpu/masked_mm.cpp index db38f3942450c7df336e357fed4424a548ab9fd0..89f3bd72143ea20d0f54ea0c8867a023e2ea0193 100644 --- ml-explore/mlx/mlx/backend/cpu/masked_mm.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/masked_mm.cpp @@ -325,6 +325,7 @@ b_mask_bool); }   // Do matmul + clear_gemm_output(ci, M, N, ldc); cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -469,6 +470,7 @@ i, lhs_indices_shape, lhs_indices_strides)]; uint32_t indx_B = rhs_indices_ptr[elem_to_loc( i, rhs_indices_shape, rhs_indices_strides)];   + clear_gemm_output(out_ptr + matrix_stride_out * i, M, N, ldc); cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA

Upstream ml-explore/mlx#4634 (5dbe9991) makes is_donatable() also require that MLX owns the buffer, so the allocator never reuses a wrapped external buffer. The fork’s C API (mlx_array_get_buffer_info, field unique) used is_donatable() to prove that no other array references a buffer. Callers in mlx-swift-lm use that proof for paged KV segments, checkpoint memory accounting and the MTP state, also for wrapped host pages. The fork adds array::is_uniquely_referenced(): the same reference-count test without the ownership test. is_donatable() and buffer donation do not change.

diff --git ml-explore/mlx/mlx/array.h Layr-Labs/mlx/mlx/array.h index 59ab941945e1a04e64e76af6dbd6e9895a7cfd06..43483aab4dfae3d910e3944f795b0ae4fd77ab9d 100644 --- ml-explore/mlx/mlx/array.h +++ Layr-Labs/mlx/mlx/array.h @@ -287,6 +287,13 @@ return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1) && array_desc_->data->is_owned(); }   + /** True when no other array references this array or its data. Unlike + * is_donatable(), this does not require MLX to own the buffer, so a wrapped + * external buffer can be unique. */ + bool is_uniquely_referenced() const { + return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1); + } + /** The array's siblings. */ const std::vector<array>& siblings() const { return array_desc_->siblings;

Upstream #4338 raises a CPU stream task error from synchronize, and its test expects async_eval not to throw. But StreamThread::enqueue throws the stored error on the main thread (#3742). async_eval enqueues several tasks: when the stream thread runs a failing task before async_eval enqueues the next one, that enqueue throws. This is a race. It failed test_async_eval_error_in_synchronize in the fork’s CPU test pass on some runs. async_eval now holds a scheduler::DeferStreamErrors guard, and enqueue does not throw while the guard lives on the thread. synchronize throws the error later. eval does not change. A C++ test stores the error first, so it fails without the fix on every run. The failing task waits until its completion marker is queued, so the test’s setup cannot consume the error before the async_eval assertion.

diff --git ml-explore/mlx/mlx/scheduler.cpp Layr-Labs/mlx/mlx/scheduler.cpp index 572e236bbeb0298e317f3761cee1bc47bf08b9f5..1516f8ef6074145f8add78755e2bbf41beb42531 100644 --- ml-explore/mlx/mlx/scheduler.cpp +++ Layr-Labs/mlx/mlx/scheduler.cpp @@ -39,6 +39,20 @@ }   namespace scheduler {   +namespace { + +thread_local int defer_stream_errors = 0; + +} // namespace + +DeferStreamErrors::DeferStreamErrors() { + ++defer_stream_errors; +} + +DeferStreamErrors::~DeferStreamErrors() { + --defer_stream_errors; +} + struct StreamThread { std::mutex mtx; std::queue<std::function<void()>> q; @@ -76,7 +90,7 @@ } }   void enqueue(std::function<void()> f) { - if (is_main_thread()) { + if (is_main_thread() && defer_stream_errors == 0) { error.check(); } {
diff --git ml-explore/mlx/mlx/scheduler.h Layr-Labs/mlx/mlx/scheduler.h index 7bce5a9fe68a0e99821cfb1a60932f6d86de64c0..7d9df759d4f07218a27dfb3a0ea06adc26b88016 100644 --- ml-explore/mlx/mlx/scheduler.h +++ Layr-Labs/mlx/mlx/scheduler.h @@ -37,6 +37,7 @@ void notify_new_task(const Stream& stream) { { std::lock_guard<std::mutex> lk(mtx); n_active_tasks_++; + n_active_cpu_tasks_ += stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -45,6 +46,7 @@ void notify_task_completion(const Stream& stream) { { std::lock_guard<std::mutex> lk(mtx); n_active_tasks_--; + n_active_cpu_tasks_ -= stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -53,6 +55,11 @@ int n_active_tasks() const { return n_active_tasks_; }   + // The active tasks of CPU streams; they are also in n_active_tasks(). + int n_active_cpu_tasks() const { + return n_active_cpu_tasks_; + } + void wait_for_one() { std::unique_lock<std::mutex> lk(mtx); int n_tasks_old = n_active_tasks(); @@ -69,6 +76,7 @@ StreamThread& get_thread(Stream s);   int n_active_tasks_{0}; + int n_active_cpu_tasks_{0}; std::unordered_map<int, std::unique_ptr<StreamThread>> threads_; std::shared_mutex threads_mtx_; std::condition_variable completion_cv; @@ -98,8 +106,23 @@ inline void check_error(Stream s) { scheduler().check_error(s); }   +// While an object of this class lives, enqueue on this thread does not throw +// the error that an earlier stream task stored. synchronize throws it later. +// async_eval uses it so that it never throws a stream task error. +class MLX_API DeferStreamErrors { + public: + DeferStreamErrors(); + ~DeferStreamErrors(); + DeferStreamErrors(const DeferStreamErrors&) = delete; + DeferStreamErrors& operator=(const DeferStreamErrors&) = delete; +}; + inline int n_active_tasks() { return scheduler().n_active_tasks(); +} + +inline int n_active_cpu_tasks() { + return scheduler().n_active_cpu_tasks(); }   inline void notify_new_task(const Stream& stream) {
diff --git ml-explore/mlx/tests/scheduler_tests.cpp Layr-Labs/mlx/tests/scheduler_tests.cpp index cc2228e0f361149fb1a56fe7d579032cc967a9f7..2645d670e197b84e496ed9c664539010abf6b920 100644 --- ml-explore/mlx/tests/scheduler_tests.cpp +++ Layr-Labs/mlx/tests/scheduler_tests.cpp @@ -1,5 +1,7 @@ // Copyright © 2023 Apple Inc.   +#include <future> + #include "doctest/doctest.h"   #include "mlx/mlx.h" @@ -304,3 +306,29 @@ CHECK_EQ(y.item<float>(), doctest::Approx(64 * 64 * 21.0f)); } } } + +TEST_CASE("test async_eval does not throw a stored stream error") { + // A failed CPU task stores its error in the stream. Wait for the task + // without synchronize, so the error is still stored when async_eval runs. + auto s = new_stream(Device::cpu); + auto release = std::make_shared<std::promise<void>>(); + auto can_throw = release->get_future().share(); + scheduler::enqueue(s, [can_throw]() { + can_throw.wait(); + throw std::runtime_error("task failed"); + }); + auto done = std::make_shared<std::promise<void>>(); + auto finished = done->get_future(); + scheduler::enqueue(s, [done]() { done->set_value(); }); + release->set_value(); + finished.wait(); + + auto x = add(array(1.0f), array(2.0f), s); + CHECK_NOTHROW(async_eval(x)); + CHECK_THROWS_AS(synchronize(s), std::runtime_error); + + // The error is cleared, so the stream works again. + auto y = add(array(1.0f), array(2.0f), s); + eval(y); + CHECK_EQ(y.item<float>(), 3.0f); +}

Upstream computes float16 and bfloat16 floor_divide, and the divmod quotient, as floor(a / b) in the half type. The quotient is rounded to the half type before the floor, so a true quotient that is less than half an ulp below an integer n rounds to n, and the result is n instead of n - 1. numpy’s float16 divmod computes in float32 from fmod (npy_divmodf) and gives n - 1. Upstream’s unseeded test_divmod fails for this reason in about 4% of runs per device. The fork now computes these two operations for float16 and bfloat16 in float32 with the same method as npy_divmodf (mod = fmod(a, b), div = (a - mod) / b, then a floor with the sign correction), and rounds the result once to the output type: in the Metal FloorDivide (which DivMod uses), in the CPU scalar and SIMD floor_divide, and in the CPU DivMod. float32, float64 and integer paths do not change. test_floor_divide_half_rounding_window uses pairs in the rounding window and compares with numpy on the CPU and the GPU. The CUDA kernels do not change; no workflow in this fork builds CUDA.

diff --git ml-explore/mlx/mlx/backend/cpu/binary.cpp Layr-Labs/mlx/mlx/backend/cpu/binary.cpp index 150cf58339db15dc1259b13caf4a528e736afec7..b167304b5ca4ff4fad9f90b4e4c0c2e9397c96d0 100644 --- ml-explore/mlx/mlx/backend/cpu/binary.cpp +++ Layr-Labs/mlx/mlx/backend/cpu/binary.cpp @@ -58,11 +58,23 @@ } return std::make_pair(q, r); }; auto float_op = [](auto x, auto y) { - auto r = std::fmod(x, y); - if (r != 0 && (r < 0) != (y < 0)) { - r += y; + using T = decltype(x); + if constexpr (simd::is_half_v<T>) { + // Compute in float32 and round once. See exact_floor_divide. + float xf = static_cast<float>(x); + float yf = static_cast<float>(y); + float r = std::fmod(xf, yf); + if (r != 0 && (r < 0) != (yf < 0)) { + r += yf; + } + return std::make_pair(T(simd::exact_floor_divide(xf, yf)), T(r)); + } else { + auto r = std::fmod(x, y); + if (r != 0 && (r < 0) != (y < 0)) { + r += y; + } + return std::make_pair(std::floor(x / y), r); } - return std::make_pair(std::floor(x / y), r); };   dispatch_all_types(out_a.dtype(), [&](auto type_tag) {
diff --git ml-explore/mlx/mlx/backend/metal/kernels/binary_ops.h Layr-Labs/mlx/mlx/backend/metal/kernels/binary_ops.h index 968087f8efba8c4fa12f1173688cad3d9f173b4e..ee6222f157a3c17bc54c84a4c632edc66bacb053 100644 --- ml-explore/mlx/mlx/backend/metal/kernels/binary_ops.h +++ Layr-Labs/mlx/mlx/backend/metal/kernels/binary_ops.h @@ -14,6 +14,29 @@ return x + y; } };   +// The floor of x / y, computed as numpy's npy_divmodf does: from fmod, so the +// quotient is not rounded before the floor. float16 and bfloat16 use it in +// float32: floor(x / y) in the half type rounds a quotient that is just below +// an integer up to that integer. +inline float exact_floor_divide(float x, float y) { + if (y == 0) { + return x / y; + } + float mod = metal::fmod(x, y); + float div = (x - mod) / y; + if (mod != 0 && ((y < 0) != (mod < 0))) { + div -= 1.0f; + } + if (div == 0) { + return metal::copysign(0.0f, x / y); + } + float floordiv = metal::floor(div); + if (div - floordiv > 0.5f) { + floordiv += 1.0f; + } + return floordiv; +} + struct FloorDivide { template <typename T> metal::enable_if_t<metal::is_integral_v<T> & !metal::is_signed_v<T>, T> @@ -31,7 +54,12 @@ return q; } template <typename T> metal::enable_if_t<!metal::is_integral_v<T>, T> operator()(T x, T y) thread { - return floor(x / y); + if constexpr ( + metal::is_same_v<T, half> || metal::is_same_v<T, bfloat16_t>) { + return static_cast<T>(exact_floor_divide(float(x), float(y))); + } else { + return floor(x / y); + } } template <> complex64_t operator()(complex64_t x, complex64_t y) thread {

Upstream Python tests draw their random input from unseeded mx.random and np.random, so each run tests other input. Some tests compare with a reference under a fixed tolerance that some inputs exceed: test_double.test_gemm (float32 8x8 matmul against float64, allclose rtol 1e-5, atol 1e-8) fails when an element of the product is near zero, because the float32 rounding of partial sums of order 1 is about 1e-7 and the tolerance there is about 1e-8 + 1e-5 * |y|. It failed for 152 of 2000 seeds on the CPU. test_ops.test_scans (bfloat16 cumsum against a tri-matrix sum, rtol 0.02) failed for 4 of 100 seeds on the GPU and 2 of 100 on the CPU. The CPU float32 and float64 gemm paths both clear C (section “CPU BLAS gemm clears C when beta is 0”), so the gemm failures are tolerance, not a stale output. MLXTestCase.setUp now seeds both generators with 0 before each test, so each test draws the same input in every run; seed 0 passes both tests. Tests that seed their own generators still do. The seed search ran in PR #46 (first commit).

diff --git ml-explore/mlx/python/tests/mlx_tests.py Layr-Labs/mlx/python/tests/mlx_tests.py index 10a7e5c35fa9a2257473e14d77324983366d6a92..8552ac5a1a7f641d0157d993d6d6f14c014ffb57 100644 --- ml-explore/mlx/python/tests/mlx_tests.py +++ Layr-Labs/mlx/python/tests/mlx_tests.py @@ -54,6 +54,12 @@ device = os.getenv("DEVICE", None) if device is not None: device = getattr(mx, device) mx.set_default_device(device) + # Each test draws the same random input in every run. Many tests + # compare with a reference under a fixed tolerance, and some random + # inputs fall outside it (for example a near-zero element under a + # relative tolerance), so unseeded input made them fail now and then. + mx.random.seed(0) + np.random.seed(0)   def tearDown(self): mx.set_default_device(self.default)

The fork deletes the upstream workflows that cannot run here: the PyPI release build, the documentation deploy and the daily bypass-list update with its two scripts. build_and_test.yml keeps the lint, sanitizer and Fedora jobs. The fork deletes the jobs that run only in the upstream repository, and the composite actions that only the deleted workflows and jobs used. An upstream merge adds these files again, so delete them again at each merge.

The gate that keeps this page honest: check_forkdiff.py fails CI when base.hash is not the merge-base with upstream, when a file the fork changes is not described by a section above, or when a section names files the fork no longer changes.

fork-tests.yml builds the fork with Metal and runs its C++ and Python tests on macOS runners. Two jobs build in parallel. One job builds the Python wheel. The other job builds the C++ library and tests, and runs the C++ tests with the GPU and then with the CPU as the default device, and builds and runs the JACCL tests with simulated verbs (tests/jaccl). Then it runs the standalone allocation cap tests with ctest, one process for each case. The Python tests run in shard jobs: one set with the GPU as the default device, and one set with the CPU. .github/scripts/fork-tests/python-shards.json gives the shards. python_shards.py fails a job when a test file is in no shard or in two shards, and the last job fails when a test ran in two shards. The last job also merges the coverage profiles of all jobs into one report. The setup action pins its actions to full commit SHAs, because the organization blocks actions that are not pinned. The organization also blocks hendrikmuhs/ccache-action, so setup installs ccache with Homebrew and restores the ccache files with actions/cache. The macOS setup also installs pinned Ninja 1.13.2 in its Python environment, so both CMake builds have their selected generator. Native build jobs fetch the Apple Metal C++ headers with four bounded attempts, then check the exact size and SHA-256 before safe ZIP extraction. Both wheel and C++ builds use that verified directory; CMake also pins the archive hash for other callers. The fork-build-cache action saves the ccache files. It also keeps a cache of the compiled Metal kernels: the build jobs put metal-cache/xcrun first in PATH, and that script gives the kernel compile and link commands a cache. The key of a kernel is its preprocessed source, its arguments, the metal compiler version and the SDK build. The ccache key holds the clang version, and ccache checks the compiler content of each object.

All eight Mac jobs in fork-tests.yml use native macOS ARM64 labels. Each label names the job’s VM size: the python-cpu shards ask for 12 vCPUs and 32 GiB (darkbloom-macos-arm64-12x32), the python-gpu shards for 4 vCPUs and 24 GiB, and the other jobs for 4 vCPUs and 16 GiB. FORKDIFF.md (Job sizes) gives the data. Each Mac job runs the report-only .github/scripts/ci-resource-sampler.py, which prints its memory and vCPU peaks, and .github/scripts/test-runner-sizes.py (in Check Lint) fails when a Mac job names no signed size. They wait for compatible capacity without a hosted fallback. The Linux lint, ASAN/UBSAN, fork-diff check and Pages renderer also use native-only labels. The sanitizer jobs use the qualified compiler image and a tool preflight, retaining their original test script within a 60-minute cap. The Fedora aarch64 job runs the same Fedora script natively in the archived Fedora 42 container rootfs under PRoot (.github/scripts/fedora-proot/); the Fedora x86_64 job and the protected Pages publisher stay on GitHub-hosted runners. FORKDIFF.md describes the qualification and watchdog time bounds. AGENTS.md adds the “Working in our MLX forks” section permitting agent-assisted contributions in Layr-Labs forks (56e12b00 on main). darkbloom-watchdog.yml remains unchanged; a rerun keeps these static labels. On a Darkbloom Sandbox that has no Darkbloom cache, fork-build-cache sets CI_ACTIONS_CACHE=off and every cache step is skipped, so that the sandbox does not write GitHub’s Actions cache. The Darkbloom macOS image has Xcode 27.2 on macOS 27. No job selects an Xcode. Lint uses a Python 3.12 virtual environment and keeps its pre-commit cache separate by runner architecture. It skips Actions caching when the sandbox has no Darkbloom cache.

The native CodeQL workflow remains disabled until the operator switches from GitHub default setup and enables CODEQL_NATIVE. Its read-only ARM scan uses the pinned CodeQL 2.27.4 bundle and the existing Actions, C/C++ and Python default query suites. A separate GitHub-hosted job validates the same run’s fingerprinted SARIF before uploading the original category identities. It checks out and executes no repository source.

Three Python tests check behavior that exists only in the Metal backend (Winograd batch tiling, the Winograd switch and the FFT size limit), so they skip when the default device is not the GPU. Upstream’s test_init_reduce_large_output skips only when the default device cannot hold its 4 GiB output: on the GPU when max_buffer_length is less than 4 GiB, on the CPU when memory_size is less than 16 GiB. The hosted macos-26 runner capped Metal buffers at 3.5 GiB. The test cannot be smaller: it is the regression test for ml-explore/mlx #4437, which needs 2^32 output elements (more than one 32-bit grid dimension), and bool outputs of one byte each give 4 GiB. David ruled on 2026-10-23 to keep this skip and not to use a larger runner. A Darkbloom Sandbox caps a Metal buffer at half its memory (12 GiB of the 24 GiB of the GPU shards), and the CPU shards have a memory_size of 32 GiB, so the test runs there on the GPU and on the CPU. When a Python test entry fails, the job prints the end of its log at once. Upstream tests that run only a GPU path (forced fused SDPA, global-scale qqmm and gather_qmm) check on the CPU pass that the documented error is raised.

diff --git ml-explore/mlx/.github/actionlint.yaml Layr-Labs/mlx/.github/actionlint.yaml new file mode 100644 index 0000000000000000000000000000000000000000..133b4ad67fbdb5098cb7cf2f20936b0cd698b4c3 --- /dev/null +++ Layr-Labs/mlx/.github/actionlint.yaml @@ -0,0 +1,7 @@ +self-hosted-runner: + labels: + - darkbloom-linux-arm64 + - darkbloom-macos-arm64-4x16 + - darkbloom-macos-arm64-4x24 + - darkbloom-macos-arm64-8x16 + - darkbloom-macos-arm64-12x32
diff --git ml-explore/mlx/.github/actions/build-docs/action.yml Layr-Labs/mlx/.github/actions/build-docs/action.yml deleted file mode 100644 index 4d4286e3c86292b903eef16d1dc22c2689e300d1..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/build-docs/action.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: 'Build Documentation' -description: 'Build documentation' - -runs: - using: "composite" - steps: - - name: Setup machine - id: setup - uses: ./.github/actions/setup - with: - ccache-key: 'release' - ccache-save: false - - - name: Install dependencies - shell: bash - env: - CMAKE_ARGS: ${{ steps.setup.outputs.cmake-args }} - run: | - sudo apt-get install -y doxygen - uv pip install -r docs/requirements.txt - uv pip install . -v - - - name: Build documentation - shell: bash - run: | - cd docs - doxygen - make html O=-W - - - name: Create artifact tar - shell: bash - run: tar -cf artifact.tar -C docs --dereference build/html index.html - - # Do it manually because upload-pages-artifact requires gtar - - name: Upload artifact - id: upload-artifact - uses: actions/upload-artifact@v7 - with: - name: github-pages - path: artifact.tar - retention-days: 1 - if-no-files-found: error
diff --git ml-explore/mlx/.github/actions/build-wheel/action.yml Layr-Labs/mlx/.github/actions/build-wheel/action.yml deleted file mode 100644 index c8f86420ab3bc5f0172a70b71723773ce652a3f0..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/build-wheel/action.yml +++ /dev/null @@ -1,106 +0,0 @@ -name: 'Build wheel' -description: 'Build the Python wheels for release on all platforms' - -inputs: - cmake-args: - description: 'The args for generating CMake project' - required: true - build-frontend: - description: 'Build the frontend mlx package' - required: false - default: 'true' - build-backend: - description: 'Build the backend mlx-cpu/mlx-cuda/mlx-metal packages' - required: false - default: 'true' - macos-target: - description: 'The target macOS version to build for' - required: false - default: '26.2' - arch-tag: - description: 'Platform architecture tag' - required: false - default: |- - ${{ case(runner.arch == 'x64', 'x86_64', - runner.arch == 'x86', 'i686', - runner.arch == 'arm', 'armv7l', - runner.arch == 'arm64', 'aarch64', - 'unknown') - }} - -runs: - using: 'composite' - steps: - - name: Install dependencies - shell: bash - run: | - uv pip install build setuptools - if ${{ runner.os == 'Linux' }} ; then - uv pip install auditwheel patchelf - fi - mkdir -p wheelhouse - - - name: Build frontend package - if: inputs.build-frontend == 'true' - shell: bash - env: - CMAKE_ARGS: ${{ inputs.cmake-args }} - MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }} - run: | - python setup.py clean --all - MLX_BUILD_FRONTEND_PACKAGE=1 python -m build -w - - - name: Post-process frontend package - if: inputs.build-frontend == 'true' - shell: bash - run: | - if ${{ runner.os == 'Linux' }} ; then - auditwheel repair dist/mlx-*.whl \ - --plat manylinux_2_35_${{ inputs.arch-tag }} \ - --exclude libmlx.so* \ - --only-plat - else - mv dist/mlx-*.whl wheelhouse/ - fi - - - name: Build backend package - if: inputs.build-backend == 'true' - shell: bash - env: - CMAKE_ARGS: ${{ inputs.cmake-args }} - MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }} - run: | - python setup.py clean --all - MLX_BUILD_BACKEND_PACKAGE=1 python -m build -w - - - name: Post-process backend package - if: inputs.build-backend == 'true' - shell: bash - run: | - if ${{ runner.os == 'Linux' }} ; then - if [ -f dist/mlx_cpu*.whl ]; then - auditwheel repair dist/mlx_cpu*.whl \ - --plat manylinux_2_35_${{ inputs.arch-tag }} - fi - if [ -f dist/mlx_cuda*.whl ]; then - auditwheel repair dist/mlx_cuda*.whl \ - --plat manylinux_2_35_${{ inputs.arch-tag }} \ - --exclude libcublas* \ - --exclude libcuda* \ - --exclude libcudnn* \ - --exclude libcufft* \ - --exclude libcusolver* \ - --exclude libnccl* \ - --exclude libnvrtc* - fi - else - if [ -f dist/mlx_cpu*.whl ]; then - mv dist/mlx_cpu*.whl wheelhouse/ - fi - if [ -f dist/mlx_cuda*.whl ]; then - mv dist/mlx_cuda*.whl wheelhouse/ - fi - if [ -f dist/mlx_metal*.whl ]; then - mv dist/mlx_metal*.whl wheelhouse/ - fi - fi
diff --git ml-explore/mlx/.github/actions/build/action.yml Layr-Labs/mlx/.github/actions/build/action.yml deleted file mode 100644 index 037e0ea6bca753272efe94c0f9b03f8c56e5af5c..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/build/action.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: 'Build' -description: 'Build C++ and Python binaries for testing on Linux and Windows' - -inputs: - cmake-args: - description: 'The args for generating CMake project' - required: true - debug: - description: 'Do debug build' - required: true - -runs: - using: 'composite' - steps: - - name: Install Python package - shell: bash - env: - DEBUG: ${{ inputs.debug == 'true' && 1 || 0 }} - CMAKE_ARGS: ${{ inputs.cmake-args }} - run: | - # Install cpu-only torch to save space. - uv pip install torch --torch-backend=cpu - uv pip install --no-build-isolation -e ".[dev]" -v - - - name: Build CPP only - shell: bash - env: - # The cpp build is using some extra settings to reuse the compile cache - # generated by the python install: - # 1. Use the same ccache options with setup.py. - # 2. Build dynamic library. - # 3. Put the build dir in the same depth with python build dir. - CCACHE_BASEDIR: ${{ github.workspace }}/build/cpp/mlx - CCACHE_NOHASHDIR: true - run: | - cmake . -B build/cpp/mlx ${{ inputs.cmake-args }} \ - -DBUILD_SHARED_LIBS=ON \ - -DCMAKE_BUILD_TYPE=${{ inputs.debug == 'true' && 'Debug' || 'Release' }} - cmake --build build/cpp/mlx \ - -j ${{ runner.os == 'Windows' && '$NUMBER_OF_PROCESSORS' || '$(nproc)' }}
diff --git ml-explore/mlx/.github/actions/fork-build-cache/action.yml Layr-Labs/mlx/.github/actions/fork-build-cache/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..61c2d92ec35375af3f19ce69dcf8287067705d40 --- /dev/null +++ Layr-Labs/mlx/.github/actions/fork-build-cache/action.yml @@ -0,0 +1,188 @@ +name: 'Fork build caches' +description: 'Set up a fork-tests build job with ccache and the Metal kernel cache, and save the caches' + +# phase: restore runs the setup action, restores the ccache files and the +# Metal kernel cache, and points the build at the cache script in +# .github/scripts/fork-tests/metal-cache. phase: save prints the cache +# statistics and saves each cache on pull requests and on pushes to main +# when the build had cache misses. +# +# Cache keys: +# ccache ccache-fork-tests-KIND-FLAGS-clangCLANG-macOS-ARM64-metal-SHA-RUN-ATTEMPT +# Metal metal-METAL-KERNELS-KIND-RUN-ATTEMPT +# CLANG is the clang major.minor version. METAL is the metal compiler +# version. FLAGS is a hash of CFLAGS, CXXFLAGS, the deployment target and +# KIND. KIND sets the CMake arguments of the build. KERNELS is a hash of +# mlx/backend/metal/kernels. A restore takes the newest cache with the same +# prefix. The ccache restore falls back to a cache of another clang version; +# ccache checks the compiler content (compiler_check=content), so the +# objects of another compiler only miss. The Metal restore falls back only to +# a cache of the same metal compiler version, and the cache script puts the +# metal compiler version and the SDK build in each entry key. + +inputs: + phase: + description: 'restore or save' + required: true + kind: + description: 'The build kind: wheel or cpp' + required: true + ccache-save-key: + description: 'phase save: the ccache-save-key output of phase restore' + required: false + default: '' + metal-save-key: + description: 'phase save: the metal-save-key output of phase restore' + required: false + default: '' + +outputs: + cmake-args: + description: 'The args for generating CMake project' + value: ${{ steps.setup.outputs.cmake-args }} ${{ steps.metal-cpp.outputs.cmake-args }} + ccache-save-key: + description: 'The key to save the ccache files with' + value: ${{ steps.setup.outputs.ccache-save-key }} + metal-save-key: + description: 'The key to save the Metal kernel cache with' + value: ${{ steps.keys.outputs.metal-save }} + +runs: + using: 'composite' + steps: + # Before every cache step. On a Darkbloom Sandbox without a Darkbloom + # cache (DARKBLOOM_CACHE_URL), a cache step would use GitHub's Actions + # cache, so every cache step is skipped (CI_ACTIONS_CACHE=off). + - name: Choose this job's Actions cache + if: inputs.phase == 'restore' + shell: bash + run: | + if [[ ${RUNNER_NAME:-} != darkbloom-* ]]; then + echo "Actions cache: this runner's own" + elif [[ -n ${DARKBLOOM_CACHE_URL:-} ]]; then + echo "Actions cache: the Darkbloom cache at $DARKBLOOM_CACHE_URL" + else + echo "CI_ACTIONS_CACHE=off" >> "$GITHUB_ENV" + echo "::notice title=Actions cache::The plane gave this Darkbloom Sandbox no cache, so every cache step is skipped." + fi + + - name: Make the cache keys + id: keys + if: inputs.phase == 'restore' + shell: bash + env: + KIND: ${{ inputs.kind }} + KERNELS: ${{ hashFiles('mlx/backend/metal/kernels/**') }} + run: | + # The other lines of --version name the install folder and the OS. + # They change between runner images, so the keys use the first line. + version() { + echo "$1" | head -n 1 | sed -E 's/.* version ([0-9.]+).*/\1/' | tr -c 'A-Za-z0-9.\n' '_' + } + clang_text=$(xcrun clang --version) + metal_text=$(xcrun -sdk macosx metal --version) + sdk=$(xcrun -sdk macosx --show-sdk-build-version) + printf '%s\n' "$clang_text" "$metal_text" "SDK build: $sdk" + clang=$(version "$clang_text" | cut -d . -f 1-2) + metal=$(version "$metal_text") + if [ -z "$clang" ] || [ -z "$metal" ] || [ -z "$sdk" ]; then + echo "::error::Cannot read the clang, metal or SDK version." + exit 1 + fi + flags=$(printf '%s\n' "$CFLAGS" "$CXXFLAGS" "$MACOSX_DEPLOYMENT_TARGET" "$KIND" \ + | shasum -a 256 | cut -c 1-16) + kernels=${KERNELS:0:16} + { + echo "toolchain=$(echo "$metal_text" | head -n 1) SDK $sdk" + echo "ccache-key=fork-tests-$KIND-$flags-clang$clang" + echo "ccache-fallback=ccache-fork-tests-$KIND-$flags-" + echo "metal-restore=metal-$metal-$kernels-" + echo "metal-fallback=metal-$metal-" + echo "metal-save=metal-$metal-$kernels-$KIND-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + } | tee -a "$GITHUB_OUTPUT" + + - uses: ./.github/actions/setup + id: setup + if: inputs.phase == 'restore' + with: + toolkit: metal + ccache-key: ${{ steps.keys.outputs.ccache-key }} + ccache-fallback: ${{ steps.keys.outputs.ccache-fallback }} + # The build and the C++ tests do not use openmpi. Only the + # distributed test in python-gpu shard 0 does. + install-macos-deps: 'false' + + - name: Fetch verified Apple headers with bounded retries + id: metal-cpp + if: inputs.phase == 'restore' && runner.os == 'macOS' && startsWith(runner.name, 'darkbloom-') + shell: bash + run: | + python3 .github/scripts/fork-tests/test_metal_cpp.py + python3 .github/scripts/fork-tests/metal_cpp.py >> "$GITHUB_OUTPUT" + + - name: Restore the Metal kernel cache + if: inputs.phase == 'restore' && env.CI_ACTIONS_CACHE != 'off' + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.metal-cache + key: ${{ steps.keys.outputs.metal-restore }} + restore-keys: | + ${{ steps.keys.outputs.metal-restore }} + ${{ steps.keys.outputs.metal-fallback }} + + - name: Prepare the caches + if: inputs.phase == 'restore' + shell: bash + env: + TOOLCHAIN: ${{ steps.keys.outputs.toolchain }} + run: | + # The script reads the restored entries from MLX_METAL_CACHE_IN and + # writes each entry that the build uses to MLX_METAL_CACHE_OUT. The + # saved cache then holds no entries that the build does not use. + in="$RUNNER_TEMP/metal-cache-in" + if [ -d .metal-cache ]; then + mv .metal-cache "$in" + else + mkdir -p "$in" + fi + echo "Restored Metal cache entries: $(ls "$in" | wc -l)" + { + echo "MLX_METAL_CACHE_TOOLCHAIN=$TOOLCHAIN" + echo "MLX_METAL_CACHE_IN=$in" + echo "MLX_METAL_CACHE_OUT=$GITHUB_WORKSPACE/.metal-cache" + } >> "$GITHUB_ENV" + ccache -z + + - name: Show the cache statistics + id: stats + if: inputs.phase == 'save' + shell: bash + run: | + ccache -s -v + ccache_misses=$(ccache -s | awk '$1 == "Misses:" { print $2; exit }') + ccache_misses=${ccache_misses:-unknown} + metal_misses=0 + log="$MLX_METAL_CACHE_OUT.log" + if [ -f "$log" ]; then + metal_misses=$(grep -c '^miss ' "$log" || true) + echo "Metal cache: $(grep -c '^hit ' "$log" || true) hits, $metal_misses misses" + grep '^miss ' "$log" || true + fi + du -sh .ccache .metal-cache || true + # A build with no misses adds nothing, so it does not save a copy. + echo "ccache-misses=$ccache_misses" | tee -a "$GITHUB_OUTPUT" + echo "metal-misses=$metal_misses" | tee -a "$GITHUB_OUTPUT" + + - name: Save the ccache files + if: inputs.phase == 'save' && env.CI_ACTIONS_CACHE != 'off' && steps.stats.outputs.ccache-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ${{ inputs.ccache-save-key }} + + - name: Save the Metal kernel cache + if: inputs.phase == 'save' && env.CI_ACTIONS_CACHE != 'off' && steps.stats.outputs.metal-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.metal-cache + key: ${{ inputs.metal-save-key }}
diff --git ml-explore/mlx/.github/actions/setup/action.yml Layr-Labs/mlx/.github/actions/setup/action.yml index 6ba85028bb44d3080a5d386ef2a2c80e376c806a..58440e9d21f907577367a9a2b82e7384d8377041 100644 --- ml-explore/mlx/.github/actions/setup/action.yml +++ Layr-Labs/mlx/.github/actions/setup/action.yml @@ -26,11 +26,22 @@ ccache-toolkit: description: 'Use this instead of inputs.toolkit in the ccache key' required: false default: '' + ccache-fallback: + description: 'A second restore-keys prefix for the ccache files' + required: false + default: '' + install-macos-deps: + description: 'Whether to run brew update and install openmpi on macOS' + required: false + default: 'true'   outputs: cmake-args: description: 'The args for generating CMake project' value: ${{ steps.cmake-args.outputs.cmakeArgs }} + ccache-save-key: + description: 'The key for actions/cache/save of the ccache files (macOS)' + value: ${{ steps.ccache-keys.outputs.save }}   runs: using: 'composite' @@ -46,12 +57,14 @@ libblas-dev liblapack-dev liblapacke-dev \ openmpi-bin openmpi-common libopenmpi-dev   - name: Install macOS dependencies - if: runner.os == 'macOS' + if: runner.os == 'macOS' && inputs.install-macos-deps == 'true' shell: bash run: | brew update brew trust aws/tap # suppress warning in github actions brew install openmpi + xcodebuild -version + swift --version xcodebuild -showComponent MetalToolchain sysctl -a | grep machdep.cpu   @@ -75,17 +88,45 @@ set CCACHE_SLOPPINESS=include_file_ctime,include_file_mtime :: Export to all steps. >>%GITHUB_ENV% set   - - uses: astral-sh/setup-uv@v8.2.0 + # setup-uv fetches its 1.5 MB version manifest (raw.githubusercontent.com) + # with a 5-second limit. Through a Darkbloom sandbox's egress proxy that takes + # about 3.3 seconds when it works, and some hosts failed twice in a row on + # 2026-11-14; a native job has no hosted fallback. So pin uv and hand setup-uv + # a one-entry manifest inline (data: URL, nothing to fetch). The archive still + # comes from the Astral mirror, with the tool cache's own retries, and must + # match this SHA-256 (the official manifest's, 2026-11-12). Bump all three + # together. Only when the first try failed, wait and try once more. + - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + id: setup-uv + continue-on-error: true with: enable-cache: false quiet: true + version: 0.13.8 + checksum: 6b71028a6b904f2ae3340ef52e595512de807d06c0a20eaef2f692581b246558 + manifest-file: data:application/x-ndjson;base64,eyJ2ZXJzaW9uIjoiMC4xMy44IiwiZGF0ZSI6IjIwMjYtMTEtMTJUMTc6MDM6MDdaIiwiYXJ0aWZhY3RzIjpbeyJwbGF0Zm9ybSI6ImFhcmNoNjQtYXBwbGUtZGFyd2luIiwidmFyaWFudCI6ImRlZmF1bHQiLCJ1cmwiOiJodHRwczovL2dpdGh1Yi5jb20vYXN0cmFsLXNoL3V2L3JlbGVhc2VzL2Rvd25sb2FkLzAuMTMuOC91di1hYXJjaDY0LWFwcGxlLWRhcndpbi50YXIuZ3oiLCJhcmNoaXZlX2Zvcm1hdCI6InRhci5neiIsInNoYTI1NiI6IjZiNzEwMjhhNmI5MDRmMmFlMzM0MGVmNTJlNTk1NTEyZGU4MDdkMDZjMGEyMGVhZWYyZjY5MjU4MWIyNDY1NTgifV19Cg==   - - name: Use ccache - if: inputs.use-ccache == 'true' - uses: hendrikmuhs/ccache-action@v1.2.23 + - name: Wait before the second uv setup + if: steps.setup-uv.outcome == 'failure' + shell: bash + run: sleep 15 + + - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + if: steps.setup-uv.outcome == 'failure' with: - key: v7-${{ inputs.ccache-key }}-${{ runner.os }}-${{ runner.arch }}-${{ inputs.ccache-toolkit || inputs.toolkit }} - max-size: |- + enable-cache: false + quiet: true + version: 0.13.8 + checksum: 6b71028a6b904f2ae3340ef52e595512de807d06c0a20eaef2f692581b246558 + manifest-file: data:application/x-ndjson;base64,eyJ2ZXJzaW9uIjoiMC4xMy44IiwiZGF0ZSI6IjIwMjYtMTEtMTJUMTc6MDM6MDdaIiwiYXJ0aWZhY3RzIjpbeyJwbGF0Zm9ybSI6ImFhcmNoNjQtYXBwbGUtZGFyd2luIiwidmFyaWFudCI6ImRlZmF1bHQiLCJ1cmwiOiJodHRwczovL2dpdGh1Yi5jb20vYXN0cmFsLXNoL3V2L3JlbGVhc2VzL2Rvd25sb2FkLzAuMTMuOC91di1hYXJjaDY0LWFwcGxlLWRhcndpbi50YXIuZ3oiLCJhcmNoaXZlX2Zvcm1hdCI6InRhci5neiIsInNoYTI1NiI6IjZiNzEwMjhhNmI5MDRmMmFlMzM0MGVmNTJlNTk1NTEyZGU4MDdkMDZjMGEyMGVhZWYyZjY5MjU4MWIyNDY1NTgifV19Cg== + + # The organization blocks hendrikmuhs/ccache-action. The next three steps + # do the same work with Homebrew and actions/cache. They run on macOS only. + - name: Install ccache + if: runner.os == 'macOS' && inputs.use-ccache == 'true' + shell: bash + env: + MAX_SIZE: |- ${{ case(inputs.ccache-key == 'release', case(startsWith(inputs.toolkit, 'cuda'), '300MB', @@ -97,13 +138,44 @@ '320MB'), runner.os == 'macOS' && inputs.toolkit == 'metal', '300MB', '200MB')) }} - save: ${{ !startsWith(github.ref, 'refs/pull/') && (inputs.ccache-save != 'false') }} - # ccache-action bug: running "apt-get update" fails on large arm runner. - update-package-index: false + run: | + brew install ccache + ccache --set-config=cache_dir="$GITHUB_WORKSPACE/.ccache" + ccache --set-config=max_size="$MAX_SIZE" + ccache --set-config=compression=true + ccache --set-config=compiler_check=content + ccache -p + + - name: Make the ccache keys + id: ccache-keys + if: runner.os == 'macOS' && inputs.use-ccache == 'true' + shell: bash + env: + PREFIX: ccache-${{ inputs.ccache-key }}-${{ runner.os }}-${{ runner.arch }}-${{ inputs.ccache-toolkit || inputs.toolkit }}- + FALLBACK: ${{ inputs.ccache-fallback }} + run: | + { + echo "restore=$PREFIX$GITHUB_SHA" + echo "save=$PREFIX$GITHUB_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + echo "restore-keys<<EOF" + echo "$PREFIX" + if [ -n "$FALLBACK" ]; then echo "$FALLBACK"; fi + echo "EOF" + } | tee -a "$GITHUB_OUTPUT" + + - name: Restore the ccache files + # This action only restores the cache. The workflow saves it with + # actions/cache/save and the key in the ccache-save-key output. + if: runner.os == 'macOS' && inputs.use-ccache == 'true' && env.CI_ACTIONS_CACHE != 'off' + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ${{ steps.ccache-keys.outputs.restore }} + restore-keys: ${{ steps.ccache-keys.outputs.restore-keys }}   - name: Cache JIT-compiled CUDA kernels if: runner.os == 'Linux' && startsWith(inputs.toolkit, 'cuda') - uses: actions/cache@v5 + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: /tmp/mlx-ptx-cache key: >- @@ -125,6 +197,13 @@ # Use PTX ccache for CUDA. if ${{ startsWith(inputs.toolkit, 'cuda') }} ; then echo MLX_PTX_CACHE_DIR=/tmp/mlx-ptx-cache >> $GITHUB_ENV fi + + - name: Install Ninja on macOS + if: runner.os == 'macOS' + shell: bash + run: | + uv pip install --python .venv/bin/python --only-binary=:all: 'ninja==1.13.2' + .venv/bin/ninja --version   - name: Setup Python venv (Windows) if: runner.os == 'Windows'
diff --git ml-explore/mlx/.github/actions/test-linux/action.yml Layr-Labs/mlx/.github/actions/test-linux/action.yml deleted file mode 100644 index 7c5f4322137a5b08c20feba74070b55d343b5e6e..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/test-linux/action.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: 'Run tests' -description: 'Run Python and C++ tests on Linux' - -runs: - using: 'composite' - steps: - - name: Check GPU support - id: gpu-check - shell: bash - run: | - if __nvcc_device_query ; then - echo "good=true" >> $GITHUB_OUTPUT - else - echo "good=false" >> $GITHUB_OUTPUT - fi - echo - - - name: Run MPI tests - if: steps.gpu-check.outputs.good == 'false' - shell: bash - run: mpirun --bind-to none --allow-run-as-root -host localhost:8 -np 8 python python/tests/mpi_test_distributed.py - - - name: Run distributed tests - if: steps.gpu-check.outputs.good == 'false' - shell: bash - run: | - mlx.launch --verbose -n 8 python python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2) - if grep -Fq '[WARN]' stderr.log ; then - grep -F '[WARN]' stderr.log - echo "Distributed ring test failed"; - exit 1; - fi - - - name: Run Python tests - CPU - if: steps.gpu-check.outputs.good == 'false' - shell: bash - env: - DEVICE: cpu - run: python python/tests/run.py -v - - - name: Run Python tests - GPU - if: steps.gpu-check.outputs.good == 'true' - shell: bash - env: - DEVICE: gpu - run: python python/tests/run.py -v - - - name: Run CPP tests - CPU - shell: bash - env: - DEVICE: cpu - run: ./build/cpp/mlx/tests/tests - - - name: Run CPP tests - GPU - if: steps.gpu-check.outputs.good == 'true' - shell: bash - env: - DEVICE: gpu - run: ./build/cpp/mlx/tests/tests -sfe="*linalg_tests.cpp" - - - name: Show stack trace on crash - if: failure() - shell: bash - run: | - set +e - sleep 10 - if coredumpctl list; then - coredumpctl debug --debugger-arguments="-batch -ex 'thread apply all bt'" - fi
diff --git ml-explore/mlx/.github/actions/test-wheel/action.yml Layr-Labs/mlx/.github/actions/test-wheel/action.yml deleted file mode 100644 index e060876503c631efa05aa838c5c7347701c21396..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/test-wheel/action.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: 'Test wheel' -description: 'Run tests with the built wheels' - -inputs: - toolkit: - description: 'Which toolkit to test' - required: false - default: 'cpu' - -runs: - using: 'composite' - steps: - - name: Get Python version - id: python - shell: bash - run: python -c "import sys; print(f'version={sys.version_info.major}.{sys.version_info.minor}')" >> $GITHUB_OUTPUT - - - name: Download frontend packages - uses: actions/download-artifact@v8 - with: - pattern: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ steps.python.outputs.version }} - path: wheelhouse - - - name: Download backend packages - uses: actions/download-artifact@v8 - with: - pattern: backend-${{ inputs.toolkit}}-${{ runner.os }}-${{ runner.arch }} - path: wheelhouse - - - name: Test local packages - shell: bash - run: | - # Fall back to PyPI if PyTorch index has issues. - uv pip install torch --torch-backend=cpu - uv pip install numpy - if ${{ inputs.toolkit == 'cpu' }} ; then - uv pip install wheelhouse/mlx_cpu*.whl - uv pip install wheelhouse/mlx-*.whl - elif ${{ startsWith(inputs.toolkit, 'cuda') }} ; then - uv pip install wheelhouse/mlx_cuda*.whl - uv pip install wheelhouse/mlx-*.whl - elif ${{ inputs.toolkit == 'metal' }} ; then - uv pip install wheelhouse/mlx_metal-*-macosx_26_0_arm64.whl - uv pip install wheelhouse/mlx-*-macosx_26_0_arm64.whl - else - echo "No matching backend wheel to install" - exit 1 - fi - uv run python/tests/run.py -v --failfast
diff --git ml-explore/mlx/.github/actions/test-windows/action.yml Layr-Labs/mlx/.github/actions/test-windows/action.yml deleted file mode 100644 index 6d89c4e5bd3c3f421a7a1cff505871fbf5e66cd2..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/actions/test-windows/action.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: 'Run tests' -description: 'Run Python and C++ tests on Windows' - -runs: - using: 'composite' - steps: - - name: Run Python tests - CPU - shell: bash - env: - DEVICE: cpu - run: uv run python/tests/run.py -v - - - name: Run CPP tests - CPU - shell: bash - env: - DEVICE: cpu - run: ./build/cpp/mlx/tests.exe -tce="*gguf*"
diff --git ml-explore/mlx/.github/scripts/ci-resource-sampler.py Layr-Labs/mlx/.github/scripts/ci-resource-sampler.py new file mode 100755 index 0000000000000000000000000000000000000000..bfa54280c9bcf6b8501a1b02c8e92d2dc651b670 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/ci-resource-sampler.py @@ -0,0 +1,720 @@ +#!/usr/bin/env python3 +"""Sample a macOS CI job's memory and CPU use and report the peaks. Report-only. + +`start` runs the sampler in the background and gives later steps the samples +directory as CI_RESOURCE_SAMPLES. Every INTERVAL seconds it writes one CSV row: + +- memory by class, from `vm_stat`: app (anonymous pages less purgeable ones; + Metal buffers count here), wired, file cache (file-backed and purgeable + pages, which the kernel can reclaim), compressed, + and used = app + wired + compressed, as Activity Monitor counts it; swap in + use (`sysctl vm.swapusage`) and the kernel's memory pressure level + (`kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical); +- busy vCPUs over the interval, from the host's CPU ticks (`host_statistics`), + or the sum of the `ps` %cpu averages where those are not available; +- the physical footprint of every process this user can read, from + `proc_pid_rusage`: `ri_phys_footprint` is the counter `footprint` and + Activity Monitor show, and it includes IOAccelerator (Metal) memory. The row + keeps their sum and the three largest by lifetime peak + (`ri_lifetime_max_phys_footprint`, so a peak between samples counts), each + with the test selection it runs under; +- the largest resident process (`ps` RSS), to compare with earlier runs. + +When the largest footprint first reaches 2 GiB, and again when it is 2 GiB +above the last capture, `/usr/bin/footprint`, where present, writes that +process's breakdown by category beside the samples (at most twice a job). Test +runners call `mark start|end LABEL PID` around each selection; a process below +PID belongs to LABEL. + +`report` stops the sampler. It prints the peak of each class, the three +largest processes, the selections that ran at the peak, the busy vCPU mean, +95th percentile and maximum, and the sampled time scaled to 4 and 8 vCPUs; in +CI it also writes them to the step summary, and to summary.json beside the +samples. No subcommand ever fails a job: every error is printed and exits 0. + +Subcommands: + start DIRECTORY [--interval SECONDS] + report DIRECTORY + mark start|end LABEL [PID] into $CI_RESOURCE_SAMPLES (nothing without it); + PID defaults to the caller, the mark's parent + run DIRECTORY [--interval SECONDS] the background loop `start` launches +""" + +import argparse +import csv +import ctypes +import json +import os +import re +import signal +import subprocess +import sys +import time +from pathlib import Path + +FIELDS = ( + "time", + "used_bytes", + "app_bytes", + "wired_bytes", + "file_bytes", + "compressed_bytes", + "swap_bytes", + "pressure", + "busy_vcpus", + "footprint_bytes", + "top_rss_bytes", + "top_command", + "top_footprints", +) +CLASSES = ( + ("used_bytes", "Used"), + ("app_bytes", "App"), + ("wired_bytes", "Wired"), + ("file_bytes", "File cache"), + ("compressed_bytes", "Compressed"), + ("swap_bytes", "Swap"), +) +SAMPLES = "samples.csv" +PID = "sampler.pid" +MACHINE = "machine.txt" +MARKS = "marks.csv" +SUMMARY = "summary.json" +ENVIRONMENT = "CI_RESOURCE_SAMPLES" +FOOTPRINT = "/usr/bin/footprint" +CAPTURES = 2 +CAPTURE_STEP = 2 * 2**30 +CAPTURE_SECONDS = 60 +TOP = 3 +SCALED_VCPUS = (4, 8) +GIB = 2**30 +UNITS = {"K": 2**10, "M": 2**20, "G": 2**30} +RUSAGE_INFO_V4 = 4 +HOST_CPU_LOAD_INFO = 3 + + +class RusageInfoV4(ctypes.Structure): + """struct rusage_info_v4 (<sys/resource.h>).""" + + _fields_ = [("ri_uuid", ctypes.c_uint8 * 16)] + [ + (name, ctypes.c_uint64) + for name in ( + "ri_user_time", + "ri_system_time", + "ri_pkg_idle_wkups", + "ri_interrupt_wkups", + "ri_pageins", + "ri_wired_size", + "ri_resident_size", + "ri_phys_footprint", + "ri_proc_start_abstime", + "ri_proc_exit_abstime", + "ri_child_user_time", + "ri_child_system_time", + "ri_child_pkg_idle_wkups", + "ri_child_interrupt_wkups", + "ri_child_pageins", + "ri_child_elapsed_abstime", + "ri_diskio_bytesread", + "ri_diskio_byteswritten", + "ri_cpu_time_qos_default", + "ri_cpu_time_qos_maintenance", + "ri_cpu_time_qos_background", + "ri_cpu_time_qos_utility", + "ri_cpu_time_qos_legacy", + "ri_cpu_time_qos_user_initiated", + "ri_cpu_time_qos_user_interactive", + "ri_billed_system_time", + "ri_serviced_system_time", + "ri_logical_writes", + "ri_lifetime_max_phys_footprint", + "ri_instructions", + "ri_cycles", + "ri_billed_energy", + "ri_serviced_energy", + "ri_interval_max_phys_footprint", + "ri_runnable_time", + ) + ] + + +# Native calls fail with these; the sampler then records what it can without them. +NATIVE_ERRORS = (OSError, AttributeError, TypeError, ctypes.ArgumentError) +_system = None + + +def system(): + """(libSystem with the calls the sampler makes, the host port). + + OSError where there is none. + """ + global _system + if _system is None: + if sys.platform != "darwin": + raise OSError("proc_pid_rusage and host_statistics need macOS") + library = ctypes.CDLL("/usr/lib/libSystem.B.dylib") + library.proc_pid_rusage.argtypes = [ + ctypes.c_int, + ctypes.c_int, + ctypes.POINTER(RusageInfoV4), + ] + library.proc_pid_rusage.restype = ctypes.c_int + library.mach_host_self.argtypes = [] + library.mach_host_self.restype = ctypes.c_uint32 + library.host_statistics.argtypes = [ + ctypes.c_uint32, + ctypes.c_int, + ctypes.POINTER(ctypes.c_uint32 * 4), + ctypes.POINTER(ctypes.c_uint32), + ] + library.host_statistics.restype = ctypes.c_int + _system = (library, library.mach_host_self()) + return _system + + +def output(*argv): + return subprocess.run( + argv, capture_output=True, text=True, timeout=10, check=True + ).stdout + + +def memory(vm_stat): + """Bytes of each memory class (CLASSES but swap) from `vm_stat` text.""" + size = int(re.search(r"page size of (\d+) bytes", vm_stat).group(1)) + pages = { + name.strip().lower(): int(value) + for name, value in re.findall(r'^"?([^:"]+)"?:\s+(\d+)\.', vm_stat, re.M) + } + purgeable = pages["pages purgeable"] + app = pages["anonymous pages"] - purgeable + wired = pages["pages wired down"] + compressed = pages["pages occupied by compressor"] + return { + "used_bytes": (app + wired + compressed) * size, + "app_bytes": app * size, + "wired_bytes": wired * size, + "file_bytes": (pages["file-backed pages"] + purgeable) * size, + "compressed_bytes": compressed * size, + } + + +def swap_used(swapusage): + """Bytes of swap in use from `sysctl -n vm.swapusage` text.""" + match = re.search(r"used = ([0-9.]+)([KMG])", swapusage) + return int(float(match.group(1)) * UNITS[match.group(2)]) + + +def processes(ps): + """[(pid, ppid, %cpu, RSS bytes, command)] from `ps` text. + + The text is the output of `ps -A -o pid=,ppid=,%cpu=,rss=,comm=`. + """ + rows = [] + for line in ps.splitlines(): + fields = line.split(None, 4) + try: + rows.append( + ( + int(fields[0]), + int(fields[1]), + float(fields[2]), + int(fields[3]) * 1024, + os.path.basename(fields[4].strip()) if len(fields) > 4 else "", + ) + ) + except (IndexError, ValueError): + continue + return rows + + +def footprints(pids): + """{pid: (physical footprint, lifetime peak)} of the processes this user reads.""" + library, _ = system() + info = RusageInfoV4() + found = {} + for pid in pids: + if library.proc_pid_rusage(pid, RUSAGE_INFO_V4, ctypes.byref(info)) == 0: + found[pid] = (info.ri_phys_footprint, info.ri_lifetime_max_phys_footprint) + return found + + +def cpu_ticks(): + """(busy, all) CPU ticks of every CPU since boot. + + HOST_CPU_LOAD_INFO: user, system, idle, nice. + """ + library, host = system() + ticks = (ctypes.c_uint32 * 4)() + count = ctypes.c_uint32(4) + if ( + library.host_statistics( + host, HOST_CPU_LOAD_INFO, ctypes.byref(ticks), ctypes.byref(count) + ) + != 0 + ): + raise OSError("host_statistics(HOST_CPU_LOAD_INFO) failed") + return ticks[0] + ticks[1] + ticks[3], sum(ticks) + + +def busy_vcpus(before, after, cpus): + """Busy vCPUs between two cpu_ticks() readings; None when no tick passed.""" + busy, total = ((now - then) % 2**32 for now, then in zip(after, before)) + return busy / total * cpus if total else None + + +def read_marks(path): + """[(time, event, label, pid)] of the whole rows of a marks file; [] without one.""" + try: + text = path.read_text() + except OSError: + return [] + marks = [] + for row in csv.reader(text.splitlines()): + if len(row) != 4 or not row[3].isdigit(): + continue + stamp, event, label, pid = row + try: + marks.append((float(stamp), event, label, int(pid))) + except ValueError: + continue + return marks + + +def active_marks(path): + """{pid: label} of the selections started under pid and not yet ended. + + From a marks file. + """ + active = {} + for _, event, label, pid in read_marks(path): + if event == "start": + active[pid] = label + elif event == "end" and active.get(pid) == label: + del active[pid] + return active + + +def selection_of(pid, parents, active): + """The label of the nearest marked ancestor of pid (itself included), or "".""" + seen = set() + while pid and pid not in seen: + if pid in active: + return active[pid] + seen.add(pid) + pid = parents.get(pid) + return "" + + +class Sampler: + """One sample a call; keeps the CPU ticks and footprint captures between calls.""" + + def __init__(self, directory): + self.directory = directory + self.cpus = os.cpu_count() or 1 + self.ticks = self.read_ticks() + self.captured_bytes = 0 + self.captures = [] + + def read_ticks(self): + try: + return cpu_ticks() + except NATIVE_ERRORS: + return None + + def busy(self, listed): + ticks = self.read_ticks() + busy = ( + busy_vcpus(self.ticks, ticks, self.cpus) if ticks and self.ticks else None + ) + self.ticks = ticks + return sum(cpu for _, _, cpu, _, _ in listed) / 100 if busy is None else busy + + def sample(self): + row = {"time": f"{time.time():.0f}", **memory(output("vm_stat"))} + row["swap_bytes"] = swap_used(output("sysctl", "-n", "vm.swapusage")) + row["pressure"] = output( + "sysctl", "-n", "kern.memorystatus_vm_pressure_level" + ).strip() + listed = processes(output("ps", "-A", "-o", "pid=,ppid=,%cpu=,rss=,comm=")) + row["busy_vcpus"] = f"{self.busy(listed):.2f}" + largest = max( + listed, key=lambda process: process[3], default=(0, 0, 0.0, 0, "") + ) + row["top_rss_bytes"], row["top_command"] = largest[3], largest[4] + try: + found = footprints([pid for pid, *_ in listed]) + except NATIVE_ERRORS: + found = {} + if found: + parents = {pid: ppid for pid, ppid, *_ in listed} + commands = {pid: command for pid, _, _, _, command in listed} + active = active_marks(self.directory / MARKS) + ranked = sorted(found, key=lambda pid: found[pid][1], reverse=True)[:TOP] + row["footprint_bytes"] = sum(current for current, _ in found.values()) + row["top_footprints"] = json.dumps( + [ + [ + pid, + commands[pid], + *found[pid], + selection_of(pid, parents, active), + ] + for pid in ranked + ] + ) + current = max(found, key=lambda pid: found[pid][0]) + self.capture(current, found[current][0], row["time"]) + self.reap() + return [row.get(field, "") for field in FIELDS] + + def capture(self, pid, footprint, stamp): + """`footprint PID` into the directory. + + Only when footprint is CAPTURE_STEP above the last capture (or 0). + """ + if ( + footprint < self.captured_bytes + CAPTURE_STEP + or len(self.captures) >= CAPTURES + or not os.access(FOOTPRINT, os.X_OK) + ): + return + self.captured_bytes = footprint + with open(self.directory / f"footprint-{stamp}-{pid}.txt", "w") as handle: + self.captures.append( + ( + time.monotonic(), + subprocess.Popen( + [FOOTPRINT, str(pid)], + stdin=subprocess.DEVNULL, + stdout=handle, + stderr=subprocess.STDOUT, + ), + ) + ) + + def reap(self): + for started, child in self.captures: + if child.poll() is None and time.monotonic() - started > CAPTURE_SECONDS: + child.kill() + + +def run(directory, interval): + sampler = Sampler(directory) + with open(directory / SAMPLES, "a", newline="") as handle: + writer = csv.writer(handle) + while True: + try: + writer.writerow(sampler.sample()) + handle.flush() + except ( + Exception + ): # Report-only: a failed sample is skipped; the loop goes on. + pass + time.sleep(interval) + + +def start(directory, interval): + directory.mkdir(parents=True, exist_ok=True) + with open(directory / SAMPLES, "w", newline="") as handle: + csv.writer(handle).writerow(FIELDS) + try: + machine = output("sysctl", "-n", "hw.ncpu", "hw.memsize").split() + (directory / MACHINE).write_text(f"{machine[0]} {machine[1]}\n") + except (OSError, IndexError, subprocess.SubprocessError): + pass + child = subprocess.Popen( + [ + sys.executable, + os.path.abspath(__file__), + "run", + str(directory), + "--interval", + str(interval), + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + (directory / PID).write_text(f"{child.pid}\n") + github_env = os.environ.get("GITHUB_ENV") + if github_env: + with open(github_env, "a") as handle: + handle.write(f"{ENVIRONMENT}={directory.resolve()}\n") + print( + f"Resource sampler: pid {child.pid}, every {interval} s, " + f"into {directory / SAMPLES}" + ) + + +def mark(event, label, pid=None): + """Note that selection `label` starts or ends under process pid. + + pid defaults to the caller. Nothing outside a sampled job. + """ + directory = os.environ.get(ENVIRONMENT) + if not directory: + return + if event not in ("start", "end"): + raise ValueError(f"mark takes start or end, got {event!r}") + with open(Path(directory) / MARKS, "a", newline="") as handle: + csv.writer(handle).writerow( + [ + f"{time.time():.3f}", + event, + label, + os.getppid() if pid is None else int(pid), + ] + ) + + +def percentile(values, fraction): + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(fraction * len(ordered)))] + + +def number(value): + return int(value) if value not in (None, "") else None + + +def gib(value): + return "n/a" if value is None else f"{value / GIB:.2f}" + + +def utc(stamp): + return time.strftime("%H:%M:%S", time.gmtime(float(stamp))) + + +def selections_at(path, moment): + """The labels of the marks file that had started and not ended at moment.""" + spans = {} + for stamp, event, label, pid in read_marks(path): + span = spans.setdefault((label, pid), [None, None]) + span[0 if event == "start" else 1] = stamp + return sorted( + label + for (label, _), (began, ended) in spans.items() + if began is not None and began <= moment and (ended is None or ended >= moment) + ) + + +def scaled_seconds(rows, cpus): + """Sampled seconds if busy vCPUs above `cpus` had run on `cpus`. + + Each interval is stretched by busy / cpus. + """ + total = 0.0 + for before, after in zip(rows, rows[1:]): + total += (int(after["time"]) - int(before["time"])) * max( + 1.0, float(after["busy_vcpus"]) / cpus + ) + return total + + +def top_processes(rows): + """The TOP processes by lifetime footprint peak. + + [pid, command, peak bytes, selection, time]. + """ + best = {} + for row in rows: + for pid, command, _, peak, label in json.loads( + row.get("top_footprints") or "[]" + ): + known = best.get(pid) + if known is None or peak > known[2]: + best[pid] = [ + pid, + command, + peak, + label or (known[3] if known else ""), + row["time"], + ] + elif label and not known[3]: + known[3] = label + return sorted(best.values(), key=lambda process: process[2], reverse=True)[:TOP] + + +def footprint_captures(directory): + """[(file, its header and IOAccelerator lines)] of the `footprint` captures.""" + captured = [] + for path in sorted(directory.glob("footprint-*.txt")): + lines = [ + line.strip() + for line in path.read_text(errors="replace").splitlines() + if line.strip() + ] + kept = [ + line for line in lines if "Footprint" in line or "IOAccelerator" in line + ][:4] or lines[:1] + captured.append((path.name, kept)) + return captured + + +def summary(directory): + """The report's Markdown lines; also writes summary.json.""" + with open(directory / SAMPLES, newline="") as handle: + rows = list(csv.DictReader(handle)) + if not rows: + return ["Resource sampler: no samples."] + facts = { + "samples": len(rows), + "seconds": int(rows[-1]["time"]) - int(rows[0]["time"]), + "peaks": {}, + } + lines = [] + machine = directory / MACHINE + cpus = None + if machine.is_file(): + cpus, memsize = (int(value) for value in machine.read_text().split()) + facts["machine"] = {"vcpus": cpus, "memory_bytes": memsize} + lines.append(f"Machine: {cpus} vCPUs, {memsize / GIB:.1f} GiB.") + for key, _ in CLASSES + (("footprint_bytes", "footprints"),): + known = [row for row in rows if number(row.get(key)) is not None] + peak = max(known, key=lambda row: number(row[key]), default=None) + facts["peaks"][key] = ( + None + if peak is None + else {"bytes": number(peak[key]), "time": int(peak["time"])} + ) + + def peak_bytes(key): + return None if facts["peaks"][key] is None else facts["peaks"][key]["bytes"] + + busy = [float(row["busy_vcpus"]) for row in rows] + facts["pressure"] = max(int(row["pressure"]) for row in rows) + facts["busy_vcpus"] = { + "mean": sum(busy) / len(busy), + "p95": percentile(busy, 0.95), + "max": max(busy), + } + lines += [ + "| Samples | " + + " | ".join(f"{name} (GiB)" for _, name in CLASSES) + + " | Worst pressure | Busy vCPUs mean | p95 | max |", + "|---" * (len(CLASSES) + 5) + "|", + f"| {len(rows)} over {facts['seconds']} s | " + + " | ".join(gib(peak_bytes(key)) for key, _ in CLASSES) + + f" | {facts['pressure']} | {facts['busy_vcpus']['mean']:.2f} | " + f"{facts['busy_vcpus']['p95']:.2f} | " + f"{facts['busy_vcpus']['max']:.2f} |", + "", + "Each class peaks at its own time. Used = app + wired + compressed " + "(`vm_stat`); app holds Metal buffers; the file cache is reclaimable.", + ] + if facts["peaks"]["used_bytes"]: + moment = facts["peaks"]["used_bytes"]["time"] + running = selections_at(directory / MARKS, moment) + facts["selections_at_peak_used"] = running + lines.append( + f"Peak used at {utc(moment)} UTC" + + (f", during: {', '.join(running)}." if running else ".") + ) + top = top_processes(rows) + facts["top_processes"] = [ + { + "pid": pid, + "command": command, + "peak_footprint_bytes": footprint, + "selection": label, + "time": int(stamp), + } + for pid, command, footprint, label, stamp in top + ] + if top: + lines += [ + "", + "| Process | PID | Peak footprint (GiB) | Selection | Seen at (UTC) |", + "|---|---|---|---|---|", + ] + lines += [ + f"| `{command}` | {pid} | {gib(footprint)} | {label or '-'} " + f"| {utc(stamp)} |" + for pid, command, footprint, label, stamp in top + ] + lines.append( + "Footprints: `proc_pid_rusage` lifetime peak (includes " + "IOAccelerator/Metal memory), processes of this user only; their sum " + f"peaked at {gib(peak_bytes('footprint_bytes'))} GiB." + ) + largest = max(rows, key=lambda row: int(row["top_rss_bytes"])) + lines.append( + "Largest RSS (`ps`, earlier runs' figure): " + f"{gib(int(largest['top_rss_bytes']))} GiB " + f"(`{largest['top_command']}`)." + ) + if cpus: + facts["scaled_seconds"] = { + str(n): scaled_seconds(rows, n) for n in SCALED_VCPUS if n < cpus + } + if facts["scaled_seconds"]: + lines.append( + f"Sampled {facts['seconds']} s; at " + + ", at ".join( + f"{n} vCPUs about {seconds:.0f} s" + for n, seconds in facts["scaled_seconds"].items() + ) + + " (each interval stretched by busy vCPUs / vCPUs where busy " + "exceeds them)." + ) + captures = footprint_captures(directory) + facts["footprint_tool"] = "present" if os.access(FOOTPRINT, os.X_OK) else "absent" + facts["footprint_captures"] = [ + {"file": name, "lines": kept} for name, kept in captures + ] + lines.append( + f"`{FOOTPRINT}`: {facts['footprint_tool']}, {len(captures)} captures " + "in the samples artifact." + ) + lines += [ + f"- `{name}`: " + "; ".join(f"`{line}`" for line in kept) + for name, kept in captures + ] + (directory / SUMMARY).write_text(json.dumps(facts, indent=2, sort_keys=True) + "\n") + return lines + + +def report(directory): + pid = directory / PID + if pid.is_file(): + try: + os.kill(int(pid.read_text()), signal.SIGTERM) + except (OSError, ValueError): + pass + lines = ["### Resource samples (report-only)", "", *summary(directory)] + print("\n".join(lines)) + step_summary = os.environ.get("GITHUB_STEP_SUMMARY") + if step_summary: + with open(step_summary, "a") as handle: + handle.write("\n".join(lines) + "\n\n") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + for name in ("start", "run", "report"): + command = commands.add_parser(name) + command.add_argument("directory", type=Path) + if name != "report": + command.add_argument("--interval", type=float, default=5.0) + marking = commands.add_parser("mark") + marking.add_argument("event") + marking.add_argument("label") + marking.add_argument("pid", nargs="?") + args = parser.parse_args(argv) + try: + if args.command == "start": + start(args.directory, args.interval) + elif args.command == "run": + run(args.directory, args.interval) + elif args.command == "mark": + mark(args.event, args.label, args.pid) + else: + report(args.directory) + except Exception as error: # Report-only: never fail the job. + print(f"::warning title=Resource sampler::{type(error).__name__}: {error}") + return 0 + + +if __name__ == "__main__": + sys.exit(main())
diff --git ml-explore/mlx/.github/scripts/codeql_artifacts.py Layr-Labs/mlx/.github/scripts/codeql_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..dacee361744f10718b59c8234eee408850b2f725 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/codeql_artifacts.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Bind read-only CodeQL SARIF to the exact Actions run before upload.""" + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess +import urllib.parse +from pathlib import Path, PurePosixPath + +# BEGIN DATA VALIDATOR +LANGUAGES = { + "actions": "/language:actions", + "cpp": "/language:c-cpp", + "python": "/language:python", +} +CODEQL_VERSION = "2.27.4" +MAX_FILE = 16 * 1024 * 1024 +MAX_BUNDLE = 64 * 1024 * 1024 + + +def context(): + return { + key: os.environ[env] + for key, env in { + "repository": "GITHUB_REPOSITORY", + "sha": "GITHUB_SHA", + "ref": "GITHUB_REF", + "run_id": "GITHUB_RUN_ID", + "attempt": "GITHUB_RUN_ATTEMPT", + }.items() + } + + +def relative_path(value): + if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: + raise ValueError("invalid bundle path") + path = PurePosixPath(value) + if path.is_absolute() or any(part in ("..", ".git") for part in path.parts): + raise ValueError("bundle path escapes its data directory") + if path.as_posix() != value: + raise ValueError("bundle path is not canonical") + return path + + +def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def validate_sarif(sarif): + if sarif.get("version") != "2.1.0" or not sarif.get("runs"): + raise ValueError("invalid SARIF") + if not any( + run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"] + ): + raise ValueError("analysis has no rules") + for run in sarif["runs"]: + driver = run.get("tool", {}).get("driver", {}) + if ( + driver.get("name") != "CodeQL" + or driver.get("semanticVersion") != CODEQL_VERSION + ): + raise ValueError("SARIF was not produced by the qualified CodeQL version") + artifacts = run.get("artifacts", []) + for result in run.get("results", []): + locations = result.get("locations", []) + if not locations: + continue + primary = locations[0].get("physicalLocation", {}) + location = primary.get("artifactLocation", {}) + if "uri" not in location and "index" in location: + index = location["index"] + if type(index) is not int or not 0 <= index < len(artifacts): + raise ValueError("invalid artifact index") + location = artifacts[index]["location"] + uri = urllib.parse.urlsplit(location.get("uri", "")) + if uri.scheme or uri.netloc: + raise ValueError("source location is not repository relative") + relative_path(urllib.parse.unquote(uri.path)) + if primary.get("region", {}).get("startLine") is not None: + fingerprint = result.get("partialFingerprints", {}).get( + "primaryLocationLineHash", "" + ) + if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint): + raise ValueError("source-line finding lacks a stable fingerprint") + + +def verify_bundle(root, expected): + root = root.resolve(strict=True) + manifest_file = root / "manifest.json" + if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024: + raise ValueError("invalid manifest") + manifest = json.loads(manifest_file.read_text()) + if manifest.get("context") != expected or manifest.get("version") != 1: + raise ValueError( + "scan belongs to another run, attempt, repository, ref or commit" + ) + if ( + manifest.get("codeql_version") != CODEQL_VERSION + or manifest.get("categories") != LANGUAGES + ): + raise ValueError("unexpected CodeQL recipe") + files = manifest.get("files") + if not isinstance(files, dict) or len(files) != 3: + raise ValueError("invalid file inventory") + required = {f"sarif/{language}.sarif" for language in LANGUAGES} + if not required.issubset(files): + raise ValueError("missing language") + actual = set() + total = 0 + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("symlinks are not scan data") + if not path.is_file(): + if path.is_dir(): + continue + raise ValueError("only regular files are scan data") + rel = path.relative_to(root).as_posix() + if rel == "manifest.json": + continue + relative_path(rel) + if not path.resolve().is_relative_to(root): + raise ValueError("file escapes bundle") + spec = files.get(rel) + size = path.stat().st_size + if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE: + raise ValueError("unexpected or oversized file") + if spec.get("size") != size or spec.get("sha256") != digest(path): + raise ValueError("scan data changed") + if rel not in required: + raise ValueError("only the three SARIF files may be supplied") + actual.add(rel) + total += size + if actual != set(files) or total > MAX_BUNDLE: + raise ValueError("file inventory differs or bundle exceeds limit") + for language in LANGUAGES: + sarif = json.loads((root / f"sarif/{language}.sarif").read_text()) + validate_sarif(sarif) + # The official uploader falls back to event SHA/ref without a checkout. + # Native CodeQL already supplies every primary-line fingerprint. + empty_checkout = root / "empty-checkout" + empty_checkout.mkdir(exist_ok=True) + return empty_checkout + + +# END DATA VALIDATOR + + +def pack_bundle(checkout, results, output): + checkout = checkout.resolve(strict=True) + expected = context() + actual_sha = subprocess.check_output( + ["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True + ).strip() + if actual_sha != expected["sha"]: + raise ValueError("checkout is not the event commit") + output.mkdir(parents=True, exist_ok=False) + (output / "sarif").mkdir() + used = 0 + for language in LANGUAGES: + source = results / f"{language}.sarif" + if source.is_symlink() or source.stat().st_size > MAX_FILE: + raise ValueError("invalid SARIF input") + data = json.loads(source.read_text()) + validate_sarif(data) + used += source.stat().st_size + if used > MAX_BUNDLE: + raise ValueError("bundle exceeds limit") + destination = output / "sarif" / source.name + shutil.copyfile(source, destination) + destination.chmod(0o644) + files = { + path.relative_to(output).as_posix(): { + "sha256": digest(path), + "size": path.stat().st_size, + } + for path in sorted(output.rglob("*")) + if path.is_file() + } + manifest = { + "version": 1, + "context": expected, + "codeql_version": CODEQL_VERSION, + "categories": LANGUAGES, + "files": files, + } + (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + verify_bundle(output, expected) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkout", type=Path, required=True) + parser.add_argument("--results", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + pack_bundle(args.checkout, args.results, args.output)
diff --git ml-explore/mlx/.github/scripts/codeql_artifacts_test.py Layr-Labs/mlx/.github/scripts/codeql_artifacts_test.py new file mode 100644 index 0000000000000000000000000000000000000000..dae67fdb562a158678506c9eb45b38ffa8c5768c --- /dev/null +++ Layr-Labs/mlx/.github/scripts/codeql_artifacts_test.py @@ -0,0 +1,194 @@ +import copy +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location( + "bundle", Path(__file__).with_name("codeql_artifacts.py") +) +bundle = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(bundle) + + +class DataBoundaryTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.expected = { + "repository": "Layr-Labs/mlx", + "sha": "a" * 40, + "ref": "refs/pull/42/merge", + "run_id": "7", + "attempt": "1", + } + (self.root / "sarif").mkdir() + for language in bundle.LANGUAGES: + data = { + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "CodeQL", + "semanticVersion": "2.27.4", + "rules": [{"id": "example"}], + } + }, + "results": [], + } + ], + } + (self.root / f"sarif/{language}.sarif").write_text(json.dumps(data)) + self.manifest = { + "version": 1, + "context": self.expected, + "codeql_version": "2.27.4", + "categories": bundle.LANGUAGES, + } + self.seal() + + def seal(self): + self.manifest["files"] = { + p.relative_to(self.root).as_posix(): { + "sha256": bundle.digest(p), + "size": p.stat().st_size, + } + for p in self.root.rglob("*") + if p.is_file() and p.name != "manifest.json" + } + (self.root / "manifest.json").write_text(json.dumps(self.manifest)) + + def test_valid_bundle_and_fork_merge_attribution(self): + self.assertEqual( + bundle.verify_bundle(self.root, self.expected), + self.root.resolve() / "empty-checkout", + ) + + def test_every_context_dimension_is_bound(self): + for key in self.expected: + changed = copy.deepcopy(self.expected) + changed[key] += "-different" + with self.subTest(key=key), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, changed) + + def test_content_changes_are_rejected(self): + (self.root / "sarif/actions.sarif").write_text("altered content\n") + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_missing_language_is_rejected(self): + (self.root / "sarif/python.sarif").unlink() + self.seal() + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_extra_files_and_incorrect_inventory_are_rejected(self): + (self.root / "unexpected.sh").write_text("exit 0\n") + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + self.seal() + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_source_symlinks_are_rejected(self): + (self.root / "link").symlink_to("/etc/passwd") + with self.assertRaisesRegex(ValueError, "symlink"): + bundle.verify_bundle(self.root, self.expected) + + def test_ruleless_or_malformed_sarif_is_rejected(self): + p = self.root / "sarif/actions.sarif" + p.write_text( + json.dumps( + {"version": "2.1.0", "runs": [{"tool": {"driver": {"rules": []}}}]} + ) + ) + self.seal() + with self.assertRaisesRegex(ValueError, "no rules"): + bundle.verify_bundle(self.root, self.expected) + + def test_bounds_are_enforced(self): + with patch.object(bundle, "MAX_BUNDLE", 1), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + with patch.object(bundle, "MAX_FILE", 1), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_traversal_git_and_ambiguous_paths_are_rejected(self): + for path in ( + "../private", + "/tmp/private", + "source/../private", + "source/.git/config", + "a\\b", + "a//b", + ): + with self.subTest(path=path), self.assertRaises(ValueError): + bundle.relative_path(path) + + def test_primary_locations_and_fingerprints_are_required(self): + primary = { + "artifactLocation": {"uri": "mlx/ops.cpp"}, + "region": {"startLine": 12}, + } + result = { + "locations": [{"physicalLocation": primary}], + "partialFingerprints": {"primaryLocationLineHash": "ab12:1"}, + } + data = { + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "CodeQL", + "semanticVersion": "2.27.4", + "rules": [{"id": "rule"}], + } + }, + "results": [result], + } + ], + } + bundle.validate_sarif(data) + del result["partialFingerprints"] + with self.assertRaisesRegex(ValueError, "fingerprint"): + bundle.validate_sarif(data) + primary["artifactLocation"]["uri"] = "../private" + with self.assertRaises(ValueError): + bundle.validate_sarif(data) + + def test_different_tool_version_is_rejected(self): + p = self.root / "sarif/cpp.sarif" + data = json.loads(p.read_text()) + data["runs"][0]["tool"]["driver"]["semanticVersion"] = "different" + p.write_text(json.dumps(data)) + self.seal() + with self.assertRaisesRegex(ValueError, "CodeQL version"): + bundle.verify_bundle(self.root, self.expected) + + def test_publisher_embeds_the_exact_tested_validator(self): + source = ( + Path(bundle.__file__) + .read_text() + .split("# BEGIN DATA VALIDATOR\n", 1)[1] + .split("# END DATA VALIDATOR", 1)[0] + ) + workflow = ( + Path(__file__) + .parents[1] + .joinpath("workflows/codeql-native.yml") + .read_text() + ) + # YAML removes this common indentation before the shell sees the program. + embedded = "\n".join( + line[10:] if line.startswith(" ") else line + for line in workflow.splitlines() + ) + self.assertIn(source.strip(), embedded) + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx/.github/scripts/fedora-proot/fedora_proot.py Layr-Labs/mlx/.github/scripts/fedora-proot/fedora_proot.py new file mode 100755 index 0000000000000000000000000000000000000000..4a47bad41ceda86f42bbf715df5d2ad200a1b37f --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fedora-proot/fedora_proot.py @@ -0,0 +1,475 @@ +#!/usr/bin/env python3 +"""Run MLX's Fedora 42 C++ build test in Fedora userspace on a Darkbloom ARM64 runner. + +The sandbox has no Docker, so the unchanged Fedora build script +(.github/scripts/setup+build-cpp-linux-fedora-container.sh) runs under PRoot, built here +from pinned source, in the official archived Fedora 42 container rootfs. PRoot +translates paths and fakes UID 0 through ptrace; it is not an isolation boundary (the +job VM is). +""" + +import argparse +import hashlib +import http.client +import json +import os +import platform +import shutil +import subprocess +import tarfile +import time +import urllib.request +from pathlib import Path, PurePosixPath + +PTRACE_PROBE = r""" +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/prctl.h> +#include <sys/ptrace.h> +#include <sys/wait.h> +#include <unistd.h> +int main(void) { + if (getuid() != 1000 || geteuid() != 1000 || prctl(PR_GET_NO_NEW_PRIVS,0,0,0,0) != 1) + return 10; + printf("PTRACE_PROBE uid=%lu dumpable=%d no_new_privs=1\n", + (unsigned long)getuid(), prctl(PR_GET_DUMPABLE)); + fflush(stdout); + pid_t child = fork(); + if (child < 0) { perror("fork"); return 11; } + if (!child) { + if (ptrace(PTRACE_TRACEME,0,0,0)) { perror("PTRACE_TRACEME"); _exit(12); } + raise(SIGSTOP); _exit(0); + } + int status; + if (waitpid(child,&status,0) != child || !WIFSTOPPED(status)) return 13; + if (ptrace(PTRACE_CONT,child,0,0)) { perror("PTRACE_CONT"); return 14; } + if (waitpid(child,&status,0) != child || !WIFEXITED(status) || WEXITSTATUS(status)) + return 15; + puts("PTRACE_PROBE_OK"); return 0; +} +""" + + +def load_pins(): + return json.loads(Path(__file__).with_name("pins.json").read_text()) + + +def verified(path, spec): + if path.stat().st_size != spec["size"]: + raise ValueError(f"wrong size: {path.name}") + with path.open("rb") as src: + digest = hashlib.file_digest(src, "sha256").hexdigest() + if digest != spec["sha256"]: + raise ValueError(f"wrong SHA-256: {path.name}") + + +OCI_GZIP_LAYER = "application/vnd.oci.image.layer.v1.tar+gzip" + + +def oci_layer(archive, spec, target): + """Write the one pinned gzip layer of the pinned archived OCI image to target. + + Only index.json, the pinned manifest and the pinned layer are read; the index + must name exactly that manifest, whose bytes must hash to its digest, and the + manifest must list exactly that one layer (media type, digest and size). + """ + if target.exists(): + verified(target, spec) + return + manifest_sha = spec["manifest"].removeprefix("sha256:") + part = target.with_name(target.name + ".part") + with tarfile.open(archive, "r:xz") as src: + + def regular(name, limit): + member = src.getmember(name) + if not member.isfile() or member.size > limit: + raise ValueError(f"unexpected OCI member: {name}") + return member + + index = json.loads(src.extractfile(regular("index.json", 1 << 16)).read()) + manifests = index.get("manifests") + if ( + not isinstance(manifests, list) + or len(manifests) != 1 + or manifests[0].get("digest") != spec["manifest"] + ): + raise ValueError("OCI index must name exactly the pinned manifest") + raw = src.extractfile(regular("blobs/sha256/" + manifest_sha, 1 << 16)).read() + if hashlib.sha256(raw).hexdigest() != manifest_sha: + raise ValueError("OCI manifest does not match its digest") + layers = json.loads(raw).get("layers") + if ( + not isinstance(layers, list) + or len(layers) != 1 + or layers[0].get("mediaType") != OCI_GZIP_LAYER + or layers[0].get("digest") != "sha256:" + spec["sha256"] + or layers[0].get("size") != spec["size"] + ): + raise ValueError("OCI manifest must list exactly the pinned gzip layer") + with ( + src.extractfile( + regular("blobs/sha256/" + spec["sha256"], spec["size"]) + ) as data, + part.open("xb") as out, + ): + shutil.copyfileobj(data, out) + verified(part, spec) + part.rename(target) + + +def patch_proot_faccessat2(src): + """Add faccessat2 (439) to PRoot 5.4.1's ARM64 syscall table before it is built. + + The table stops at clone3, so PRoot passes faccessat2 to the kernel untranslated: + a guest `test -x` (bash uses faccessat2) would read the host's path, not the + guest's. enter.c and the seccomp filter already handle PR_faccessat2. + """ + table = src / "syscall" / "sysnums-arm64.h" + text = table.read_text() + anchor = " [435] = PR_clone3,\n" + if text.count(anchor) != 1 or "PR_faccessat2" in text: + raise RuntimeError("unexpected PRoot ARM64 syscall table") + text = text.replace(anchor, anchor + " [439] = PR_faccessat2,\n") + table.write_text(text) + return hashlib.sha256(text.encode()).hexdigest() + + +def verify_inputs(inputs, pins): + """Every pinned download, and the rootfs layer derived from the OCI archive.""" + for name, spec in pins["files"].items(): + verified(inputs / name, spec) + verified(inputs / "fedora.tar.gz", pins["fedora_layer"]) + + +def download(url, part, size, attempts=3, pause=5): + """One pinned download with bounded retries; any stale partial file goes first.""" + for attempt in range(1, attempts + 1): + part.unlink(missing_ok=True) + try: + with urllib.request.urlopen(url, timeout=60) as src, part.open("xb") as out: + copied = 0 + while chunk := src.read(1024 * 1024): + copied += len(chunk) + if copied > size: + raise ValueError(f"oversized download: {part.name}") + out.write(chunk) + if copied != size: + raise ValueError( + f"truncated download: {part.name} ({copied} of {size} bytes)" + ) + return + except (OSError, ValueError, http.client.HTTPException) as error: + part.unlink(missing_ok=True) + if attempt == attempts: + raise + print( + f"FEDORA_PROOT_RETRY {part.name} attempt {attempt}: " + f"{type(error).__name__}: {error}", + flush=True, + ) + time.sleep(pause * attempt) + + +def fetch_inputs(dest, pins): + dest.mkdir(parents=True, exist_ok=True) + for name, spec in pins["files"].items(): + target = dest / name + if not target.exists(): + part = dest / (name + ".part") + download(spec["url"], part, spec["size"]) + verified(part, spec) + part.rename(target) + verified(target, spec) + layer = pins["fedora_layer"] + oci_layer(dest / layer["archive"], layer, dest / "fedora.tar.gz") + + +def extract_root(archive, dest): + """One pinned layer, no overlay merging; links are created after regular files. + + This order prevents tar members writing through links, including absolute + rootfs links. Device nodes are unnecessary: /dev is an explicit PRoot bind. + All real ownership remains the calling runner; setuid/setgid bits are dropped. + """ + dest.mkdir() + dest = dest.resolve() + seen = set() + links = [] + with tarfile.open(archive, "r:*") as src: + for member in src: + p = PurePosixPath(member.name) + if p.is_absolute() or ".." in p.parts or not p.parts: + raise ValueError(f"unsafe tar path: {member.name}") + if any(part.startswith(".wh.") for part in p.parts): + raise ValueError("overlay whiteouts require a different unpacker") + key = str(p) + if key == ".": + continue + if key in seen: + raise ValueError(f"duplicate tar path: {key}") + seen.add(key) + target = dest.joinpath(*p.parts) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + elif member.isfile(): + target.parent.mkdir(parents=True, exist_ok=True) + with src.extractfile(member) as source, target.open("xb") as out: + shutil.copyfileobj(source, out) + target.chmod(member.mode & 0o777) + elif member.issym() or member.islnk(): + links.append((member, target)) + elif not (member.ischr() or member.isblk() or member.isfifo()): + raise ValueError(f"unsupported tar entry: {key}") + # Hardlinks must name an already extracted regular file, never a symlink. + for member, target in links: + if not member.islnk(): + continue + link = PurePosixPath(member.linkname) + source = dest.joinpath(*link.parts) + if link.is_absolute() or ".." in link.parts or not source.is_file(): + raise ValueError(f"unsafe hardlink: {member.name}") + target.parent.mkdir(parents=True, exist_ok=True) + os.link(source, target) + for member, target in links: + if member.issym(): + if not target.parent.resolve().is_relative_to(dest): + raise ValueError(f"symlink parent escapes root: {member.name}") + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(member.linkname) + + +def archived_repos(root): + root = root.resolve(strict=True) + repo_dir = root / "etc/yum.repos.d" + target = repo_dir / "pilot-fedora42.repo" + if root.stat().st_uid != os.geteuid(): + raise ValueError("rootfs is not owned by this job user") + for path in (repo_dir, target): + if not path.resolve().is_relative_to(root): + raise ValueError("repository configuration escapes the owned rootfs") + repo_dir.mkdir(parents=True, exist_ok=True) + for repo in repo_dir.glob("*.repo"): + repo.rename(repo.with_suffix(".repo.disabled-pilot")) + key = "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-42-primary" + text = "" + for name, suffix in ( + ("fedora", "releases/42/Everything/aarch64/os"), + ("updates", "updates/42/Everything/aarch64"), + ): + text += ( + f"[{name}]\nname=Fedora 42 archived {name}\n" + f"baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/{suffix}/\n" + f"enabled=1\ngpgcheck=1\ngpgkey={key}\n\n" + ) + target.write_text(text) + + +SCRIPT = ".github/scripts/setup+build-cpp-linux-fedora-container.sh" + + +def run_pilot(work, source, pins): + if platform.system() != "Linux" or platform.machine() != "aarch64": + raise RuntimeError("run only on a Linux ARM64 runner") + if os.getuid() != 1000 or os.geteuid() != 1000: + raise RuntimeError("run as the unchanged UID1000 job user") + status = Path("/proc/self/status").read_text() + if "NoNewPrivs:\t1" not in status: + raise RuntimeError("the job must inherit no_new_privs") + work.mkdir(parents=True, exist_ok=False) + start = time.monotonic() + evidence = { + "pins": pins, + "host_arch": platform.machine(), + "uid": os.getuid(), + "kernel": platform.release(), + "steps": [], + "result": "running", + } + + def call(name, args, *, cwd=work, env=None, timeout=180): + before = time.monotonic() + print(f"FEDORA_PROOT_STEP {name}", flush=True) + with (work / (name + ".log")).open("w") as log: + proc = subprocess.Popen( + args, + cwd=cwd, + env=env, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + import signal + + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + evidence["steps"].append( + { + "name": name, + "seconds": time.monotonic() - before, + "exit": "timeout", + } + ) + print( + (work / (name + ".log")).read_text(errors="replace"), + end="", + flush=True, + ) + raise + duration = time.monotonic() - before + evidence["steps"].append( + {"name": name, "seconds": duration, "exit": proc.returncode} + ) + print((work / (name + ".log")).read_text(errors="replace"), end="", flush=True) + if proc.returncode: + raise subprocess.CalledProcessError(proc.returncode, args) + + try: + script = (source / SCRIPT).resolve(strict=True) + if not script.is_file() or not script.is_relative_to(source): + raise RuntimeError("the checked-out Fedora build script is missing") + inputs = work / "inputs" + fetch_inputs(inputs, pins) + verify_inputs(inputs, pins) + (work / "ptrace.c").write_text(PTRACE_PROBE) + call( + "ptrace-build", + ["cc", "-O2", "-Wall", "-Wextra", "-Werror", "ptrace.c", "-o", "ptrace"], + ) + call("ptrace", [str(work / "ptrace")], timeout=15) + deps = work / "deps" + for deb in ( + "libtalloc-dev.deb", + "libtalloc2.deb", + "pkgconf-bin.deb", + "libpkgconf3.deb", + ): + call(deb, ["dpkg-deb", "--extract", str(inputs / deb), str(deps)]) + (deps / "usr/bin/pkg-config").symlink_to("pkgconf") + extract_root(inputs / "proot.tar.gz", work / "proot-source") + proot_src = work / "proot-source" / ("proot-" + pins["proot_commit"]) / "src" + evidence["proot_arm64_table_sha256"] = patch_proot_faccessat2(proot_src) + lib = deps / "usr/lib/aarch64-linux-gnu" + env = dict( + os.environ, + PKG_CONFIG_LIBDIR=str(lib / "pkgconfig"), + PKG_CONFIG_SYSROOT_DIR=str(deps), + LDFLAGS=f"-Wl,-rpath,{lib}", + PATH=f"{deps / 'usr/bin'}:{os.environ['PATH']}", + LD_LIBRARY_PATH=str(lib), + ) + call( + "proot-build", + ["make", "-j2", "HAS_SWIG=", "HAS_PYTHON_CONFIG=", "proot"], + cwd=proot_src, + env=env, + ) + proot = proot_src / "proot" + call("proot-version", [str(proot), "--version"]) + with proot.open("rb") as src: + evidence["proot_sha256"] = hashlib.file_digest(src, "sha256").hexdigest() + extract_root(inputs / "fedora.tar.gz", work / "fedora") + root = work / "fedora" + if "VERSION_ID=42" not in (root / "etc/os-release").read_text(): + raise RuntimeError("rootfs is not Fedora42") + archived_repos(root) + scratch = work / "tmp" + scratch.mkdir() + command = [ + str(proot), + "-0", + "-r", + str(root), + "-b", + "/dev", + "-b", + "/proc", + "-b", + f"{scratch}:/tmp", + "-b", + f"{source}:/work", + "-w", + "/work", + ] + # The checkout belongs to the runner's UID 1000; git in the fake-root guest + # must accept it. + guest = dict( + os.environ, + GIT_CONFIG_COUNT="1", + GIT_CONFIG_KEY_0="safe.directory", + GIT_CONFIG_VALUE_0="/work", + ) + # No sudo, no Docker, no namespaces/capabilities, no host /etc or /run bind. + call( + "fedora-smoke", + command + + [ + "/bin/bash", + "-ec", + "cat /etc/fedora-release; test $(uname -m) = aarch64; " + # faccessat2 translation: Fedora has dnf and no apt-get; the Ubuntu host + # has apt-get. + "test -x /usr/bin/dnf; test ! -x /usr/bin/apt-get; " + "test $(id -u) = 0; ldd --version; dnf --version; " + "grep '^NoNewPrivs:' /proc/self/status; (true)& wait", + ], + env=guest, + timeout=60, + ) + # Exercise actual DNS/proxy/TLS and both literal archive repositories + # before the expensive build, using Fedora's own libcurl/trust store. + call( + "fedora-archive-network", + command + ["/usr/bin/dnf", "-q", "makecache", "--refresh"], + env=guest, + timeout=300, + ) + call( + "fedora-build-test", + command + ["/bin/bash", "/work/" + SCRIPT], + env=guest, + timeout=1800, + ) + evidence["result"] = "pass" + except BaseException as error: + evidence["result"] = "failure" + evidence["error_type"] = type(error).__name__ + raise + finally: + evidence["seconds"] = time.monotonic() - start + (work / "evidence.json").write_text(json.dumps(evidence, indent=2) + "\n") + print( + json.dumps({k: v for k, v in evidence.items() if k != "pins"}, indent=2), + flush=True, + ) + print("FEDORA_PROOT_EVIDENCE " + str(work / "evidence.json"), flush=True) + print("FEDORA_PROOT_OK " + evidence["result"], flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("fetch", "run")) + parser.add_argument( + "--inputs", type=Path, help="fetch: download and verify the pinned inputs here" + ) + parser.add_argument( + "--source", type=Path, help="run: the MLX checkout to build and test" + ) + parser.add_argument("--work", type=Path, help="run: a new private work directory") + args = parser.parse_args() + pins = load_pins() + if args.action == "fetch": + if args.inputs is None: + parser.error("fetch requires --inputs") + fetch_inputs(args.inputs.resolve(), pins) + else: + if args.source is None or args.work is None: + parser.error("run requires --source and --work") + run_pilot(args.work.resolve(), args.source.resolve(strict=True), pins) + + +if __name__ == "__main__": + main()
diff --git ml-explore/mlx/.github/scripts/fedora-proot/pins.json Layr-Labs/mlx/.github/scripts/fedora-proot/pins.json new file mode 100644 index 0000000000000000000000000000000000000000..34fb962429b092b9ba196b5fb32e9c416416f7a0 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fedora-proot/pins.json @@ -0,0 +1,43 @@ +{ + "schema": 1, + "proot_commit": "d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00", + "fedora_manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794", + "files": { + "fedora.oci.tar.xz": { + "url": "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/Fedora-Container-Base-Generic-42-1.1.aarch64.oci.tar.xz", + "size": 57715532, + "sha256": "137a907cd0931d9c4c7cfd5467031e03da3715141f24c39078c7b7f76c809038" + }, + "proot.tar.gz": { + "url": "https://codeload.github.com/proot-me/proot/tar.gz/d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00", + "size": 234642, + "sha256": "25ffd8f31f32a0edd644da770008d8b8ee99197da03dc80cd20226b3012b7d26" + }, + "libtalloc-dev.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc-dev_2.4.2-1build2_arm64.deb", + "size": 62224, + "sha256": "d63fc770129092ba8c40d44db4e2d740f645d5291ea6a9bf9b61d7e5294dcf5c" + }, + "libtalloc2.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc2_2.4.2-1build2_arm64.deb", + "size": 26748, + "sha256": "4b182e41db5537937a423fc8f9593c65330553442eba17e058c4cc1c7a73a382" + }, + "pkgconf-bin.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/pkgconf-bin_1.8.1-2build1_arm64.deb", + "size": 20458, + "sha256": "bcd0d24c48b8b73ed7ba20ffc21a3575d5d9bdd53c3cee5a8051b7bde5fbf638" + }, + "libpkgconf3.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/libpkgconf3_1.8.1-2build1_arm64.deb", + "size": 31226, + "sha256": "f476cb81e1ecec6bf974f21181469cf5edcc749c4ead621469cdbf584dfd3be8" + } + }, + "fedora_layer": { + "archive": "fedora.oci.tar.xz", + "manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794", + "sha256": "cfc0be9fb5518ec8eb4521cdb4dc2ee14df42924e0f468d24a8e6cfbdda5fdc9", + "size": 58468983 + } +}
diff --git ml-explore/mlx/.github/scripts/fedora-proot/test_fedora_proot.py Layr-Labs/mlx/.github/scripts/fedora-proot/test_fedora_proot.py new file mode 100644 index 0000000000000000000000000000000000000000..7656bba1447e8602276f461926fa049dd7fb8574 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fedora-proot/test_fedora_proot.py @@ -0,0 +1,410 @@ +import hashlib +import importlib.util +import io +import json +import tarfile +import tempfile +import unittest +import unittest.mock +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("pilot", HERE / "fedora_proot.py") +pilot = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(pilot) + + +class InputValidation(unittest.TestCase): + def test_size_and_digest_must_both_match(self): + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) / "input" + p.write_bytes(b"approved") + spec = {"size": 8, "sha256": hashlib.sha256(b"approved").hexdigest()} + pilot.verified(p, spec) + p.write_bytes(b"replaced") + with self.assertRaisesRegex(ValueError, "SHA-256"): + pilot.verified(p, spec) + p.write_bytes(b"short") + with self.assertRaisesRegex(ValueError, "size"): + pilot.verified(p, spec) + + def extract(self, entries, tmp): + archive = Path(tmp) / "layer.tar" + with tarfile.open(archive, "w") as tar: + for name, typ, content in entries: + info = tarfile.TarInfo(name) + info.type = typ + if typ == tarfile.REGTYPE: + info.size = len(content) + info.mode = 0o6755 + tar.addfile(info, io.BytesIO(content)) + else: + info.linkname = content + tar.addfile(info) + root = Path(tmp) / "root" + pilot.extract_root(archive, root) + return root + + def test_absolute_rootfs_symlink_is_created_last(self): + with tempfile.TemporaryDirectory() as tmp: + root = self.extract( + [ + ("lib", tarfile.SYMTYPE, "/usr/lib"), + ("usr/lib/tool", tarfile.REGTYPE, b"tool"), + ], + tmp, + ) + self.assertEqual((root / "lib").readlink(), Path("/usr/lib")) + self.assertEqual((root / "usr/lib/tool").read_bytes(), b"tool") + self.assertEqual((root / "usr/lib/tool").stat().st_mode & 0o6000, 0) + + def test_bad_paths_and_overlay_layers_are_refused(self): + for name in ("/outside", "../outside", "usr/../../outside", "usr/.wh.hidden"): + with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(ValueError): + self.extract([(name, tarfile.REGTYPE, b"bad")], tmp) + + def test_symlink_cannot_redirect_another_symlink_outside(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaisesRegex(ValueError, "parent escapes"): + self.extract( + [ + ("escape", tarfile.SYMTYPE, tmp), + ("escape/other", tarfile.SYMTYPE, "/usr/lib"), + ], + tmp, + ) + self.assertFalse((Path(tmp) / "other").exists()) + + def test_duplicate_and_escaping_hardlinks_are_refused(self): + cases = [ + [("tool", tarfile.REGTYPE, b"x"), ("tool", tarfile.REGTYPE, b"y")], + [("tool", tarfile.LNKTYPE, "../../outside")], + ] + for entries in cases: + with tempfile.TemporaryDirectory() as tmp, self.assertRaises(ValueError): + self.extract(entries, tmp) + + def test_archived_repos_keep_package_signature_checks(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + repo = root / "etc/yum.repos.d" + repo.mkdir(parents=True) + (repo / "mirror.repo").write_text("metalink=https://unbounded.example/\n") + pilot.archived_repos(root) + files = list(repo.glob("*.repo")) + self.assertEqual(len(files), 1) + text = files[0].read_text() + self.assertEqual(text.count("gpgcheck=1"), 2) + self.assertNotIn("metalink", text) + self.assertEqual(text.count("https://archives.fedoraproject.org/"), 2) + + def test_repository_writes_cannot_follow_rootfs_links_outside(self): + for escape_file in (False, True): + with ( + self.subTest(escape_file=escape_file), + tempfile.TemporaryDirectory() as tmp, + ): + root = Path(tmp) / "root" + outside = Path(tmp) / "outside" + root.mkdir() + outside.mkdir() + (root / "etc").mkdir() + if escape_file: + (root / "etc/yum.repos.d").mkdir() + (root / "etc/yum.repos.d/pilot-fedora42.repo").symlink_to( + outside / "target" + ) + else: + (root / "etc/yum.repos.d").symlink_to(outside) + with self.assertRaisesRegex(ValueError, "escapes"): + pilot.archived_repos(root) + self.assertEqual(list(outside.iterdir()), []) + + +class OciLayer(unittest.TestCase): + """The archived Fedora OCI image: only its one pinned gzip layer, by digest.""" + + LAYER = "application/vnd.oci.image.layer.v1.tar+gzip" + + def build(self, tmp, layers=1, manifests=1, media=None, tamper_manifest=False): + layer = b"layer-bytes-" * 100 + digest = hashlib.sha256(layer).hexdigest() + entries = [ + { + "mediaType": media or self.LAYER, + "digest": "sha256:" + digest, + "size": len(layer), + } + ] * layers + manifest = json.dumps({"schemaVersion": 2, "layers": entries}).encode() + mdigest = hashlib.sha256(manifest).hexdigest() + stored = manifest + (b" " if tamper_manifest else b"") + index = json.dumps( + { + "schemaVersion": 2, + "manifests": [{"digest": "sha256:" + mdigest}] * manifests, + } + ).encode() + archive = Path(tmp) / "fedora.oci.tar.xz" + with tarfile.open(archive, "w:xz") as tar: + for name, data in ( + ("index.json", index), + ("blobs/sha256/" + mdigest, stored), + ("blobs/sha256/" + digest, layer), + ): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + spec = { + "archive": "fedora.oci.tar.xz", + "manifest": "sha256:" + mdigest, + "sha256": digest, + "size": len(layer), + } + return archive, spec, layer + + def test_pinned_layer_is_extracted_and_verified(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, layer = self.build(tmp) + target = Path(tmp) / "fedora.tar.gz" + pilot.oci_layer(archive, spec, target) + self.assertEqual(target.read_bytes(), layer) + pilot.oci_layer(archive, spec, target) # an existing verified layer is kept + + def test_other_manifest_layers_or_media_are_refused(self): + cases = [ + dict(layers=2), + dict(manifests=2), + dict(media="application/vnd.oci.image.layer.v1.tar"), + dict(tamper_manifest=True), + ] + for case in cases: + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp, **case) + with self.assertRaises(ValueError): + pilot.oci_layer(archive, spec, Path(tmp) / "fedora.tar.gz") + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def test_pins_must_name_the_manifest_and_layer(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + for change in ( + {"manifest": "sha256:" + "0" * 64}, + {"sha256": "0" * 64}, + {"size": spec["size"] - 1}, + ): + with self.assertRaises(ValueError): + pilot.oci_layer( + archive, dict(spec, **change), Path(tmp) / "fedora.tar.gz" + ) + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def rebuild(self, tmp, archive, replace): + """Copy archive, replacing members by name: (TarInfo, bytes or None).""" + out = Path(tmp) / "hostile.oci.tar.xz" + with tarfile.open(archive, "r:xz") as src, tarfile.open(out, "w:xz") as dst: + for member in src: + if member.name in replace: + info, data = replace[member.name] + dst.addfile(info, io.BytesIO(data) if data is not None else None) + else: + dst.addfile(member, src.extractfile(member)) + return out + + def test_non_regular_or_oversized_members_are_refused(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + link = tarfile.TarInfo("blobs/sha256/" + spec["sha256"]) + link.type = tarfile.SYMTYPE + link.linkname = "index.json" + big = json.dumps( + {"manifests": [{"digest": spec["manifest"]}], "pad": "x" * (1 << 16)} + ).encode() + index = tarfile.TarInfo("index.json") + index.size = len(big) + for replace in ({link.name: (link, None)}, {"index.json": (index, big)}): + hostile = self.rebuild(tmp, archive, replace) + with self.assertRaisesRegex(ValueError, "unexpected OCI member"): + pilot.oci_layer(hostile, spec, Path(tmp) / "fedora.tar.gz") + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def test_existing_target_must_be_the_pinned_layer(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + target = Path(tmp) / "fedora.tar.gz" + target.write_bytes(b"not the layer") + with self.assertRaises(ValueError): + pilot.oci_layer(archive, spec, target) + + def test_fetch_inputs_derives_the_layer_and_verify_inputs_checks_it(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, layer = self.build(tmp) + raw = archive.read_bytes() + pins = { + "files": { + "fedora.oci.tar.xz": { + "url": "https://unused.invalid/", + "size": len(raw), + "sha256": hashlib.sha256(raw).hexdigest(), + } + }, + "fedora_layer": spec, + } + dest = Path(tmp) / "inputs" + dest.mkdir() + (dest / "fedora.oci.tar.xz").write_bytes(raw) + pilot.fetch_inputs(dest, pins) # present and verified: no download + self.assertEqual((dest / "fedora.tar.gz").read_bytes(), layer) + pilot.verify_inputs(dest, pins) + (dest / "fedora.tar.gz").write_bytes(b"x" * len(layer)) + with self.assertRaisesRegex(ValueError, "SHA-256"): + pilot.verify_inputs(dest, pins) + + def test_rootfs_comes_from_the_archived_oci_image(self): + pins = json.loads((HERE / "pins.json").read_text()) + layer = pins["fedora_layer"] + self.assertNotIn("fedora.tar.gz", pins["files"]) + source = pins["files"][layer["archive"]] + self.assertTrue( + source["url"].startswith( + "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/" + ) + ) + self.assertEqual(pins["fedora_manifest"], layer["manifest"]) + self.assertEqual(len(layer["sha256"]), 64) + self.assertGreater(layer["size"], 0) + + +class ProotFaccessat2(unittest.TestCase): + """PRoot 5.4.1's ARM64 table lacks faccessat2 (439). + + Guest access checks would otherwise read host paths. + """ + + TABLE = ( + "static const Sysnum sysnums_arm64[] = {\n" + " [291] = PR_statx,\n" + " [435] = PR_clone3,\n" + "};\n" + ) + + def table(self, tmp, text): + path = Path(tmp) / "syscall" + path.mkdir() + (path / "sysnums-arm64.h").write_text(text) + return Path(tmp) + + def test_faccessat2_is_added_once_after_clone3(self): + with tempfile.TemporaryDirectory() as tmp: + src = self.table(tmp, self.TABLE) + digest = pilot.patch_proot_faccessat2(src) + text = (src / "syscall/sysnums-arm64.h").read_text() + self.assertIn(" [435] = PR_clone3,\n [439] = PR_faccessat2,\n", text) + self.assertEqual(digest, hashlib.sha256(text.encode()).hexdigest()) + + def test_unexpected_tables_are_refused(self): + for text in ( + self.TABLE.replace("[435] = PR_clone3,", ""), + self.TABLE + " [435] = PR_clone3,\n", + self.TABLE.replace("};", " [439] = PR_faccessat2,\n};"), + ): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(RuntimeError): + pilot.patch_proot_faccessat2(self.table(tmp, text)) + + +class Downloads(unittest.TestCase): + """Pinned downloads retry a bounded number of times; no partial file is kept.""" + + class Response(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def test_a_stale_partial_file_is_removed_before_the_first_attempt(self): + calls = [] + + def urlopen(url, timeout): + calls.append(url) + return self.Response(b"approved") + + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + part.write_bytes(b"stale") + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + # One attempt: the stale file was removed up front, not after a failure. + self.assertEqual(len(calls), 1) + + def test_a_truncated_body_is_retried(self): + bodies = [b"appr", b"approved"] + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object( + pilot.urllib.request, + "urlopen", + lambda url, timeout: self.Response(bodies.pop(0)), + ), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + self.assertEqual(bodies, []) + + def test_a_failed_attempt_is_retried_after_removing_the_partial_file(self): + calls = [] + + def urlopen(url, timeout): + calls.append(url) + if len(calls) == 1: + raise OSError("Tunnel connection failed: 502 Bad Gateway") + return self.Response(b"approved") + + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + part.write_bytes(b"stale") + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + self.assertEqual(len(calls), 2) + + def test_retries_are_bounded_and_oversized_bodies_refused(self): + calls = [] + + def urlopen(url, timeout): + calls.append(url) + return self.Response(b"x" * 9) + + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + with self.assertRaisesRegex(ValueError, "oversized"): + pilot.download("https://example.invalid/x", part, 8, attempts=2) + self.assertFalse(part.exists()) + self.assertEqual(len(calls), 2) + + def test_pins_name_no_mlx_source_archive(self): + pins = json.loads((HERE / "pins.json").read_text()) + self.assertNotIn("mlx.tar.gz", pins["files"]) + self.assertFalse({"mlx_commit", "mlx_script", "mlx_script_sha256"} & set(pins)) + for spec in pins["files"].values(): + self.assertEqual(len(spec["sha256"]), 64) + self.assertTrue(spec["url"].startswith("https://")) + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx/.github/scripts/find-eligible-contributors.js Layr-Labs/mlx/.github/scripts/find-eligible-contributors.js deleted file mode 100644 index 296c8f2be69b06b1ef3b5177b624c9a93b1171c8..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/scripts/find-eligible-contributors.js +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/env node - -/** - * find-eligible-contributors.js - * - * Finds users who have opened pull requests on a GitHub repo, - * are NOT collaborators on that repo, and match: - * - fewer than 5 currently open PRs - * - more than 2 merged PRs - * - merge rate (merged / closed) > 50% - * - "low priority" PRs < 50% - * - * Usage: - * GITHUB_TOKEN=xxxx node find-eligible-contributors.js <owner> <repo> - */ - -const GITHUB_API = 'https://api.github.com'; - -function authHeaders(token) { - return { - Authorization: `Bearer ${token}`, - Accept: 'application/vnd.github+json', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'find-eligible-contributors-script', - }; -} - -async function fetchAllPages(url, token, { stopWhen } = {}) { - const results = []; - let page = 1; - const perPage = 100; - const concurrentRequests = 5; - - while (true) { - const responses = await Promise.all( - Array.from({ length: concurrentRequests }, async (_, index) => { - const pageUrl = new URL(url); - pageUrl.searchParams.set('per_page', String(perPage)); - pageUrl.searchParams.set('page', String(page + index)); - - const res = await fetch(pageUrl, { headers: authHeaders(token) }); - if (!res.ok) { - const body = await res.text(); - throw new Error(`GitHub API error ${res.status} for ${pageUrl}: ${body}`); - } - return res.json(); - }) - ); - - let end = false; - for (const data of responses) { - if (!Array.isArray(data) || data.length === 0) { - end = true; - continue; - } - if (data.length < perPage) { - end = true; - } - - for (const item of data) { - if (stopWhen && stopWhen(item)) break; - results.push(item); - } - } - - if (end) { - break; - } - - page += concurrentRequests; - } - - return results; -} - -async function fetchPullRequests(owner, repo, token) { - const url = `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=all&sort=created&direction=desc`; - - const oneYearAgo = new Date(); - oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1); - - return fetchAllPages(url, token, { - stopWhen: (pr) => new Date(pr.created_at) < oneYearAgo, - }); -} - -async function fetchCollaborators(owner, repo, token) { - const url = `${GITHUB_API}/repos/${owner}/${repo}/collaborators`; - const collaborators = await fetchAllPages(url, token); - return new Set(collaborators.map((c) => c.login)); -} - -/** - * Aggregate per-user PR stats from the list of PRs. - * Returns Map<login, { - * open: number, - * closed: number, - * merged: number, - * total: number, - * lowPriority: number, - * mostRecentCreatedAt: Date - * }> - */ -function aggregateUserStats(pullRequests) { - const stats = new Map(); - - for (const pr of pullRequests) { - const login = pr.user?.login; - if (!login) continue; - - if (!stats.has(login)) { - stats.set(login, { - open: 0, - closed: 0, - merged: 0, - total: 0, - lowPriority: 0, - mostRecentCreatedAt: null, - }); - } - const s = stats.get(login); - - s.total += 1; - if (pr.labels?.some((label) => label.name === 'low priority')) { - s.lowPriority += 1; - } - - if (pr.state === 'open') { - s.open += 1; - } else if (pr.state === 'closed') { - s.closed += 1; - if (pr.merged_at) { - s.merged += 1; - } - } - - const createdAt = new Date(pr.created_at); - if (!s.mostRecentCreatedAt || createdAt > s.mostRecentCreatedAt) { - s.mostRecentCreatedAt = createdAt; - } - } - - return stats; -} - -/** - * Apply eligibility filters: - * - fewer than 5 currently open PRs - * - more than 2 merged PRs - * - merge rate (merged / closed) > 50% - * - "low priority" PRs < 50% - * - not a collaborator - * - has an open PR or at least one PR within the past 6 weeks - */ -function filterEligibleUsers(stats, collaboratorLogins) { - const SIX_WEEKS_MS = 6 * 7 * 24 * 60 * 60 * 1000; - const cutoff = new Date((new Date).getTime() - SIX_WEEKS_MS); - const eligible = []; - - for (const [login, s] of stats.entries()) { - if (s.open >= 5) continue; - if (s.merged <= 2) continue; - if (collaboratorLogins.has(login)) continue; - if (s.open == 0 && s.mostRecentCreatedAt < cutoff) continue; - if ((s.merged / s.closed) < 0.5) continue; - if ((s.lowPriority / s.total) > 0.5) continue; - - eligible.push(login); - } - return eligible; -} - -/** - * Given a repo (owner/repo) and a GitHub token, returns the login names of - * eligible external contributors matching all filters. - * - * @param {Object} params - * @param {string} params.owner - Repo owner (user or org). - * @param {string} params.repo - Repo name. - * @param {string} params.token - GitHub token with repo read (and ideally push) access. - * @returns {Promise<string[]>} - */ -async function findEligibleContributors({ owner, repo, token } = {}) { - if (!owner || !repo) { - throw new Error('findEligibleContributors requires both "owner" and "repo".'); - } - if (!token) { - throw new Error('findEligibleContributors requires a "token".'); - } - - const [pullRequests, collaboratorLogins] = await Promise.all([ - fetchPullRequests(owner, repo, token), - fetchCollaborators(owner, repo, token), - ]); - - const stats = aggregateUserStats(pullRequests); - return filterEligibleUsers(stats, collaboratorLogins); -} - -// ---- CLI entry point ---- - -function isRunAsCLI() { - return import.meta.url === `file://${process.argv[1]}`; -} - -async function runCLI() { - const [, , owner, repo] = process.argv; - if (!owner || !repo) { - console.error('Usage: node find-eligible-contributors.js <owner> <repo>'); - process.exit(1); - } - const token = process.env.GITHUB_TOKEN; - if (!token) { - console.error('Error: set GITHUB_TOKEN environment variable with a valid GitHub token.'); - process.exit(1); - } - - console.error(`Fetching pull requests and collaborators for ${owner}/${repo} in parallel...`); - const eligibleLogins = await findEligibleContributors({ owner, repo, token }); - - console.log(JSON.stringify(eligibleLogins, null, 2)); - console.error(`\n${eligibleLogins.length} user(s) match the criteria.`); -} - -if (isRunAsCLI()) { - runCLI().catch((err) => { - console.error('Fatal error:', err); - process.exit(1); - }); -} - -export { findEligibleContributors };
diff --git ml-explore/mlx/.github/scripts/fork-tests/metal-cache/xcrun Layr-Labs/mlx/.github/scripts/fork-tests/metal-cache/xcrun new file mode 100755 index 0000000000000000000000000000000000000000..5b7de48845032488017d64dbd3a60606bb7d6b05 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fork-tests/metal-cache/xcrun @@ -0,0 +1,94 @@ +#!/bin/bash +# A cache for the Metal kernel build of fork-tests.yml. +# +# The build jobs put this folder first in PATH. The kernel rules in +# mlx/backend/metal/kernels/CMakeLists.txt call "xcrun -sdk macosx metal" +# to compile each .metal file to an .air file and to link the .air files to +# mlx.metallib. This script gives those two calls a cache. It sends all other +# calls to /usr/bin/xcrun without a change. +# +# The key of an .air file is the SHA-256 of the toolchain ID, the arguments +# without "-o FILE", and the preprocessed source. The key of a .metallib file +# is the SHA-256 of the toolchain ID and the arguments, with each .air input +# replaced by the SHA-256 of its content. +# +# Environment: +# MLX_METAL_CACHE_TOOLCHAIN the metal compiler version and the SDK build +# MLX_METAL_CACHE_IN the folder with the restored entries +# MLX_METAL_CACHE_OUT the folder that gets every entry that this +# build uses; the job saves this folder +# If one of them is not set, the script only calls /usr/bin/xcrun. +set -euo pipefail + +real=/usr/bin/xcrun + +if [[ -z "${MLX_METAL_CACHE_TOOLCHAIN:-}" || -z "${MLX_METAL_CACHE_IN:-}" || + -z "${MLX_METAL_CACHE_OUT:-}" || $# -lt 4 || + "$1" != "-sdk" || "$2" != "macosx" || "$3" != "metal" ]]; then + exec "$real" "$@" +fi + +out="" +compile=0 +key_args=() +pre_args=() +args=("${@:4}") +i=0 +while (( i < ${#args[@]} )); do + arg=${args[i]} + if [[ $arg == "-o" && $(( i + 1 )) -lt ${#args[@]} ]]; then + out=${args[i + 1]} + pre_args+=(-o -) + i=$(( i + 2 )) + continue + fi + if [[ $arg == "-c" ]]; then + compile=1 + key_args+=(-c) + pre_args+=(-E) + elif [[ $arg == *.air && -f $arg ]]; then + key_args+=("air:$(shasum -a 256 < "$arg" | cut -d ' ' -f 1)") + pre_args+=("$arg") + else + key_args+=("$arg") + pre_args+=("$arg") + fi + i=$(( i + 1 )) +done + +if [[ $compile == 1 && $out == *.air ]]; then + mode=compile +elif [[ $compile == 0 && $out == *.metallib ]]; then + mode=link +else + exec "$real" "$@" +fi + +{ + printf '%s\0' "$MLX_METAL_CACHE_TOOLCHAIN" "$mode" "${key_args[@]}" + if [[ $mode == compile ]]; then + # The toolchain mount folder has a random suffix on each runner, for + # example MetalToolchain-v17.6.109.0.oxYh3g. Remove it from the line + # markers, and keep the version. + "$real" -sdk macosx metal "${pre_args[@]}" 2>/dev/null | + sed -E 's#(MetalToolchain-v[0-9.]*[0-9])\.[A-Za-z0-9]+/#\1/#g' + fi +} > "$out.key" || { + rm -f "$out.key" + exec "$real" "$@" +} +key=$(shasum -a 256 < "$out.key" | cut -d ' ' -f 1) +rm -f "$out.key" + +mkdir -p "$MLX_METAL_CACHE_OUT" +log="$MLX_METAL_CACHE_OUT.log" +if [[ -f "$MLX_METAL_CACHE_IN/$key" ]]; then + cp "$MLX_METAL_CACHE_IN/$key" "$out" + echo "hit $mode $(basename "$out")" >> "$log" +else + "$real" "$@" + echo "miss $mode $(basename "$out")" >> "$log" +fi +tmp="$MLX_METAL_CACHE_OUT/$key.$$" +cp "$out" "$tmp" +mv "$tmp" "$MLX_METAL_CACHE_OUT/$key"
diff --git ml-explore/mlx/.github/scripts/fork-tests/metal_cpp.py Layr-Labs/mlx/.github/scripts/fork-tests/metal_cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..69c8c04cbea5a5ef9490bd73ac0d6c839b75fbed --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fork-tests/metal_cpp.py @@ -0,0 +1,129 @@ +"""Fetch the pinned Apple headers before a native CI build.""" + +import hashlib +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import zipfile +from pathlib import Path, PurePosixPath + +URL = "https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip" +SHA256 = "4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4" +SIZE = 260405 +ATTEMPTS = 4 + + +def download(path, *, run=subprocess.run, sleep=time.sleep): + partial = path.with_suffix(".partial") + for attempt in range(1, ATTEMPTS + 1): + partial.unlink(missing_ok=True) + try: + result = run( + [ + "curl", + "--disable", + "--fail", + "--location", + "--proto", + "=https", + "--proto-redir", + "=https", + "--connect-timeout", + "10", + "--max-time", + "60", + "--max-filesize", + str(SIZE), + "--silent", + "--show-error", + "--output", + str(partial), + URL, + ], + timeout=65, + check=False, + ) + if result.returncode == 0 and partial.stat().st_size == SIZE: + if hashlib.sha256(partial.read_bytes()).hexdigest() == SHA256: + partial.replace(path) + return + except (OSError, subprocess.TimeoutExpired): + pass + partial.unlink(missing_ok=True) + print( + f"Apple header download attempt {attempt}/{ATTEMPTS} failed", + file=sys.stderr, + ) + if attempt < ATTEMPTS: + sleep(2) + raise RuntimeError("Apple headers failed the bounded download/integrity check") + + +def unpack(archive, destination): + with zipfile.ZipFile(archive) as source: + entries = source.infolist() + if ( + len(entries) > 512 + or sum(item.file_size for item in entries) > 16 * 1024 * 1024 + ): + raise ValueError("Apple header archive exceeds its bounds") + names = set() + files = set() + for item in entries: + path = PurePosixPath(item.filename) + mode = stat.S_IFMT(item.external_attr >> 16) + if ( + path.is_absolute() + or ".." in path.parts + or "\\" in item.filename + or "\x00" in item.filename + or not path.parts + or path.parts[0] != "metal-cpp" + or path.as_posix() != item.filename.rstrip("/") + or path in names + or item.flag_bits & 1 + or mode not in (0, stat.S_IFREG, stat.S_IFDIR) + ): + raise ValueError("unsafe Apple header archive entry") + names.add(path) + if not item.is_dir(): + files.add(path) + required = { + PurePosixPath("metal-cpp") / name + for name in ( + "Metal/Metal.hpp", + "Foundation/Foundation.hpp", + "QuartzCore/QuartzCore.hpp", + ) + } + if not required.issubset(files): + raise ValueError("Apple header archive is incomplete") + destination.mkdir() + for item in entries: + target = destination / item.filename + if item.is_dir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + with source.open(item) as reader, target.open("xb") as writer: + shutil.copyfileobj(reader, writer) + return destination / "metal-cpp" + + +def main(): + directory = Path(tempfile.mkdtemp(prefix="mlx-metal-cpp-", dir="/tmp")) + try: + archive = directory / "headers.zip" + download(archive) + source = unpack(archive, directory / "source") + print(f"cmake-args=-DFETCHCONTENT_SOURCE_DIR_METAL_CPP={source}") + except BaseException: + shutil.rmtree(directory) + raise + + +if __name__ == "__main__": + main()
diff --git ml-explore/mlx/.github/scripts/fork-tests/python-shards.json Layr-Labs/mlx/.github/scripts/fork-tests/python-shards.json new file mode 100644 index 0000000000000000000000000000000000000000..8d181d7fedb8b25d7f14dc21ceba0ce3a42954a2 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fork-tests/python-shards.json @@ -0,0 +1,98 @@ +{ + "gpu": [ + [ + "test_quantized", + "test_ops", + "test_reduce", + "test_nn", + "test_threads", + "test_autograd", + "test_vmap", + "test_conv", + "test_optimizers", + "test_fast", + "test_linalg", + "test_load", + "test_eval", + "test_einsum", + "test_export_import", + "test_upsample", + "test_memory", + "test_init", + "test_random", + "test_losses", + "test_zero_copy", + "test_bf16", + "test_conv_transpose", + "test_double", + "test_constants", + "test_device", + "test_extension", + "test_graph", + "test_metal_threadgroup_bounds", + "test_tree" + ], + [ + "test_fast_sdpa", + "test_fast_gated_delta", + "test_compile", + "test_fft", + "test_array", + "test_blas" + ] + ], + "cpu": [ + [ + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_simdgroup", + "test_fast_sdpa.TestFastSDPA.test_sdpa_vector_gqa_long", + "test_fft", + "test_fast_gated_delta:rest", + "test_ops", + "test_array", + "test_conv", + "test_eval", + "test_autograd", + "test_metal_threadgroup_bounds", + "test_zero_copy", + "test_bf16", + "test_einsum", + "test_double", + "test_memory" + ], + [ + "test_quantized:rest", + "test_reduce", + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_sequential", + "test_compile", + "test_quantized.TestQuantized.test_qmv_wide", + "test_quantized.TestQuantized.test_gather_qmm_sorted", + "test_nn", + "test_quantized.TestQuantized.test_qmv", + "test_fast", + "test_upsample", + "test_threads", + "test_random", + "test_vmap", + "test_conv_transpose", + "test_tree", + "test_graph" + ], + [ + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_nax", + "test_fast_sdpa.TestFastSDPA.test_sdpa", + "test_fast_sdpa:rest", + "test_export_import", + "test_quantized.TestQuantized.test_gather_qmm_sorted_nax_large_m", + "test_blas", + "test_quantized.TestQuantized.test_qmm_large_dims", + "test_optimizers", + "test_load", + "test_extension", + "test_linalg", + "test_init", + "test_constants", + "test_losses", + "test_device" + ] + ] +}
diff --git ml-explore/mlx/.github/scripts/fork-tests/python_shards.py Layr-Labs/mlx/.github/scripts/fork-tests/python_shards.py new file mode 100755 index 0000000000000000000000000000000000000000..a1fc84736ec5e82c8e36e7fb6772a072cb3b13ef --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fork-tests/python_shards.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +"""Check and run the Python test shards of fork-tests.yml. + +The shard map (python-shards.json) has one list of shards for each pass +("gpu" and "cpu"). A shard is a list of entries. Each entry runs in its own +child process, and the child writes its own log. An entry is one of these: + + test_x all tests in python/tests/test_x.py + test_x.Class.test_y one test (or a class with test_x.Class) + test_x:rest the tests in test_x.py that no other entry names + +Commands: + + check Check the map without importing mlx. Every + python/tests/test*.py file must be in the map of + each pass exactly one time: as one whole-file + entry, or as named entries with at most one rest + entry. The command fails on any other case. + run PASS SHARD COUNT Check the map, expand the split files to test IDs + (this imports them), and fail if the named IDs of + a split file are not a partition of its tests. + Then run the entries of shard SHARD, JOBS at a + time. COUNT is the number of shard jobs in the + workflow, and it must equal the shards in the map. + verify DIR Read the test ID files that the shard jobs wrote + and fail if a test ran in two shards of a pass or + if a shard result is missing. +""" + +import argparse +import json +import os +import re +import subprocess +import sys +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +TESTS = Path("python/tests") +MAP = Path(__file__).with_name("python-shards.json") +PASSES = ("gpu", "cpu") + + +def parse(entry): + """Return (file, kind) for a map entry.""" + if entry.endswith(":rest"): + return entry[: -len(":rest")], "rest" + if "." in entry: + return entry.split(".", 1)[0], "named" + return entry, "whole" + + +def load_map(): + with open(MAP) as f: + data = json.load(f) + if sorted(data) != sorted(PASSES): + sys.exit(f"error: {MAP} must have exactly the keys {PASSES}") + return data + + +def check_static(shards): + """Return a list of errors. Does not import mlx or the test files.""" + errors = [] + files = sorted(p.stem for p in TESTS.glob("test*.py")) + for name in PASSES: + uses = {} + entries = [] + for index, shard in enumerate(shards[name]): + if not shard: + errors.append(f"{name} shard {index} has no entries") + for entry in shard: + file, kind = parse(entry) + uses.setdefault(file, []).append((index, kind, entry)) + entries.append(entry) + for entry in sorted({e for e in entries if entries.count(e) > 1}): + errors.append(f"{name}: the entry {entry} is in the map more than one time") + for file in files: + found = uses.pop(file, []) + kinds = [kind for _, kind, _ in found] + where = ", ".join(f"shard {i}: {e}" for i, _, e in found) + if not found: + errors.append(f"{name}: {TESTS}/{file}.py is in no shard") + elif "whole" in kinds and len(found) > 1: + errors.append( + f"{name}: {TESTS}/{file}.py is in more than one shard " + f"or entry ({where})" + ) + elif kinds.count("rest") > 1: + errors.append( + f"{name}: {TESTS}/{file}.py has more than one rest entry ({where})" + ) + for file, found in sorted(uses.items()): + names = ", ".join(e for _, _, e in found) + errors.append(f"{name}: {names} names no file {TESTS}/{file}.py") + return errors + + +def flatten(suite): + for test in suite: + if isinstance(test, unittest.TestSuite): + yield from flatten(test) + else: + yield test + + +def test_ids(module): + suite = unittest.defaultTestLoader.loadTestsFromName(module) + ids = [test.id() for test in flatten(suite)] + bad = [i for i in ids if not i.startswith(module + ".")] + if bad: + sys.exit(f"error: {module} did not load: {bad}") + return ids + + +def expand(shards, name): + """Expand the entries of one pass to child arguments. + + Returns a list (one item for each shard) of lists of (entry, names), + where names is the list of unittest names for the child. Also returns + a list of errors. + """ + errors = [] + split = {} + for shard in shards[name]: + for entry in shard: + file, kind = parse(entry) + if kind != "whole": + split.setdefault(file, []).append(entry) + sys.path.insert(0, str(TESTS)) + owner = {} + rest_ids = {} + for file, entries in sorted(split.items()): + ids = test_ids(file) + count = {i: 0 for i in ids} + for entry in entries: + if parse(entry)[1] != "named": + continue + matched = [i for i in ids if i == entry or i.startswith(entry + ".")] + if not matched: + errors.append(f"{name}: the entry {entry} matches no test in {file}.py") + for i in matched: + count[i] += 1 + owner[i] = entry + twice = [i for i, c in count.items() if c > 1] + if twice: + errors.append(f"{name}: these tests are in more than one entry: {twice}") + missing = [i for i, c in count.items() if c == 0] + if f"{file}:rest" in entries: + rest_ids[file] = missing + elif missing: + errors.append( + f"{name}: these tests of {file}.py are in no shard: {missing}" + ) + plan = [] + for shard in shards[name]: + units = [] + for entry in shard: + file, kind = parse(entry) + if kind == "whole": + units.append((entry, [entry])) + elif kind == "rest": + units.append((entry, rest_ids.get(file, []))) + else: + units.append((entry, sorted(i for i, e in owner.items() if e == entry))) + plan.append(units) + return plan, errors + + +def child(log_dir, unit, names): + """Run the tests in names in this process. Used by run.""" + # The same settings as python/tests/run.py. + os.environ["MLX_ENABLE_TF32"] = "0" + os.environ["MLX_ENABLE_CACHE_THRASHING_CHECK"] = "0" + sys.path.insert(0, str(TESTS)) + import mlx.core as mx + + exclude = set(os.environ.get("CPU_EXCLUDE", "").split()) + suite = unittest.defaultTestLoader.loadTestsFromNames(names) + tests = [t for t in flatten(suite) if t.id() not in exclude] + ran = [] + + class Result(unittest.TextTestResult): + def startTest(self, test): + ran.append(test.id()) + super().startTest(test) + + runner = unittest.TextTestRunner( + sys.stdout, verbosity=2, durations=0, resultclass=Result + ) + result = runner.run(unittest.TestSuite(tests)) + with open(Path(log_dir) / f"{unit}.ids", "w") as f: + json.dump(ran, f) + mx.clear_streams() + sys.exit(0 if result.wasSuccessful() else 1) + + +def file_name(entry): + return re.sub(r"[^A-Za-z0-9_.-]", "_", entry) + + +def run(args): + shards = load_map() + errors = check_static(shards) + if errors: + report(errors) + if args.count != len(shards[args.name]): + report( + [ + f"the workflow runs {args.count} {args.name} shard jobs, " + f"but {MAP.name} has {len(shards[args.name])} {args.name} shards" + ] + ) + plan, errors = expand(shards, args.name) + if errors: + report(errors) + units = plan[args.shard] + logs = Path(args.logs) + logs.mkdir(parents=True, exist_ok=True) + lock = threading.Lock() + results = {} + + def one(unit): + entry, names = unit + name = file_name(entry) + start = time.monotonic() + with open(logs / f"{name}.log", "w") as log: + code = subprocess.run( + [sys.executable, "-u", __file__, "child", str(logs), name, *names], + stdout=log, + stderr=subprocess.STDOUT, + ).returncode + seconds = time.monotonic() - start + with lock: + results[entry] = (code, seconds) + state = "passed" if code == 0 else f"failed (exit code {code})" + print(f"{entry}: {state} in {seconds:.1f} s", flush=True) + # Print the end of a failed log at once. The full logs print + # after all entries finish, and a killed job never gets there. + if code != 0: + tail = ( + (logs / f"{name}.log") + .read_text(errors="replace") + .splitlines()[-80:] + ) + print("\n".join(f" | {line}" for line in tail), flush=True) + + print( + f"{args.name} shard {args.shard}: {len(units)} entries, {args.jobs} at a time", + flush=True, + ) + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + list(pool.map(one, units)) + + ran = {} + failed = [] + for entry, _ in units: + name = file_name(entry) + print(f"::group::Python tests ({args.name}): {entry}") + print((logs / f"{name}.log").read_text(errors="replace"), end="") + print("::endgroup::") + if results[entry][0] != 0: + failed.append(entry) + ids_file = logs / f"{name}.ids" + ran[entry] = json.loads(ids_file.read_text()) if ids_file.exists() else [] + out = { + "pass": args.name, + "shard": args.shard, + "count": args.count, + "entries": { + e: { + "exit": results[e][0], + "seconds": round(results[e][1], 1), + "tests": ran[e], + } + for e, _ in units + }, + } + with open(logs / f"testids-{args.name}-{args.shard}.json", "w") as f: + json.dump(out, f) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as f: + f.write(f"### Python tests, {args.name} pass, shard {args.shard}\n\n") + f.write("| Entry | Result | Tests | Seconds |\n|---|---|---|---|\n") + for e, _ in sorted(units, key=lambda u: -results[u[0]][1]): + code, seconds = results[e] + state = "passed" if code == 0 else f"failed ({code})" + f.write(f"| `{e}` | {state} | {len(ran[e])} | {seconds:.1f} |\n") + total = sum(len(t) for t in ran.values()) + f.write(f"\nTests started: {total}\n\n") + if failed: + names = " ".join(failed) + print(f"::error::Python test entries that failed ({args.name} pass): {names}") + sys.exit(1) + + +def verify(args): + shards = load_map() + errors = [] + lines = [ + "### Python tests in all shards", + "", + "| Pass | Shards | Tests started |", + "|---|---|---|", + ] + for name in PASSES: + seen = {} + found = 0 + for index in range(len(shards[name])): + path = Path(args.dir) / f"testids-{name}-{index}.json" + if not path.exists(): + errors.append(f"{name} shard {index} wrote no result ({path.name})") + continue + found += 1 + data = json.loads(path.read_text()) + for entry, info in data["entries"].items(): + for test in info["tests"]: + seen.setdefault(test, []).append(f"shard {index} {entry}") + twice = {t: w for t, w in seen.items() if len(w) > 1} + for test, where in sorted(twice.items()): + errors.append(f"{name}: {test} ran more than one time: {where}") + lines.append(f"| {name} | {found} of {len(shards[name])} | {len(seen)} |") + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as f: + f.write("\n".join(lines) + "\n\n") + print("\n".join(lines)) + if errors: + report(errors) + + +def report(errors): + for error in errors: + print(f"::error::{error}") + sys.exit(1) + + +def main(): + if len(sys.argv) > 1 and sys.argv[1] == "child": + child(sys.argv[2], sys.argv[3], sys.argv[4:]) + return + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("check") + p = sub.add_parser("run") + p.add_argument("name", choices=PASSES) + p.add_argument("shard", type=int) + p.add_argument("count", type=int) + p.add_argument("--jobs", type=int, default=1) + p.add_argument("--logs", required=True) + p = sub.add_parser("verify") + p.add_argument("dir") + args = parser.parse_args() + if args.command == "check": + errors = check_static(load_map()) + if errors: + report(errors) + print(f"{MAP.name}: every test file is in exactly one place in each pass.") + elif args.command == "run": + if not 0 <= args.shard < args.count: + report([f"shard {args.shard} is not in 0..{args.count - 1}"]) + run(args) + else: + verify(args) + + +if __name__ == "__main__": + main()
diff --git ml-explore/mlx/.github/scripts/fork-tests/test_metal_cpp.py Layr-Labs/mlx/.github/scripts/fork-tests/test_metal_cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cf327957baece4339171d16199576ded32c670 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/fork-tests/test_metal_cpp.py @@ -0,0 +1,158 @@ +import hashlib +import io +import stat +import subprocess +import tempfile +import unittest +import warnings +import zipfile +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import metal_cpp + + +def archive(entries=()): + data = io.BytesIO() + with warnings.catch_warnings(), zipfile.ZipFile(data, "w") as output: + warnings.simplefilter("ignore", UserWarning) + for name in ( + "Metal/Metal.hpp", + "Foundation/Foundation.hpp", + "QuartzCore/QuartzCore.hpp", + ): + output.writestr("metal-cpp/" + name, b"header") + for name, value in entries: + output.writestr(name, value) + return data.getvalue() + + +class MetalCppIntegrity(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def test_cmake_pins_the_verified_archive(self): + source = Path(__file__).resolve().parents[3] / "CMakeLists.txt" + self.assertRegex(source.read_text(), r"URL_HASH\s+SHA256=" + metal_cpp.SHA256) + self.assertIn(metal_cpp.URL, source.read_text()) + + def test_partial_transfer_retries_from_empty_file(self): + content = archive() + calls = [] + + def run(args, **kwargs): + path = Path(args[args.index("--output") + 1]) + self.assertFalse(path.exists()) + self.assertEqual(kwargs["timeout"], 65) + self.assertEqual(args[args.index("--max-filesize") + 1], str(len(content))) + self.assertIn("=https", args) + self.assertNotIn("--insecure", args) + calls.append(args) + path.write_bytes(content[:5] if len(calls) == 1 else content) + return SimpleNamespace(returncode=18 if len(calls) == 1 else 0) + + sleep = Mock() + with ( + patch.object(metal_cpp, "SIZE", len(content)), + patch.object(metal_cpp, "SHA256", hashlib.sha256(content).hexdigest()), + ): + metal_cpp.download(self.root / "headers.zip", run=run, sleep=sleep) + self.assertEqual(len(calls), 2) + self.assertEqual((self.root / "headers.zip").read_bytes(), content) + sleep.assert_called_once_with(2) + + def test_timeout_clears_partial_file_before_retry(self): + content = archive() + calls = [] + + def run(args, **kwargs): + path = Path(args[args.index("--output") + 1]) + self.assertFalse(path.exists()) + calls.append(args) + if len(calls) == 1: + path.write_bytes(content[:5]) + raise subprocess.TimeoutExpired(args, kwargs["timeout"]) + path.write_bytes(content) + return SimpleNamespace(returncode=0) + + with ( + patch.object(metal_cpp, "SIZE", len(content)), + patch.object(metal_cpp, "SHA256", hashlib.sha256(content).hexdigest()), + ): + metal_cpp.download(self.root / "headers.zip", run=run, sleep=Mock()) + self.assertEqual(len(calls), 2) + self.assertEqual((self.root / "headers.zip").read_bytes(), content) + + def test_wrong_digest_aborts_after_four_attempts(self): + content = b"bad content of expected length" + run = Mock() + + def write(args, **kwargs): + Path(args[args.index("--output") + 1]).write_bytes(content) + return SimpleNamespace(returncode=0) + + run.side_effect = write + sleep = Mock() + with ( + patch.object(metal_cpp, "SIZE", len(content)), + self.assertRaises(RuntimeError), + ): + metal_cpp.download(self.root / "headers.zip", run=run, sleep=sleep) + self.assertEqual(run.call_count, 4) + self.assertEqual(sleep.call_count, 3) + self.assertEqual(list(self.root.iterdir()), []) + + def test_failed_transfers_abort_without_publishing(self): + run = Mock(return_value=SimpleNamespace(returncode=18)) + with self.assertRaises(RuntimeError): + metal_cpp.download(self.root / "headers.zip", run=run, sleep=Mock()) + self.assertEqual(run.call_count, 4) + self.assertEqual(list(self.root.iterdir()), []) + + def test_valid_headers_extract(self): + path = self.root / "headers.zip" + path.write_bytes(archive()) + result = metal_cpp.unpack(path, self.root / "source") + self.assertEqual((result / "Metal/Metal.hpp").read_bytes(), b"header") + + def test_unsafe_paths_are_rejected_before_extraction(self): + for name in ( + "../escape", + "/escape", + "metal-cpp/../escape", + "metal-cpp\\escape", + "other/file", + ): + with self.subTest(name=name): + path = self.root / "headers.zip" + path.write_bytes(archive([(name, b"bad")])) + with self.assertRaises(ValueError): + metal_cpp.unpack(path, self.root / "source") + self.assertFalse((self.root / "source").exists()) + + def test_duplicate_or_symlink_is_rejected(self): + link = zipfile.ZipInfo("metal-cpp/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + for extra in [ + [("metal-cpp/Metal/Metal.hpp", b"duplicate")], + [(link, b"/escape")], + ]: + path = self.root / "headers.zip" + path.write_bytes(archive(extra)) + with self.assertRaises(ValueError): + metal_cpp.unpack(path, self.root / "source") + self.assertFalse((self.root / "source").exists()) + + def test_expanded_archive_bound_is_enforced(self): + path = self.root / "headers.zip" + path.write_bytes(archive([("metal-cpp/large", b"x" * (16 * 1024 * 1024))])) + with self.assertRaises(ValueError): + metal_cpp.unpack(path, self.root / "source") + self.assertFalse((self.root / "source").exists()) + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx/.github/scripts/test-ci-resource-sampler.py Layr-Labs/mlx/.github/scripts/test-ci-resource-sampler.py new file mode 100755 index 0000000000000000000000000000000000000000..fc890c16a463e536296485b0783a8ef22fe59f88 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/test-ci-resource-sampler.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +"""Offline checks of the report-only resource sampler. + +They check parsing, attribution, the summary, and that it never fails. + +The native readers (`proc_pid_rusage`, `host_statistics`) and a whole sample +run only on macOS; the CI jobs' own samples are their check. +""" + +import contextlib +import csv +import importlib.util +import io +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "scripts/ci-resource-sampler.py" +SPEC = importlib.util.spec_from_file_location("ci_resource_sampler", SCRIPT) +sampler = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(sampler) +GIB = sampler.GIB + +# macOS 27 `vm_stat` output, shortened. +VM_STAT = """Mach Virtual Memory Statistics: (page size of 16384 bytes) +Pages free: 100000. +Pages active: 200000. +Pages inactive: 150000. +Pages speculative: 5000. +Pages wired down: 50000. +Pages purgeable: 2000. +"Translation faults": 9999999. +File-backed pages: 120000. +Anonymous pages: 230000. +Pages occupied by compressor: 10000. +""" +PS = """ 1 0 0.0 512 /sbin/launchd + 100 1 12.5 204800 /usr/bin/swift-frontend + 200 150 250.0 4194304 /private/tmp/w/.build/debug/swiftpm-testing-helper + 150 1 0.0 512 /Applications/Xcode 27.app/usr/bin/my tool + garbage +""" +FOOTPRINT_TEXT = """\ +====================================================================== +swiftpm-testing-helper [200]: 64-bit Footprint: 9 GB (16384 bytes per page) +====================================================================== + + Dirty Clean Reclaimable Regions Category + 6 GB 0 B 0 B 12 IOAccelerator (graphics) + 1 GB 0 B 0 B 800 MALLOC_LARGE +""" + + +def write_rows(directory, rows): + with open(directory / sampler.SAMPLES, "w", newline="") as handle: + writer = csv.DictWriter(handle, sampler.FIELDS) + writer.writeheader() + writer.writerows(rows) + + +def row( + stamp, used, app, wired, cache, compressed, swap, pressure, busy, footprint, top +): + return { + "time": stamp, + "used_bytes": used * GIB, + "app_bytes": app * GIB, + "wired_bytes": wired * GIB, + "file_bytes": cache * GIB, + "compressed_bytes": compressed * GIB, + "swap_bytes": swap * GIB, + "pressure": pressure, + "busy_vcpus": busy, + "footprint_bytes": "" if footprint is None else footprint * GIB, + "top_rss_bytes": GIB, + "top_command": "swiftpm-testing-helper", + "top_footprints": json.dumps(top) if top else "", + } + + +class ParsingTests(unittest.TestCase): + def test_memory_counts_each_class_as_activity_monitor_does(self): + classes = sampler.memory(VM_STAT) + page = 16384 + self.assertEqual( + classes, + { + "used_bytes": (228000 + 50000 + 10000) * page, + "app_bytes": 228000 * page, + "wired_bytes": 50000 * page, + "file_bytes": 122000 * page, + "compressed_bytes": 10000 * page, + }, + ) + with self.assertRaises(KeyError): + sampler.memory(VM_STAT.replace("Anonymous pages", "Anonymous")) + + def test_swap_used_reads_each_unit(self): + self.assertEqual( + sampler.swap_used( + "total = 2048.00M used = 1536.50M free = 511.50M (encrypted)" + ), + int(1536.5 * 2**20), + ) + self.assertEqual( + sampler.swap_used("total = 4.00G used = 1.50G free = 2.50G"), + int(1.5 * GIB), + ) + self.assertEqual( + sampler.swap_used("total = 0.00M used = 0.00M free = 0.00M (encrypted)"), + 0, + ) + with self.assertRaises(AttributeError): + sampler.swap_used("no swap") + + def test_processes_keep_pid_parent_cpu_rss_and_the_command_name(self): + listed = sampler.processes(PS) + self.assertEqual(listed[1], (100, 1, 12.5, 204800 * 1024, "swift-frontend")) + self.assertEqual(listed[2][4], "swiftpm-testing-helper") + self.assertEqual(listed[3][4], "my tool") + self.assertEqual(len(listed), 4) + + def test_busy_vcpus_from_tick_deltas_survive_a_counter_wrap(self): + self.assertAlmostEqual(sampler.busy_vcpus((100, 1000), (400, 1600), 12), 6.0) + self.assertAlmostEqual( + sampler.busy_vcpus((2**32 - 100, 2**32 - 50), (200, 550), 12), 6.0 + ) + self.assertIsNone(sampler.busy_vcpus((5, 9), (5, 9), 12)) + + def test_native_readers_refuse_outside_macos(self): + if sys.platform == "darwin": + self.skipTest("the native readers exist here") + with self.assertRaises(OSError): + sampler.footprints([1]) + self.assertIsNone(sampler.Sampler(Path(".")).read_ticks()) + + +class AttributionTests(unittest.TestCase): + def test_active_marks_and_the_nearest_marked_ancestor_name_the_selection(self): + with tempfile.TemporaryDirectory() as work: + marks = Path(work) / sampler.MARKS + self.assertEqual(sampler.active_marks(marks), {}) + marks.write_text( + "1.0,start,1-of-6,150\n2.0,start,2-of-6,160\n3.0,end,1-of-6,150\n" + "4.0,start,parallel,150\n5.0,end,1-of-6,160\nbroken\n" + "6.0,start,x,pid\n7.0,start,y,1.5\n" + "partial,start,z,170\n" + ) + active = sampler.active_marks(marks) + # An end ends only the same label under the same pid; a row with a bad + # time or pid is skipped. + self.assertEqual(active, {150: "parallel", 160: "2-of-6"}) + parents = {300: 200, 200: 160, 160: 1, 1: 0, 7: 8, 8: 7} + self.assertEqual(sampler.selection_of(300, parents, active), "2-of-6") + self.assertEqual(sampler.selection_of(150, parents, active), "parallel") + self.assertEqual(sampler.selection_of(999, parents, active), "") + self.assertEqual(sampler.selection_of(7, parents, active), "") + + def test_mark_writes_only_in_a_sampled_job_and_defaults_to_its_caller(self): + with tempfile.TemporaryDirectory() as work: + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop(sampler.ENVIRONMENT, None) + sampler.mark("start", "1-of-6") + self.assertFalse((Path(work) / sampler.MARKS).exists()) + with mock.patch.dict(os.environ, {sampler.ENVIRONMENT: work}): + sampler.mark("start", "1-of-6") + sampler.mark("end", "1-of-6", 4242) + with self.assertRaises(ValueError): + sampler.mark("begin", "1-of-6", 1) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + self.assertEqual(sampler.main(["mark", "begin", "1-of-6"]), 0) + self.assertIn( + "::warning title=Resource sampler::ValueError", printed.getvalue() + ) + rows = list( + csv.reader((Path(work) / sampler.MARKS).read_text().splitlines()) + ) + self.assertEqual( + [row[1:] for row in rows], + [["start", "1-of-6", str(os.getppid())], ["end", "1-of-6", "4242"]], + ) + + +class CaptureTests(unittest.TestCase): + def test_footprint_runs_on_each_new_high_and_at_most_twice(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/echo")) + capturing = sampler.Sampler(directory) + capturing.capture(200, GIB, "100") # Under the first step. + capturing.capture(200, 3 * GIB, "105") + capturing.capture(200, 4 * GIB, "110") # Not 2 GiB above the last capture. + capturing.capture(201, 5 * GIB, "115") + capturing.capture(202, 9 * GIB, "120") # Two captures already. + for _, child in capturing.captures: + child.wait(timeout=10) + self.assertEqual( + sorted(path.name for path in directory.glob("footprint-*")), + ["footprint-105-200.txt", "footprint-115-201.txt"], + ) + self.assertEqual((directory / "footprint-115-201.txt").read_text(), "201\n") + + def test_a_footprint_that_outlives_its_time_is_killed(self): + with tempfile.TemporaryDirectory() as work: + self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/sleep")) + self.enterContext(mock.patch.object(sampler, "CAPTURE_SECONDS", -1)) + capturing = sampler.Sampler(Path(work)) + capturing.capture(30, 3 * GIB, "100") + capturing.reap() + _, child = capturing.captures[0] + self.assertLess(child.wait(timeout=10), 0) + + def test_no_capture_without_the_tool(self): + with tempfile.TemporaryDirectory() as work: + self.enterContext( + mock.patch.object(sampler, "FOOTPRINT", str(Path(work) / "absent")) + ) + capturing = sampler.Sampler(Path(work)) + capturing.capture(200, 9 * GIB, "100") + self.assertEqual(capturing.captures, []) + + +class SummaryTests(unittest.TestCase): + def test_summary_reports_each_class_the_top_processes_and_the_selection_at_the_peak( + self, + ): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + write_rows( + directory, + [ + row( + "100", + 6, + 4, + 1, + 3, + 1, + 0, + 1, + 2.0, + 3, + [ + [200, "swiftpm-testing-helper", 2 * GIB, 3 * GIB, "2-of-6"], + [100, "swift-frontend", GIB, GIB, ""], + ], + ), + row( + "105", + 10, + 5, + 4, + 2, + 1, + 1, + 2, + 24.0, + 9, + [ + [200, "swiftpm-testing-helper", 8 * GIB, 9 * GIB, ""], + [300, "xctest", GIB, GIB, "3-of-6"], + ], + ), + row("110", 8, 3, 4, 5, 1, 0, 1, 6.0, None, None), + ], + ) + (directory / sampler.MACHINE).write_text(f"12 {32 * GIB}\n") + (directory / sampler.MARKS).write_text( + "101.0,start,2-of-6,150\n102.0,start,3-of-6,160\n" + "104.0,end,3-of-6,160\n108.0,end,2-of-6,150\n" + "partial,start,3-of-6,170\n" + ) + (directory / "footprint-105-200.txt").write_text(FOOTPRINT_TEXT) + (directory / "footprint-110-300.txt").write_text( + "footprint: insufficient privileges\n" + ) + self.enterContext( + mock.patch.object(sampler, "FOOTPRINT", str(directory / "absent")) + ) + lines = sampler.summary(directory) + facts = json.loads((directory / sampler.SUMMARY).read_text()) + self.assertEqual(lines[0], "Machine: 12 vCPUs, 32.0 GiB.") + self.assertEqual( + lines[3], + "| 3 over 10 s | 10.00 | 5.00 | 4.00 | 5.00 | 1.00 | 1.00 | 2 | 10.67 " + "| 24.00 | 24.00 |", + ) + self.assertIn("Peak used at 00:01:45 UTC, during: 2-of-6.", lines) + self.assertIn( + "| `swiftpm-testing-helper` | 200 | 9.00 | 2-of-6 | 00:01:45 |", lines + ) + self.assertIn("| `swift-frontend` | 100 | 1.00 | - | 00:01:40 |", lines) + self.assertIn("| `xctest` | 300 | 1.00 | 3-of-6 | 00:01:45 |", lines) + self.assertTrue(any("their sum peaked at 9.00 GiB" in line for line in lines)) + self.assertIn( + f"`{directory / 'absent'}`: absent, 2 captures in the samples artifact.", + lines, + ) + self.assertIn( + "- `footprint-105-200.txt`: `swiftpm-testing-helper [200]: 64-bit " + "Footprint: 9 GB (16384 bytes per page)`; `6 GB 0 B 0 B " + " 12 IOAccelerator (graphics)`", + lines, + ) + self.assertIn( + "- `footprint-110-300.txt`: `footprint: insufficient privileges`", lines + ) + self.assertEqual(facts["peaks"]["file_bytes"], {"bytes": 5 * GIB, "time": 110}) + self.assertEqual( + facts["peaks"]["footprint_bytes"], {"bytes": 9 * GIB, "time": 105} + ) + self.assertEqual(facts["selections_at_peak_used"], ["2-of-6"]) + self.assertEqual(facts["scaled_seconds"], {"4": 37.5, "8": 20.0}) + self.assertEqual(facts["busy_vcpus"]["p95"], 24.0) + self.assertEqual( + [process["pid"] for process in facts["top_processes"]], [200, 100, 300] + ) + + def test_summary_without_footprints_marks_or_machine_still_reports(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + write_rows( + directory, + [ + row("100", 6, 4, 1, 3, 1, 0, 1, 2.0, None, None), + row("105", 7, 4, 2, 3, 1, 0, 1, 1.0, None, None), + ], + ) + lines = sampler.summary(directory) + facts = json.loads((directory / sampler.SUMMARY).read_text()) + self.assertIn("Peak used at 00:01:45 UTC.", lines) + self.assertFalse(any(line.startswith("| Process") for line in lines)) + self.assertIsNone(facts["peaks"]["footprint_bytes"]) + self.assertNotIn("scaled_seconds", facts) + + +class LifecycleTests(unittest.TestCase): + def test_report_never_fails_and_writes_the_step_summary(self): + with tempfile.TemporaryDirectory() as work: + summary = Path(work) / "summary" + self.enterContext( + mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)}) + ) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + # No samples directory at all: a warning, never a failure. + self.assertEqual( + sampler.main(["report", str(Path(work) / "absent")]), 0 + ) + self.assertIn("::warning title=Resource sampler::", printed.getvalue()) + directory = Path(work) / "empty" + directory.mkdir() + (directory / sampler.SAMPLES).write_text(",".join(sampler.FIELDS) + "\n") + (directory / sampler.PID).write_text("not a pid\n") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(sampler.main(["report", str(directory)]), 0) + self.assertIn("Resource sampler: no samples.", summary.read_text()) + + def test_start_runs_in_the_background_until_report_stops_it(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) / "samples" + github_env = Path(work) / "github-env" + started = subprocess.run( + [ + sys.executable, + str(SCRIPT), + "start", + str(directory), + "--interval", + "0.05", + ], + capture_output=True, + text=True, + timeout=30, + env={**os.environ, "GITHUB_ENV": str(github_env)}, + ) + self.assertEqual(started.returncode, 0, started.stdout + started.stderr) + # Later steps find the directory for their marks. + self.assertEqual( + github_env.read_text(), f"{sampler.ENVIRONMENT}={directory.resolve()}\n" + ) + pid = int((directory / sampler.PID).read_text()) + os.kill(pid, 0) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(sampler.main(["report", str(directory)]), 0) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.05) + else: + self.fail(f"sampler {pid} still runs after the report") + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx/.github/scripts/test-runner-sizes.py Layr-Labs/mlx/.github/scripts/test-runner-sizes.py new file mode 100755 index 0000000000000000000000000000000000000000..802ad54f3e021063d49c1c5b8758e040e17ba178 --- /dev/null +++ Layr-Labs/mlx/.github/scripts/test-runner-sizes.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Every macOS job that runs on Darkbloom names a signed VM size. + +A Darkbloom macOS job without a size gets the size that the repository's +approval pins. Each macOS job here names its own size instead: in its runner +label (`darkbloom-macos-arm64-4x16`), or, for a lane of +`darkbloom-route.yml`, in the lane's size column. This test fails when: + +- a job asks for a Darkbloom Mac without a size, or with a size that the + image pipeline does not sign (4x16, 4x24, 8x16 and 12x32); +- a Linux route lane names a size (the route refuses one); +- a job's size is not the size that SIZES gives it, or SIZES names a job + that no workflow has (so a size changes only on purpose); +- `.github/actionlint.yaml` does not list a used label, or still lists the + label without a size. + +FORKDIFF.md (Job sizes) gives each size and the data behind it. + +Run: python3 .github/scripts/test-runner-sizes.py +""" + +import re +import unittest +from pathlib import Path + +GITHUB = Path(__file__).resolve().parent.parent +WORKFLOWS = GITHUB / "workflows" +ACTIONLINT = GITHUB / "actionlint.yaml" +SIGNED = {"4x16", "4x24", "8x16", "12x32"} +MACOS = "darkbloom-macos-arm64" +# (workflow, job) for a job, (workflow, "lane <name>") for a route lane: its size. +SIZES = { + ("fork-tests.yml", "build-wheel"): "4x16", + ("fork-tests.yml", "build-cpp"): "4x16", + ("fork-tests.yml", "python-gpu"): "4x24", + ("fork-tests.yml", "python-cpu"): "12x32", + ("fork-tests.yml", "metal-build-and-test"): "4x16", +} + +JOB = re.compile(r"(?m)^ ([A-Za-z0-9_-]+):[ \t]*(?:#.*)?\n") +RUNS_ON = re.compile(r"(?m)^ runs-on:(.*)$") +MACOS_LABELS = re.compile( + r"\[self-hosted, macOS, ARM64, " + MACOS + r"-([0-9]+x[0-9]+)\]" +) +ROUTE = " uses: ./.github/workflows/darkbloom-route.yml" +LANES = re.compile(r"(?m)^ lanes: \|\n((?: .*\n|[ \t]*\n)*)") +EXPRESSION = re.compile(r"\$\{\{.*?\}\}") + + +def jobs(text): + """Return {job id: text} of a workflow's `jobs:` mapping (two-space job keys).""" + text = "\n" + text + if "\njobs:\n" not in text: + return {} + parts = JOB.split(text.split("\njobs:\n", 1)[1]) + return dict(zip(parts[1::2], parts[2::2])) + + +def lane_lines(job): + """Return the fields of each line of a route job's `lanes:` block. + + A `${{ }}` expression counts as one field. + """ + match = LANES.search(job) + if not match: + return [] + return [ + EXPRESSION.sub("EXPRESSION", line).split() + for line in match.group(1).splitlines() + if line.strip() + ] + + +def macos_sizes(workflows): + """Return ({(workflow, job or "lane <name>"): size}, [errors]). + + `workflows` is {workflow file name: text}. + """ + sizes, errors = {}, [] + for workflow, text in sorted(workflows.items()): + for name, job in jobs(text).items(): + where = f"{workflow}: job {name}" + if ROUTE in job: + for fields in lane_lines(job): + lane, profile = fields[0], fields[1] if len(fields) > 1 else "" + size = fields[4] if len(fields) > 4 else None + if profile == "macos_arm64": + if size not in SIGNED: + errors.append(f"{where}: macOS lane {lane}: no signed size") + sizes[(workflow, f"lane {lane}")] = size + elif size is not None: + errors.append(f"{where}: lane {lane} is not macOS: no size") + runs_on = RUNS_ON.findall(job) + if not runs_on: + continue + value = runs_on[0].split(" #", 1)[0].strip() + if len(runs_on) > 1 or not value: + errors.append(f"{where}: write runs-on once, on one line") + continue + if MACOS not in value: + continue + match = MACOS_LABELS.fullmatch(value) + if not match: + errors.append( + f"{where}: runs-on {value} names no size; use [self-hosted, " + f"macOS, ARM64, {MACOS}-<size>], a size of {sorted(SIGNED)}" + ) + continue + if match.group(1) not in SIGNED: + errors.append(f"{where}: size {match.group(1)} is not signed") + sizes[(workflow, name)] = match.group(1) + return sizes, errors + + +def actionlint_labels(): + text = ACTIONLINT.read_text() + return set(re.findall(r"(?m)^ - ([A-Za-z0-9._-]+)\s*$", text)) + + +class RunnerSizes(unittest.TestCase): + def setUp(self): + self.workflows = { + path.name: path.read_text() for path in sorted(WORKFLOWS.glob("*.yml")) + } + + def test_every_macos_job_names_its_signed_size(self): + sizes, errors = macos_sizes(self.workflows) + self.assertEqual(errors, []) + self.assertLessEqual(set(SIZES.values()), SIGNED) + self.assertEqual(sizes, SIZES) + + def test_actionlint_lists_the_sized_labels_only(self): + labels = actionlint_labels() + for size in sorted(set(SIZES.values())): + self.assertIn(f"{MACOS}-{size}", labels) + self.assertNotIn(MACOS, labels) + + def test_an_unsized_or_unsigned_job_fails(self): + # The check must block, not only pass: each of these is refused. + job = "jobs:\n a:\n runs-on: [self-hosted, macOS, ARM64, {}]\n" + bare = job.format(MACOS) + unsigned = job.format(f"{MACOS}-6x12") + block = f"jobs:\n a:\n runs-on:\n - self-hosted\n - {MACOS}\n" + lane = ( + "jobs:\n route:\n" + " uses: ./.github/workflows/darkbloom-route.yml\n" + " with:\n lanes: |\n" + " mac macos_arm64 xcode-27 ${{ inputs.mac && 1 || 0 }}\n" + " lin linux_arm64 ubuntu-24.04 1 4x16\n" + ) + for text in (bare, unsigned, block): + with self.subTest(text=text): + self.assertNotEqual(macos_sizes({"x.yml": text})[1], []) + self.assertEqual(len(macos_sizes({"x.yml": lane})[1]), 2) + sized = job.format(f"{MACOS}-4x16") + self.assertEqual(macos_sizes({"x.yml": sized}), ({("x.yml", "a"): "4x16"}, [])) + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx/.github/scripts/update-bypass-list.js Layr-Labs/mlx/.github/scripts/update-bypass-list.js deleted file mode 100644 index 0f0f0817a88f71dc76f14b276d9ad510c675d594..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/scripts/update-bypass-list.js +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env node - -/** - * update-bypass-list.js - * - * Syncs a repo's PR interaction-limits bypass list with the current - * set of eligible external contributors. - * - * Usage: - * GITHUB_TOKEN=xxxx node update-bypass-list.js <owner> <repo> [--dry-run] - */ - -import { findEligibleContributors } from './find-eligible-contributors.js'; - -const GITHUB_API = 'https://api.github.com'; - -function authHeaders(token) { - return { - Authorization: `Bearer ${token}`, - Accept: 'application/vnd.github+json', - 'X-GitHub-Api-Version': '2026-03-10', - 'User-Agent': 'update-bypass-list-script', - 'Content-Type': 'application/json', - }; -} - -function bypassListUrl(owner, repo) { - return `${GITHUB_API}/repos/${owner}/${repo}/interaction-limits/pulls/bypass-list`; -} - -async function fetchBypassList(owner, repo, token) { - const url = bypassListUrl(owner, repo); - const res = await fetch(url, { headers: authHeaders(token) }); - - if (res.status === 404) { - return new Set(); - } - - if (!res.ok) { - const body = await res.text(); - throw new Error(`Failed to fetch bypass list (${res.status}): ${body}`); - } - - const data = await res.json(); - const logins = data.map((user) => user?.login).filter(Boolean); - - return new Set(logins); -} - -async function addUsersToBypassList(owner, repo, token, usernames) { - if (usernames.length === 0) return; - - const res = await fetch(bypassListUrl(owner, repo), { - method: 'PUT', - headers: authHeaders(token), - body: JSON.stringify({ users: usernames }), - }); - - if (!res.ok) { - const body = await res.text(); - throw new Error(`Failed to add users [${usernames.join(', ')}] (${res.status}): ${body}`); - } -} - -async function removeUsersFromBypassList(owner, repo, token, usernames) { - if (usernames.length === 0) return; - - const res = await fetch(bypassListUrl(owner, repo), { - method: 'DELETE', - headers: authHeaders(token), - body: JSON.stringify({ users: usernames }), - }); - - if (!res.ok) { - const body = await res.text(); - throw new Error(`Failed to remove users [${usernames.join(', ')}] (${res.status}): ${body}`); - } -} - -function diffLists(eligibleLogins, currentBypassLogins) { - const toAdd = [...eligibleLogins].filter((login) => !currentBypassLogins.has(login)); - const toRemove = [...currentBypassLogins].filter((login) => !eligibleLogins.has(login)); - return { toAdd, toRemove }; -} - -/** - * Update the bypass list to eligible contributors. - * - * @param {Object} params - * @param {string} params.owner - * @param {string} params.repo - * @param {string} params.token - * @param {boolean} [params.dryRun] - If true, only computes the diff, makes no API writes. - */ -async function updateBypassList({ owner, repo, token, dryRun = false }) { - console.error(`Getting eligible external contributors for ${owner}/${repo}...`); - const eligibleLogins = new Set(await findEligibleContributors({ owner, repo, token })); - console.error(`Found ${eligibleLogins.size} eligible user(s).`); - - console.error(`Fetching current bypass list...`); - const currentBypassLogins = await fetchBypassList(owner, repo, token); - console.error(`Current bypass list has ${currentBypassLogins.size} user(s).`); - - const { toAdd, toRemove } = diffLists(eligibleLogins, currentBypassLogins); - - console.error(`\nUsers to add (${toAdd.length}): ${toAdd.join(', ') || '(none)'}`); - console.error(`Users to remove (${toRemove.length}): ${toRemove.join(', ') || '(none)'}`); - - if (dryRun) { - console.error('\nDry run mode: no changes will be made.'); - return; - } - - try { - await addUsersToBypassList(owner, repo, token, toAdd); - if (toAdd.length > 0) console.error(`Added ${toAdd.length} user(s) to bypass list.`); - } catch (err) { - console.error(`Error adding users: ${err.message}`); - } - - try { - await removeUsersFromBypassList(owner, repo, token, toRemove); - if (toRemove.length > 0) console.error(`Removed ${toRemove.length} user(s) from bypass list.`); - } catch (err) { - console.error(`Error removing users: ${err.message}`); - } -} - -// ---- CLI entry point ---- - -function isRunAsCLI() { - return import.meta.url === `file://${process.argv[1]}`; -} - -async function runCLI() { - const args = process.argv.slice(2); - const dryRun = args.includes('--dry-run'); - const [owner, repo] = args.filter((a) => !a.startsWith('--')); - - if (!owner || !repo) { - console.error('Usage: node update-bypass-list.js <owner> <repo> [--dry-run]'); - process.exit(1); - } - - const token = process.env.GITHUB_TOKEN; - if (!token) { - console.error('Error: set GITHUB_TOKEN environment variable with a valid GitHub token.'); - process.exit(1); - } - - await updateBypassList({ owner, repo, token, dryRun }); -} - -if (isRunAsCLI()) { - runCLI().catch((err) => { - console.error('Fatal error:', err); - process.exit(1); - }); -} - -export { updateBypassList };
diff --git ml-explore/mlx/.github/workflows/build_and_test.yml Layr-Labs/mlx/.github/workflows/build_and_test.yml index c50a39adb541a1d453c22fbdf4895ce23faf4b54..9152f611c9403b701fe4fcd7174fb4a859e86ac2 100644 --- ml-explore/mlx/.github/workflows/build_and_test.yml +++ Layr-Labs/mlx/.github/workflows/build_and_test.yml @@ -19,181 +19,37 @@ jobs: check_lint: name: Check Lint - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v7 - - uses: pre-commit/action@v3.0.1 - - build_and_test: - name: ${{ matrix.os }} (${{ matrix.toolkit }}, ${{ matrix.arch }}) - if: github.repository == 'ml-explore/mlx' - needs: check_lint - strategy: - fail-fast: false - matrix: - os: ['Linux', 'Windows'] - arch: ['x86_64', 'aarch64'] - toolkit: ['cpu', 'cuda-12.6', 'cuda-12.9', 'cuda-13.0'] - exclude: - # CUDA does not support Windows on arm. - - os: 'Windows' - arch: 'aarch64' - toolkit: 'cuda-12.6' - - os: 'Windows' - arch: 'aarch64' - toolkit: 'cuda-12.9' - - os: 'Windows' - arch: 'aarch64' - toolkit: 'cuda-13.0' - # CUDA 12.6 does not compile with CUTLASS on Windows. - - os: 'Windows' - arch: 'x86_64' - toolkit: 'cuda-12.6' - runs-on: |- - ${{ case(matrix.os == 'Windows', - case(matrix.arch == 'aarch64', 'windows-11-arm', - startsWith(matrix.toolkit, 'cuda'), 'windows-2022-large', - 'windows-2022'), - case(matrix.arch == 'x86_64' && startsWith(matrix.toolkit, 'cuda'), 'gpu-t4-4-core', - matrix.arch == 'aarch64', 'ubuntu-22.04-arm', - 'ubuntu-22.04')) - }} - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - id: setup - with: - toolkit: ${{ matrix.toolkit }} - - uses: ./.github/actions/build - with: - cmake-args: ${{ steps.setup.outputs.cmake-args }} - # For MSVC, Ninja/Release is the only config supported by ccache. - debug: ${{ matrix.os != 'Windows' }} - - name: Check generated Python stubs with ty - if: matrix.os == 'Linux' && matrix.arch == 'x86_64' && matrix.toolkit == 'cpu' - run: uvx ty check python/mlx/core - - uses: ./.github/actions/test-linux - if: matrix.os == 'Linux' && (matrix.toolkit == 'cpu' || matrix.arch == 'x86_64') - - uses: ./.github/actions/test-windows - if: matrix.os == 'Windows' && matrix.toolkit == 'cpu' - - mac_build: - name: macOS (${{ matrix.macos-target }}, ${{ matrix.toolkit }}) - if: github.repository == 'ml-explore/mlx' - strategy: - fail-fast: false - matrix: - macos-target: ['14.0', '15.0', '26.2'] - toolkit: ['cpu', 'metal', 'jit'] - runs-on: macos-26-xlarge - needs: check_lint + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - id: setup - with: - toolkit: ${{ matrix.toolkit }} - ccache-key: 'test-${{ matrix.macos-target }}' - # Use the compile cache of metal build for all builds. - ccache-save: ${{ matrix.toolkit == 'metal' }} - ccache-toolkit: 'metal' - - uses: ./.github/actions/build-macos - with: - cmake-args: ${{ steps.setup.outputs.cmake-args }} - macos-target: ${{ matrix.macos-target }} - - uses: ./.github/actions/test-macos - if: matrix.toolkit == 'cpu' - with: - toolkit: 'cpu' - - uses: actions/upload-artifact@v7 - if: matrix.toolkit != 'cpu' - with: - name: mlx-${{ matrix.toolkit }}-macos${{ matrix.macos-target }} - path: | - dist/mlx-*.whl - build/mlx/backend/metal/kernels/mlx.metallib - build/tests/tests - if-no-files-found: error - - mac_test: - name: Test macOS (${{ matrix.toolkit }}) - if: github.repository == 'ml-explore/mlx' - runs-on: macos-26-xlarge - needs: mac_build - strategy: - fail-fast: false - matrix: - toolkit: ['metal', 'jit'] - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - with: - toolkit: ${{ matrix.toolkit }} - use-ccache: false - - uses: actions/download-artifact@v8 - with: - path: artifact - pattern: mlx-${{ matrix.toolkit }}-* - - run: ls -lhR artifact - - uses: ./.github/actions/test-macos - with: - toolkit: ${{ matrix.toolkit }} - - array_api_test: - name: Array API Tests (Metal) - if: github.repository == 'ml-explore/mlx' - needs: mac_build - runs-on: macos-26-xlarge - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - with: - toolkit: 'metal' - use-ccache: false - - uses: actions/download-artifact@v8 - with: - path: artifact - pattern: mlx-metal-* - - name: Checkout array-api-tests - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: - repository: data-apis/array-api-tests - ref: 'ef5b39f1190d54dca0d9a12646033d2d123afdd5' # v2026.09.08 - submodules: 'true' - path: 'array-api-tests' - persist-credentials: false - - name: Install dependencies - shell: bash + python-version: "3.12" + - name: Install pre-commit run: | - uv pip install pytest-xdist -r array-api-tests/requirements.txt - - name: Run the test suite - shell: bash - env: - ARRAY_API_TESTS_MODULE: mlx.core - ARRAY_API_TESTS_SKIP_DTYPES: 'float64,complex128' - PYTHONWARNINGS: 'ignore::UserWarning::,ignore::DeprecationWarning::,ignore::RuntimeWarning::' - METAL_DEBUG_ERROR_MODE: 0 - METAL_DEVICE_WRAPPER_TYPE: 1 + python -m venv "$RUNNER_TEMP/lint-venv" + "$RUNNER_TEMP/lint-venv/bin/python" -m pip install pre-commit + "$RUNNER_TEMP/lint-venv/bin/python" -m pip freeze --local + echo "$RUNNER_TEMP/lint-venv/bin" >> "$GITHUB_PATH" + - name: Choose this job's Actions cache run: | - if [[ -d artifact ]] ; then - for SUBDIR in artifact/*; do - rm -rf build dist - mv "$SUBDIR"/* . - break - done + if [[ ${RUNNER_NAME:-} == darkbloom-* && -z ${DARKBLOOM_CACHE_URL:-} ]]; then + echo "CI_ACTIONS_CACHE=off" >> "$GITHUB_ENV" + echo "::notice title=Actions cache::The plane gave this Darkbloom Sandbox no cache, so the cache step is skipped." fi - uv pip install dist/*.whl - cd "${GITHUB_WORKSPACE}/array-api-tests" - pytest array_api_tests -v -c pytest.ini -n 2 --max-examples=1000 --derandomize --disable-data-dependent-shapes --disable-deadline -o strict_xfail=False --xfails-file "${GITHUB_WORKSPACE}/python/tests/xp-tests/xfail.txt" --skips-file "${GITHUB_WORKSPACE}/python/tests/xp-tests/skips.txt" - - build_documentation: - name: Build Documentation - if: github.repository == 'ml-explore/mlx' - runs-on: ubuntu-22.04 - needs: check_lint - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + if: env.CI_ACTIONS_CACHE != 'off' + with: + path: ~/.cache/pre-commit + key: pre-commit-3|${{ runner.os }}|${{ runner.arch }}|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} + - name: Run pre-commit + run: pre-commit run --show-diff-on-failure --color=always --all-files + - name: Test the runner sizes and the resource sampler + # Fails when a macOS job names no signed VM size (FORKDIFF.md, Job sizes). + run: | + python3 .github/scripts/test-runner-sizes.py + python3 .github/scripts/test-ci-resource-sampler.py   linux_sanitizer_build_and_test: name: Linux Sanitizer Tests (${{ matrix.sanitizer }}) @@ -204,49 +60,65 @@ matrix: sanitizer: [ASAN, UBSAN] # todo 12/16/2025: enable TSAN later + consider enabling ASAN for GPU backend tests. # sanitizer: [ASAN, UBSAN, TSAN] - runs-on: ubuntu-22.04-arm + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + # ASAN takes about 22 minutes natively; a hung run must not hold a sandbox for GitHub's 6-hour default. + timeout-minutes: 60 steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7   - - name: Install Dependencies + - name: Check the native sanitizer image tools run: | - export DEBIAN_FRONTEND=noninteractive - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libblas-dev \ - liblapacke-dev \ - libopenblas-dev \ - cmake \ - clang \ - git - sudo apt-get clean - sudo rm -rf /var/lib/apt/lists/* + [[ "$RUNNER_NAME" == darkbloom-* ]] + [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]] + cmake --version + cc --version + c++ --version + clang --version + make --version + git --version   - name: Linux Build and Test with ${{ matrix.sanitizer }} run: | bash .github/scripts/build-sanitizer-tests.sh ${{ matrix.sanitizer }}   - linux_fedora_build_cpp: - name: Linux Fedora (${{ matrix.arch }}) + linux_fedora_build_cpp_x86_64: + name: Linux Fedora (x86_64) needs: check_lint - strategy: - fail-fast: false - matrix: - include: - - host: ubuntu-22.04 - arch: x86_64 - - host: ubuntu-22.04-arm - arch: aarch64 - - runs-on: ${{ matrix.host }} + runs-on: ubuntu-22.04 container: image: fedora:42 steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7   - name: CPP Build Test - No Release run: | bash ./.github/scripts/setup+build-cpp-linux-fedora-container.sh + + linux_fedora_build_cpp_aarch64: + name: Linux Fedora (aarch64) + needs: check_lint + # The sandbox has no Docker: fedora_proot.py runs the same Fedora script in the archived + # Fedora 42 container rootfs under PRoot (built from pinned source). About 2.5 minutes. + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 45 + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Check the runner tools and test the Fedora PRoot helper + run: | + [[ "$RUNNER_NAME" == darkbloom-* ]] + [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]] + cc --version + make --version + dpkg-deb --version + python3 --version + python3 -B .github/scripts/fedora-proot/test_fedora_proot.py + + - name: CPP Build Test - No Release + run: | + python3 .github/scripts/fedora-proot/fedora_proot.py run --source "$GITHUB_WORKSPACE" --work "$RUNNER_TEMP/fedora-proot"
diff --git ml-explore/mlx/.github/workflows/codeql-native.yml Layr-Labs/mlx/.github/workflows/codeql-native.yml new file mode 100644 index 0000000000000000000000000000000000000000..82c75ac91dcb605e07561b6b8bdb161c5dbe7a37 --- /dev/null +++ Layr-Labs/mlx/.github/workflows/codeql-native.yml @@ -0,0 +1,261 @@ +name: Native CodeQL + +# Enable only after the operator switches GitHub default setup to advanced setup. +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '15 5 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: native-codeql-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + route: + if: ${{ vars.CODEQL_NATIVE == 'on' && (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') }} + uses: ./.github/workflows/darkbloom-route.yml + permissions: {} + with: + lanes: | + codeql linux_arm64 ubuntu-22.04-arm + + scan: + needs: route + runs-on: ${{ fromJSON(needs.route.outputs.routes)['codeql'] }} + timeout-minutes: 45 + permissions: + contents: read + steps: + - name: Require Linux ARM64 + run: | + [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]] + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Check the artifact boundary + run: python3 .github/scripts/codeql_artifacts_test.py + - name: Download the qualified CodeQL 2.27.4 ARM64 bundle + run: | + set -euo pipefail + cd "$RUNNER_TEMP" + curl --fail --location --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 600 --output codeql.tar.zst https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-linux-arm64.tar.zst + echo '1c015b411c6e1c7f7e767eb8c9408fc6a2012d24d78b177cf22f29edc5772d10 codeql.tar.zst' | sha256sum --check + tar --zstd -xf codeql.tar.zst + "$RUNNER_TEMP/codeql/codeql" version --format=json + "$RUNNER_TEMP/codeql/codeql" resolve languages + - name: Run the existing language-default suites without a build + run: | + set -euo pipefail + codeql="$RUNNER_TEMP/codeql/codeql" + mkdir "$RUNNER_TEMP/codeql-dbs" "$RUNNER_TEMP/codeql-results" + for language in actions cpp python; do + "$codeql" database create "$RUNNER_TEMP/codeql-dbs/$language" --source-root="$GITHUB_WORKSPACE" --language="$language" --build-mode=none --threads=4 --ram=8192 + "$codeql" database analyze "$RUNNER_TEMP/codeql-dbs/$language" --format=sarifv2.1.0 --output="$RUNNER_TEMP/codeql-results/$language.sarif" --threads=4 --ram=8192 + done + - name: Bind fingerprinted SARIF to the exact workflow run + run: | + python3 .github/scripts/codeql_artifacts.py --checkout "$GITHUB_WORKSPACE" --results "$RUNNER_TEMP/codeql-results" --output "$RUNNER_TEMP/codeql-bundle" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/codeql-bundle/ + if-no-files-found: error + retention-days: 3 + + publish: + needs: scan + if: ${{ vars.CODEQL_NATIVE == 'on' && needs.scan.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + actions: read + contents: read + security-events: write + steps: + # No checkout or repository code; native SARIF already has fingerprints. + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/codeql-publish/ + - name: Validate the exact run and bounded data-only bundle + id: validate + env: + BUNDLE: ${{ runner.temp }}/codeql-publish + run: | + python3 - <<'PYCODE' + import hashlib, json, os, re, urllib.parse + from pathlib import Path, PurePosixPath + LANGUAGES = { + "actions": "/language:actions", + "cpp": "/language:c-cpp", + "python": "/language:python", + } + CODEQL_VERSION = "2.27.4" + MAX_FILE = 16 * 1024 * 1024 + MAX_BUNDLE = 64 * 1024 * 1024 + + + def context(): + return { + key: os.environ[env] + for key, env in { + "repository": "GITHUB_REPOSITORY", + "sha": "GITHUB_SHA", + "ref": "GITHUB_REF", + "run_id": "GITHUB_RUN_ID", + "attempt": "GITHUB_RUN_ATTEMPT", + }.items() + } + + + def relative_path(value): + if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: + raise ValueError("invalid bundle path") + path = PurePosixPath(value) + if path.is_absolute() or any(part in ("..", ".git") for part in path.parts): + raise ValueError("bundle path escapes its data directory") + if path.as_posix() != value: + raise ValueError("bundle path is not canonical") + return path + + + def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + + def validate_sarif(sarif): + if sarif.get("version") != "2.1.0" or not sarif.get("runs"): + raise ValueError("invalid SARIF") + if not any( + run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"] + ): + raise ValueError("analysis has no rules") + for run in sarif["runs"]: + driver = run.get("tool", {}).get("driver", {}) + if ( + driver.get("name") != "CodeQL" + or driver.get("semanticVersion") != CODEQL_VERSION + ): + raise ValueError("SARIF was not produced by the qualified CodeQL version") + artifacts = run.get("artifacts", []) + for result in run.get("results", []): + locations = result.get("locations", []) + if not locations: + continue + primary = locations[0].get("physicalLocation", {}) + location = primary.get("artifactLocation", {}) + if "uri" not in location and "index" in location: + index = location["index"] + if type(index) is not int or not 0 <= index < len(artifacts): + raise ValueError("invalid artifact index") + location = artifacts[index]["location"] + uri = urllib.parse.urlsplit(location.get("uri", "")) + if uri.scheme or uri.netloc: + raise ValueError("source location is not repository relative") + relative_path(urllib.parse.unquote(uri.path)) + if primary.get("region", {}).get("startLine") is not None: + fingerprint = result.get("partialFingerprints", {}).get( + "primaryLocationLineHash", "" + ) + if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint): + raise ValueError("source-line finding lacks a stable fingerprint") + + + def verify_bundle(root, expected): + root = root.resolve(strict=True) + manifest_file = root / "manifest.json" + if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024: + raise ValueError("invalid manifest") + manifest = json.loads(manifest_file.read_text()) + if manifest.get("context") != expected or manifest.get("version") != 1: + raise ValueError( + "scan belongs to another run, attempt, repository, ref or commit" + ) + if ( + manifest.get("codeql_version") != CODEQL_VERSION + or manifest.get("categories") != LANGUAGES + ): + raise ValueError("unexpected CodeQL recipe") + files = manifest.get("files") + if not isinstance(files, dict) or len(files) != 3: + raise ValueError("invalid file inventory") + required = {f"sarif/{language}.sarif" for language in LANGUAGES} + if not required.issubset(files): + raise ValueError("missing language") + actual = set() + total = 0 + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("symlinks are not scan data") + if not path.is_file(): + if path.is_dir(): + continue + raise ValueError("only regular files are scan data") + rel = path.relative_to(root).as_posix() + if rel == "manifest.json": + continue + relative_path(rel) + if not path.resolve().is_relative_to(root): + raise ValueError("file escapes bundle") + spec = files.get(rel) + size = path.stat().st_size + if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE: + raise ValueError("unexpected or oversized file") + if spec.get("size") != size or spec.get("sha256") != digest(path): + raise ValueError("scan data changed") + if rel not in required: + raise ValueError("only the three SARIF files may be supplied") + actual.add(rel) + total += size + if actual != set(files) or total > MAX_BUNDLE: + raise ValueError("file inventory differs or bundle exceeds limit") + for language in LANGUAGES: + sarif = json.loads((root / f"sarif/{language}.sarif").read_text()) + validate_sarif(sarif) + # The official uploader falls back to event SHA/ref without a checkout. + # Native CodeQL already supplies every primary-line fingerprint. + empty_checkout = root / "empty-checkout" + empty_checkout.mkdir(exist_ok=True) + return empty_checkout + + + source = verify_bundle(Path(os.environ['BUNDLE']), context()) + with open(os.environ['GITHUB_OUTPUT'], 'a') as out: + out.write(f'checkout-path={source}\n') + PYCODE + - name: Upload actions analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/actions.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:actions + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true + - name: Upload cpp analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/cpp.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:c-cpp + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true + - name: Upload python analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/python.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:python + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true
diff --git ml-explore/mlx/.github/workflows/darkbloom-route.yml Layr-Labs/mlx/.github/workflows/darkbloom-route.yml new file mode 100644 index 0000000000000000000000000000000000000000..5f851bb394b2a61e83c3e922927265b95358654b --- /dev/null +++ Layr-Labs/mlx/.github/workflows/darkbloom-route.yml @@ -0,0 +1,227 @@ +name: Darkbloom Route + +# Chooses a runner for each read-only CI lane: a Darkbloom Sandbox when the +# plane grants one, otherwise the lane's fallback label. Callers run each job on +# `fromJSON(needs.route.outputs.routes)['<lane>']`. Routing is off unless the +# DARKBLOOM_ROUTING variable is exactly `on`; the plane can never fail this job. +# DARKBLOOM_MACOS_LANES, when set, caps the macOS jobs one run asks for: lanes +# are kept in the caller's order while they fit, and the others keep their +# fallback without asking. A macOS lane can name a size. Sizes are sent only +# when the DARKBLOOM_JOB_SHAPES variable is exactly `on`; otherwise the request +# is the one without sizes, and a `required` lane keeps its fallback without +# asking. +on: + workflow_call: + inputs: + lanes: + description: >- + One lane per line: `<lane> <profile> <fallback-label> [count [size + [required]]]`. Profiles are linux_arm64 and macos_arm64. Count is the + number of jobs that will run (default 1); 0 keeps the fallback + without asking. Size, macOS only, is `<vCPUs>x<GiB>`, such as 4x24. + While sizes are off, a `required` lane keeps its fallback without + asking, and any other lane asks without its size. + type: string + required: true + outputs: + routes: + description: JSON object mapping every lane to its runs-on value. + value: ${{ jobs.select.outputs.routes }} + +permissions: {} + +jobs: + select: + name: Select Runners + runs-on: ubuntu-24.04 + permissions: {} + timeout-minutes: 3 + outputs: + routes: ${{ steps.route.outputs.routes }} + steps: + - name: Choose a Darkbloom or fallback runner for each lane + id: route + shell: bash + env: + LANES: ${{ inputs.lanes }} + ROUTING: ${{ vars.DARKBLOOM_ROUTING }} + MACOS_LANES: ${{ vars.DARKBLOOM_MACOS_LANES }} + JOB_SHAPES: ${{ vars.DARKBLOOM_JOB_SHAPES }} + PLANE_URL: ${{ vars.DARKBLOOM_SANDBOX_URL }} + REPOSITORY: ${{ github.repository }} + EVENT_NAME: ${{ github.event_name }} + HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + set -euo pipefail + + # The only labels a lane can receive besides its fallback. A plane + # decision is used only when it repeats its profile's array exactly. + # For a lane sent with a size, the size qualifies the last label + # (darkbloom-macos-arm64-4x24). + profiles='{"linux_arm64":["self-hosted","linux","ARM64","darkbloom-linux-arm64"],"macos_arm64":["self-hosted","macOS","ARM64","darkbloom-macos-arm64"]}' + # Plane text is untrusted: keep it short, on one line, and free of + # Markdown, HTML and workflow-command syntax before printing it. + clean='def clean: tostring | gsub("[^A-Za-z0-9 _.,:;/=+()-]"; "?") | .[0:120];' + + configuration_error() { + echo "::error title=Darkbloom route configuration::$1" + exit 1 + } + + configured='[]' + seen=' ' + while read -r lane profile fallback count shape required extra; do + [ -n "$lane" ] || continue + count=${count:-1} + [ -z "$extra" ] || configuration_error "lane $lane has more than six fields" + [[ $lane =~ ^[A-Za-z0-9_-]+$ ]] || configuration_error "invalid lane name: $lane" + jq -e --arg profile "$profile" 'has($profile)' <<<"$profiles" >/dev/null \ + || configuration_error "lane $lane has unknown profile: $profile" + [[ $fallback =~ ^[A-Za-z0-9._-]+$ ]] \ + || configuration_error "lane $lane has invalid fallback label: $fallback" + [[ $count =~ ^(0|[1-9][0-9]?)$ ]] || configuration_error "lane $lane has invalid count: $count" + # The plane's size grammar: <vCPUs>x<GiB>, lowercase decimal, no leading zeros. + if [ -n "$shape" ]; then + [[ $shape =~ ^[1-9][0-9]*x[1-9][0-9]*$ ]] \ + || configuration_error "lane $lane has invalid size: $shape (use <vCPUs>x<GiB>, such as 4x24)" + [ "$profile" = macos_arm64 ] || configuration_error "lane $lane has a size, but sizes are macOS only" + fi + [ -z "$required" ] || [ "$required" = required ] \ + || configuration_error "lane $lane has an unknown sixth field: $required" + case $seen in *" $lane "*) configuration_error "lane $lane is listed twice" ;; esac + seen="$seen$lane " + configured=$(jq -c --arg lane "$lane" --arg profile "$profile" --arg fallback "$fallback" \ + --argjson count "$count" --arg shape "$shape" --arg required "$required" \ + '. + [{$lane, $profile, $fallback, $count, + shape: (if $shape == "" then null else $shape end), required: ($required != ""), held: false}]' \ + <<<"$configured") + done <<<"${LANES:-}" + [ "$configured" != '[]' ] || configuration_error "no lanes are configured" + + # Job sizes are a repository setting, off unless exactly `on`. While + # they are off, no size is sent, so the request is the request of a + # lane table without sizes. A `required` lane is then held: it keeps + # its fallback without asking and takes no place under the macOS cap. + shapes_note="" + if jq -e 'any(.[]; .shape != null)' <<<"$configured" >/dev/null; then + if [ "${JOB_SHAPES:-}" = on ]; then + shapes_note=" Job sizes are on: DARKBLOOM_JOB_SHAPES is 'on'." + else + shapes_note=" Job sizes are off: DARKBLOOM_JOB_SHAPES is not 'on'. No size was requested." + configured=$(jq -c 'map(.held = .required | .shape = null)' <<<"$configured") + fi + fi + + # The macOS cap is a repository setting, not caller configuration: a + # value other than 0 to 99 asks for no macOS lane rather than failing. + macos_cap=${MACOS_LANES:-} + cap_note="" + if [ -n "$macos_cap" ] && ! [[ $macos_cap =~ ^(0|[1-9][0-9]?)$ ]]; then + cap_note=" DARKBLOOM_MACOS_LANES is not a number from 0 to 99, so no macOS lane was requested." + macos_cap=0 + fi + configured=$(jq -c --arg cap "$macos_cap" ' + reduce .[] as $entry ({used: 0, lanes: []}; + if $entry.held then .lanes += [$entry + {capped: false}] + elif $cap != "" and $entry.profile == "macos_arm64" and $entry.count > 0 + and .used + $entry.count > ($cap | tonumber) + then .lanes += [$entry + {capped: true}] + else .used += (if $entry.profile == "macos_arm64" then $entry.count else 0 end) + | .lanes += [$entry + {capped: false}] + end) | .lanes' <<<"$configured") + # A lane without a size is exactly {lane, profile, count}. + requested=$(jq -c '[.[] | select(.count > 0 and (.capped | not) and (.held | not)) + | {lane, profile, count} + (if .shape != null then {shape} else {} end)]' <<<"$configured") + + plane_url=${PLANE_URL:-https://api-sandbox.darkbloom.dev} + body=$(mktemp) + trap 'rm -f "$body"' EXIT + reply=/dev/null + fallback_reason="" + if [ "${ROUTING:-}" != on ]; then + fallback_reason="routing is off" + note="Routing is off: DARKBLOOM_ROUTING is not 'on'. No request was sent." + elif [[ ${EVENT_NAME:-} == pull_request* && ${HEAD_REPOSITORY:-} != "${REPOSITORY:-}" ]]; then + fallback_reason="pull request from a fork" + note="Pull requests from forks keep their fallback runners. No request was sent." + elif [ "$requested" = '[]' ]; then + note="No lane has jobs to run. No request was sent." + elif [[ $plane_url != https://* ]]; then + fallback_reason="plane URL is not https" + note="DARKBLOOM_SANDBOX_URL must start with https://. No request was sent." + elif ! [[ ${RUN_ID:-} =~ ^[0-9]+$ && ${RUN_ATTEMPT:-} =~ ^[0-9]+$ ]]; then + fallback_reason="run identity is unavailable" + note="The run ID or attempt is not numeric. No request was sent." + else + request=$(jq -n -c --arg repository "$REPOSITORY" --argjson run_id "$RUN_ID" \ + --argjson run_attempt "$RUN_ATTEMPT" --argjson lanes "$requested" \ + '{$repository, $run_id, $run_attempt, $lanes}') + # The request names only the repository, the run and the lanes. + echo "Request: $request" + # One attempt plus at most one retry after a transport failure, + # timeout or transient status; each attempt is bounded to 5 seconds. + for attempt in 1 2; do + status=$(curl --disable --silent --show-error --proto '=https' --max-time 5 \ + --max-filesize 65536 --user-agent darkbloom-route/1 --request POST \ + --header 'Content-Type: application/json' --header 'Accept: application/json' \ + --data-binary @- --output "$body" --write-out '%{http_code}' \ + "${plane_url%/}/v1/ci/routes" <<<"$request") || status=000 + case $status in + 000|408|429|5??) [ "$attempt" = 2 ] || sleep 1 ;; + *) break ;; + esac + done + if [ "$status" != 200 ]; then + fallback_reason="plane request failed (HTTP $status)" + elif ! jq -e -s 'length == 1 and (.[0] | type == "object" + and (.route_id | type == "string" and length > 0) + and (.expires_at | type == "string") + and (.lanes | type == "object"))' "$body" >/dev/null 2>&1; then + fallback_reason="plane reply is malformed" + else + reply=$body + fi + if [ -n "$fallback_reason" ]; then + note="Asked $plane_url: $fallback_reason. Requested lanes keep their fallback runners." + else + note=$(jq -r --arg url "$plane_url" \ + "$clean"'"Asked \($url): route \(.route_id | clean), expires \(.expires_at | clean)."' "$body") + fi + fi + + decisions=$(jq -n -c --argjson configured "$configured" --argjson profiles "$profiles" \ + --arg fallback_reason "$fallback_reason" --slurpfile reply "$reply" "$clean"' + ($reply[0].lanes // {}) as $plane_decisions + | [ $configured[] + | ($plane_decisions[.lane] | if type == "object" then . else {} end) as $decision + | (.shape as $shape | $profiles[.profile] + | if $shape == null then . else .[:-1] + [.[-1] + "-" + $shape] end) as $labels + | if .count == 0 then .target = "fallback" | .reason = "not requested" + elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason + elif .held then .target = "fallback" | .reason = "needs its size, and job sizes are off (DARKBLOOM_JOB_SHAPES)" + elif .capped then .target = "fallback" | .reason = "over the macOS lane cap (DARKBLOOM_MACOS_LANES)" + elif $decision.target == "darkbloom" and $decision.runs_on == $labels + then .target = "darkbloom" | .reason = "granted" + elif $decision.target == "fallback" + then .target = "fallback" | .reason = "plane: " + ($decision.reason // "no reason" | clean) + else .target = "fallback" | .reason = "plane decision is missing or invalid" + end + | .runs_on = (if .target == "darkbloom" then $decision.runs_on else .fallback end) ]') + routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions") + echo "routes=$routes" >> "$GITHUB_OUTPUT" + + note="$note$cap_note$shapes_note" + echo "$note" + jq -r '.[] | (if .shape == null then "" else "; size \(.shape)" end) as $size + | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason)\($size))"' <<<"$decisions" + { + echo "### Darkbloom runner routing" + echo + echo "$note" + echo + echo "| Lane | Profile | Jobs | Size | Runner | Decision |" + echo "| --- | --- | --- | --- | --- | --- |" + jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | \(.shape // "-") | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions" + } >> "$GITHUB_STEP_SUMMARY"
diff --git ml-explore/mlx/.github/workflows/darkbloom-watchdog.yml Layr-Labs/mlx/.github/workflows/darkbloom-watchdog.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f956baae416761a384b932b43784aa8cd5c6e89 --- /dev/null +++ Layr-Labs/mlx/.github/workflows/darkbloom-watchdog.yml @@ -0,0 +1,304 @@ +name: Darkbloom Watchdog + +# Rescues runs stranded on Darkbloom: a job routed to Darkbloom can only run +# on a Darkbloom runner, so when one waits queued with no runner for +# DARKBLOOM_WATCHDOG_MINUTES (default 30) since its own creation, and no +# Darkbloom job of the run got a runner within that time, this cancels the +# run and re-runs the route job and its dependents (the whole run when the +# cancel interrupted other jobs), also when other Darkbloom jobs of the run +# ran or still run. The new +# attempt's route job then keeps its fallback labels: the plane unreachable, +# or answering run_fallback_forced. It needs only GitHub and this +# repository's GITHUB_TOKEN, so it works while Darkbloom's plane is down. +# What it cannot see, it does not guess: GitHub shows no sign of a job that +# waits by design, so a payer at its concurrency or resource limit (a sized +# job waiting for room in its grant) looks like a fault to it once no runner +# came for the whole wait. Set DARKBLOOM_WATCHDOG_MINUTES above such waits. +# Darkbloom's own watchdog acts first (after 15 minutes, on the plane's +# evidence) and marks the run with a `Darkbloom watchdog` check run, which +# this leaves alone for 20 minutes. A run is rescued at most once, by either: +# stranded again, it is only cancelled. Off when the repository variable +# DARKBLOOM_WATCHDOG is `off`. +# +# Copy this file into the repository as .github/workflows/darkbloom-watchdog.yml, +# beside darkbloom-route.yml, unchanged. See README.md. +on: + schedule: + - cron: '*/10 * * * *' + workflow_dispatch: + +permissions: {} + +concurrency: + group: darkbloom-watchdog + cancel-in-progress: false + +jobs: + watch: + name: Rescue Stranded Runs + runs-on: ubuntu-24.04 + # A minute of jitter, then at most two rescues of three minutes each. + timeout-minutes: 12 + permissions: + actions: write + checks: write + steps: + - name: Cancel and re-run runs whose Darkbloom jobs are stranded + shell: bash + env: + GH_TOKEN: ${{ github.token }} + API_URL: ${{ github.api_url }} + REPOSITORY: ${{ github.repository }} + SELF_RUN_ID: ${{ github.run_id }} + WATCHDOG: ${{ vars.DARKBLOOM_WATCHDOG }} + MINUTES: ${{ vars.DARKBLOOM_WATCHDOG_MINUTES }} + ROUTE_JOB: ${{ vars.DARKBLOOM_ROUTE_JOB }} + APP_SLUG: ${{ vars.DARKBLOOM_APP_SLUG }} + run: | + set -euo pipefail + export LC_ALL=C + summary() { echo "$1"; echo "$1" >> "$GITHUB_STEP_SUMMARY"; } + configuration_error() { + echo "::error title=Darkbloom watchdog configuration::$1" + exit 1 + } + + if [ "${WATCHDOG:-}" = off ]; then + summary "The Darkbloom watchdog is off: DARKBLOOM_WATCHDOG is 'off'." + exit 0 + fi + minutes=${MINUTES:-30} + if ! [[ $minutes =~ ^[0-9]{1,4}$ ]] || ((10#$minutes < 15 || 10#$minutes > 1440)); then + configuration_error "DARKBLOOM_WATCHDOG_MINUTES must be 15 to 1440" + fi + minutes=$((10#$minutes)) + route_job=${ROUTE_JOB:-Select Runners} + api=${API_URL:-https://api.github.com} + [[ $api == https://* ]] || configuration_error "the API URL must start with https://" + [[ ${REPOSITORY:-} =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || configuration_error "no repository" + # A random delay, so that repositories and Darkbloom's rounds do not + # move in step. Tests set these. + jitter=${JITTER_SECONDS:-60} + poll=${POLL_SECONDS:-10} + cancel_wait=${CANCEL_WAIT_SECONDS:-120} + app=${APP_SLUG:-darkbloom-sandbox} + max_rescues=2 + rerun_title="Cancelled to re-run on the fallback runners" + cancel_title="Cancelled: rescued once already, not re-run" + sleep $((RANDOM % (jitter + 1))) + + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + # One API call: sets STATUS (000 when the transport failed); the + # body is in $tmp/body. + request() { # method path [JSON body] + local method=$1 path=$2 + if [ $# -ge 3 ]; then + set -- --header 'Content-Type: application/json' --data-binary "$3" + else + set -- + fi + STATUS=$(curl --disable --silent --show-error --proto '=https' --max-time 20 \ + --max-filesize 16777216 --user-agent darkbloom-watchdog/1 --request "$method" "$@" \ + --header "Authorization: Bearer $GH_TOKEN" --header 'Accept: application/vnd.github+json' \ + --header 'X-GitHub-Api-Version: 2022-11-28' --output "$tmp/body" --write-out '%{http_code}' \ + "${api%/}/repos/$REPOSITORY/$path") || STATUS=000 + } + # Large JSON never goes on jq's command line: one argument is at + # most 128 KiB on Linux, and a day of runs is more ("Argument list + # too long"). Pages go through files, the rest through stdin. + # The repository's runs with `status` created in the last day, as + # one JSON array, up to 1,000; fails when GitHub does. + runs_with() { # status + local page=1 count + : >"$tmp/run-pages" + while :; do + request GET "actions/runs?status=$1&created=%3E%3D$since&per_page=100&page=$page" + [ "$STATUS" = 200 ] || return 1 + jq -c '.workflow_runs // []' "$tmp/body" >>"$tmp/run-pages" + count=$(jq '.workflow_runs // [] | length' "$tmp/body") + [ "$count" = 100 ] && [ "$page" -lt 10 ] || break + page=$((page + 1)) + done + jq -cs 'add // []' "$tmp/run-pages" + } + # The run's jobs (filter latest or all) as one JSON array, up to + # 1,000; fails when GitHub does. + jobs_of() { # run filter + local page=1 count + : >"$tmp/job-pages" + while :; do + request GET "actions/runs/$1/jobs?filter=$2&per_page=100&page=$page" + [ "$STATUS" = 200 ] || return 1 + jq -c '.jobs // []' "$tmp/body" >>"$tmp/job-pages" + count=$(jq '.jobs // [] | length' "$tmp/body") + [ "$count" = 100 ] && [ "$page" -lt 10 ] || break + page=$((page + 1)) + done + jq -cs 'add // []' "$tmp/job-pages" + } + # Waits up to $2 seconds for GitHub to report the run completed. + completed() { # run seconds + local deadline=$((SECONDS + $2)) + while :; do + request GET "actions/runs/$1" + [ "$STATUS" = 200 ] && [ "$(jq -r .status "$tmp/body")" = completed ] && return 0 + [ "$SECONDS" -lt "$deadline" ] || return 1 + sleep "$poll" + done + } + # Darkbloom's labels (self-hosted beside a darkbloom-* label), a + # GitHub time in Unix seconds (null when absent), a name safe to + # print (no workflow commands, no markup), and a marker check run. + # shellcheck disable=SC2016 # jq's variables + defs='def darkbloom: (.labels // [] | map(ascii_downcase)) + | index("self-hosted") != null and any(.[]; startswith("darkbloom-")); + def at: if type == "string" then sub("[.][0-9]+Z$"; "Z") | fromdateiso8601 else null end; + def clean: tostring | gsub("[^A-Za-z0-9 ._()/,+-]"; "?") | .[0:80]; + def marker($id): .check_runs[]? | select(.name == "Darkbloom watchdog" and .external_id == $id);' + + # Re-runs run $1 after its cancel: the route job and its dependents, + # or the whole run when it has no single route job or the cancel + # interrupted a job that started before the route job completed (a + # route job's rerun would leave it cancelled). Prints what it re-ran. + rerun() { # run attempt + local jobs route + jobs=$(jobs_of "$1" latest) || return 1 + route=$(jq -r --arg name "$route_job" --argjson attempt "$2" "$defs"' + [.[] | select((.name == $name or (.name | endswith(" / " + $name))) and .conclusion == "success")] as $r + | if ($r | length) != 1 then empty + else ($r[0].completed_at | at // 0) as $done + | if any(.[]; .run_attempt == $attempt and .conclusion == "cancelled" and (.runner_id // 0) != 0 + and ((.started_at | at) // 1e12) < $done) then empty else $r[0].id end + end' <<<"$jobs") + if [ -n "$route" ]; then + request POST "actions/jobs/$route/rerun" + what="its route job and dependents" + else + request POST "actions/runs/$1/rerun" + what="the whole run" + fi + case $STATUS in + 201) echo "$what" ;; + 403) echo "nothing: it is re-running already" ;; + *) return 1 ;; + esac + } + + now=$(date -u +%s) + since=$(date -u -d "@$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \ + || date -u -r "$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ) + before=$((now - minutes * 60)) + failed=0 + acted=0 + : >"$tmp/runs" + for status in in_progress queued; do + runs_with "$status" >>"$tmp/runs" || { echo "::warning::Listing $status runs failed (HTTP $STATUS)"; exit 1; } + done + runs=$(jq -cs 'add // []' "$tmp/runs") + + # Rescues this workflow cancelled and did not re-run (cut short + # between the two): cancelled runs changed in the last half hour + # whose current attempt carries this workflow's own marker. + cancelled=$(runs_with cancelled) || { echo "::warning::Listing cancelled runs failed (HTTP $STATUS)"; exit 1; } + resumable=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson recent "$((now - 1800))" "$defs"' + .[] | select((.id | tostring) != $self and ((.updated_at | at) // 0) >= $recent) + | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$cancelled") + while read -r run attempt sha; do + [ -n "$run" ] || continue + request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100" + [ "$STATUS" = 200 ] || continue + jq -e --arg id "run:$run:$attempt" --arg title "$rerun_title" "$defs"'[marker($id) + | select(.app.slug == "github-actions" and .output.title == $title)] | length > 0' \ + "$tmp/body" >/dev/null || continue + acted=1 + if what=$(rerun "$run" "$attempt"); then + summary "Run $run attempt $attempt: resumed its rescue, re-ran $what." + else + echo "::warning::Run $run: re-running it failed (HTTP $STATUS)" + failed=1 + fi + done <<<"$resumable" + + # Runs whose attempt started before the wait, other than this. + candidates=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson before "$before" "$defs"' + unique_by(.id) | .[] | select((.id | tostring) != $self) + | select((.run_started_at // .created_at | at) as $t | $t != null and $t <= $before) + | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$runs") + rescues=0 + while read -r run attempt sha; do + [ -n "$run" ] || continue + jobs=$(jobs_of "$run" latest) || { echo "::warning::Run $run: listing its jobs failed"; failed=1; continue; } + # Stranded: a Darkbloom job of this attempt queued with no runner + # since before the wait, timed from its own creation (GitHub + # creates a job behind `needs:` once those are done), while no + # Darkbloom job of the run got a runner within the wait (runners + # still coming: a payer at its limit). Other Darkbloom jobs of the + # run that ran, or run still, do not hold it back. + stranded=$(jq -r --argjson before "$before" --argjson attempt "$attempt" "$defs"' + if any(.[]; darkbloom and (.runner_id // 0) != 0 and ((.started_at | at) // 0) > $before) then "" + else [.[] | select(.run_attempt == $attempt and .status == "queued" and (.runner_id // 0) == 0 + and darkbloom and ((.created_at | at) // 1e12) <= $before) | .name | clean] + | join(", ") end' <<<"$jobs") + [ -n "$stranded" ] || continue + request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100" + [ "$STATUS" = 200 ] || { echo "::warning::Run $run: reading its checks failed (HTTP $STATUS)"; failed=1; continue; } + # Darkbloom's watchdog (its App) marked this attempt within 20 + # minutes: it is rescuing it. + if jq -e --arg id "run:$run:$attempt" --arg app "$app" --argjson since "$((now - 1200))" "$defs"' + [marker($id) | select(.app.slug == $app and ((.started_at // .completed_at | at) // 0) >= $since)] + | length > 0' "$tmp/body" >/dev/null; then + summary "Run $run attempt $attempt: Darkbloom's watchdog is rescuing it." + continue + fi + # Rescued before, by either watchdog: a marker of an earlier + # attempt, or an earlier attempt's Darkbloom job cancelled with no + # runner after the whole wait. Then it is only cancelled. + marked=$(jq -r --arg run "run:$run:" --argjson attempt "$attempt" '[.check_runs[]? + | select(.name == "Darkbloom watchdog" and (.external_id // "" | startswith($run))) + | .external_id | ltrimstr($run) | tonumber? | select(. < $attempt)] | length > 0' "$tmp/body") + all=$(jobs_of "$run" all) || { echo "::warning::Run $run: listing its attempts failed"; failed=1; continue; } + once=$(jq -r --argjson attempt "$attempt" --argjson wait "$((minutes * 60))" --argjson marked "$marked" "$defs"' + $marked or any(.[]; .run_attempt < $attempt and .conclusion == "cancelled" and (.runner_id // 0) == 0 + and darkbloom and ((.completed_at | at) // 0) - ((.created_at | at) // 1e12) >= $wait)' <<<"$all") + if [ "$rescues" -ge "$max_rescues" ]; then + summary "Run $run attempt $attempt: stranded; left for the next round ($max_rescues rescues a round)." + continue + fi + # Nobody re-ran it since it was listed. + request GET "actions/runs/$run" + [ "$STATUS" = 200 ] && [ "$(jq -r .run_attempt "$tmp/body")" = "$attempt" ] || continue + rescues=$((rescues + 1)) + acted=1 + # Marked first: a rescue cut short after the cancel resumes next time. + title=$rerun_title + [ "$once" != true ] || title=$cancel_title + mark=$(jq -cn --arg sha "$sha" --arg id "run:$run:$attempt" --arg title "$title" --arg jobs "$stranded" '{ + name: "Darkbloom watchdog", head_sha: $sha, external_id: $id, status: "completed", + conclusion: "neutral", output: {title: $title, + summary: "A Darkbloom job of this run attempt got no runner (\($jobs)): the repository watchdog cancelled it."}}') + request POST check-runs "$mark" + [ "$STATUS" = 201 ] || { echo "::warning::Run $run: marking it failed (HTTP $STATUS)"; failed=1; continue; } + request POST "actions/runs/$run/cancel" + case $STATUS in + 202) ;; + 409) summary "Run $run attempt $attempt: someone else is cancelling it; not re-run."; continue ;; + *) echo "::warning::Run $run: cancelling it failed (HTTP $STATUS)"; failed=1; continue ;; + esac + if ! completed "$run" "$cancel_wait"; then + request POST "actions/runs/$run/force-cancel" + completed "$run" 60 || { echo "::warning::Run $run: GitHub did not cancel it"; failed=1; continue; } + fi + if [ "$once" = true ]; then + summary "Run $run attempt $attempt: cancelled ($stranded waited ${minutes}+ minutes for a Darkbloom runner); it was rescued once already, so it is not re-run again." + continue + fi + if what=$(rerun "$run" "$attempt"); then + summary "Run $run attempt $attempt: $stranded waited ${minutes}+ minutes for a Darkbloom runner; cancelled and re-ran $what on the fallback runners." + else + echo "::warning::Run $run: re-running it failed (HTTP $STATUS)" + failed=1 + fi + done <<<"$candidates" + [ "$acted" = 1 ] || summary "No run is stranded on Darkbloom." + exit "$failed"
diff --git ml-explore/mlx/.github/workflows/documentation.yml Layr-Labs/mlx/.github/workflows/documentation.yml deleted file mode 100644 index fad1647999807332410edc20de0a6254dd617b5b..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/workflows/documentation.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Documentation - -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs - - deploy: - needs: build - permissions: - pages: write - id-token: write - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v5
diff --git ml-explore/mlx/.github/workflows/release.yml Layr-Labs/mlx/.github/workflows/release.yml deleted file mode 100644 index 0a03b429ac9dd649b8f7fda836eedd264927385f..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/workflows/release.yml +++ /dev/null @@ -1,321 +0,0 @@ -name: 'Release build' -description: 'Build Python wheels for nightly or offical releases' - -on: - push: - tags: - - 'v*' - workflow_dispatch: - inputs: - publish: - description: 'Publish to PyPI' - required: false - type: boolean - dev-release: - description: 'Development release (DEV_RELEASE=1)' - required: false - type: boolean - schedule: - - cron: 33 6 * * * - -# In jobs we must use |*publish| instead of |inputs.publish| because we can not -# set default value for workflow_dispatch inputs reliably. -env: - publish: &publish ${{ inputs.publish || github.event_name == 'push' }} - pypi-env: &pypi-env ${{ (inputs.publish || github.event_name == 'push') && 'pypi' || 'dry-run' }} - -permissions: - contents: read - -jobs: - build_documentation: - name: Build documentation - if: github.repository == 'ml-explore/mlx' - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs - - deploy_documentation: - name: Deploy documentation - if: *publish - needs: build_documentation - permissions: - pages: write - id-token: write - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v5 - - build_frontend: - name: ${{ matrix.os }} (python-${{ matrix.python-version }}, ${{ matrix.arch }}) - strategy: - matrix: - os: ['Linux', 'Windows'] - arch: ['x86_64', 'aarch64'] - python-version: &pyver ['3.10', '3.11', '3.12', '3.13', '3.13t', '3.14', '3.14t', '3.15', '3.15t'] - # There is no cp310 binary for Windows on arm. - exclude: - - os: 'Windows' - arch: 'aarch64' - python-version: '3.10' - runs-on: |- - ${{ case(matrix.os == 'Windows', - case(matrix.arch == 'aarch64', 'windows-11-arm', - 'windows-2022'), - case(matrix.arch == 'aarch64', 'ubuntu-22.04-arm', - 'ubuntu-22.04')) - }} - env: &build-env - PYPI_RELEASE: 1 - DEV_RELEASE: ${{ inputs.dev-release && 1 || 0 }} - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - id: setup - with: - python-version: ${{ matrix.python-version }} - ccache-key: 'release' - ccache-save: false - - uses: ./.github/actions/build-wheel - with: - cmake-args: ${{ steps.setup.outputs.cmake-args }} - build-backend: false - - run: unzip -l wheelhouse/*.whl - - uses: actions/upload-artifact@v7 - with: - name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }} - path: wheelhouse/mlx-*.whl - if-no-files-found: error - - build_backend: - name: ${{ matrix.os }} (${{ matrix.toolkit }}, ${{ matrix.arch }}) - if: github.repository == 'ml-explore/mlx' - strategy: - matrix: - os: ['Linux', 'Windows'] - arch: ['x86_64', 'aarch64'] - toolkit: ['cpu', 'cuda-12.9', 'cuda-13.0'] - exclude: - # CUDA does not support Windows on arm. - - os: 'Windows' - arch: 'aarch64' - toolkit: 'cuda-12.9' - - os: 'Windows' - arch: 'aarch64' - toolkit: 'cuda-13.0' - runs-on: |- - ${{ case(matrix.os == 'Windows', - case(matrix.arch == 'aarch64', 'windows-11-arm', - 'windows-2022-large'), - case(matrix.arch == 'aarch64', 'ubuntu-22-large-arm', - 'ubuntu-22-large')) - }} - env: *build-env - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - id: setup - with: - toolkit: ${{ matrix.toolkit }} - ccache-key: 'release' - - uses: ./.github/actions/build-wheel - with: - cmake-args: ${{ steps.setup.outputs.cmake-args }} - build-frontend: false - - run: unzip -l wheelhouse/*.whl - - uses: actions/upload-artifact@v7 - with: - name: backend-${{ matrix.toolkit }}-${{ runner.os }}-${{ runner.arch }} - path: wheelhouse/*.whl - if-no-files-found: ignore - - build_mac_wheels: - name: macOS (python-${{ matrix.python-version }}) - if: github.repository == 'ml-explore/mlx' - strategy: - matrix: - python-version: *pyver - runs-on: 'macos-26-xlarge' - env: *build-env - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - id: setup - with: - toolkit: 'metal' - python-version: ${{ matrix.python-version }} - ccache-key: 'release' - ccache-save: ${{ matrix.python-version == '3.10' }} - - name: Build macOS 14 package - uses: ./.github/actions/build-wheel - with: - macos-target: '14.0' - cmake-args: ${{ steps.setup.outputs.cmake-args }} - build-backend: ${{ matrix.python-version == '3.10' }} - - name: Build macOS 15 package - uses: ./.github/actions/build-wheel - with: - macos-target: '15.0' - cmake-args: ${{ steps.setup.outputs.cmake-args }} - build-backend: ${{ matrix.python-version == '3.10' }} - - name: Build macOS 26 package - uses: ./.github/actions/build-wheel - with: - macos-target: '26.2' - cmake-args: ${{ steps.setup.outputs.cmake-args }} - build-backend: ${{ matrix.python-version == '3.10' }} - - name: Display content of the wheels - run: for WHEEL in wheelhouse/*.whl; do unzip -l $WHEEL; echo; done - - name: Upload frontend packages - uses: actions/upload-artifact@v7 - with: - name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }} - path: wheelhouse/mlx-*.whl - if-no-files-found: error - - name: Upload backend packages - if: matrix.python-version == '3.10' - uses: actions/upload-artifact@v7 - with: - name: backend-metal-${{ runner.os }}-${{ runner.arch }} - path: wheelhouse/mlx_metal-*.whl - if-no-files-found: error - - test_wheel: - name: Test (${{ matrix.os }}, ${{ matrix.toolkit }}, ${{ matrix.arch }}) - if: github.repository == 'ml-explore/mlx' - needs: [build_frontend, build_backend, build_mac_wheels] - strategy: - matrix: - os: ['Linux', 'Windows'] - arch: ['aarch64'] - toolkit: ['cpu'] - include: - - os: 'Linux' - arch: 'x86_64' - toolkit: 'cpu' - - os: 'Linux' - arch: 'x86_64' - toolkit: 'cuda-12.9' - - os: 'Linux' - arch: 'x86_64' - toolkit: 'cuda-13.0' - - os: 'Windows' - arch: 'x86_64' - toolkit: 'cpu' - - os: 'macOS' - arch: 'aarch64' - toolkit: 'metal' - runs-on: |- - ${{ case(matrix.os == 'Windows', case(matrix.arch == 'aarch64', 'windows-11-arm', - 'windows-2022'), - matrix.os == 'macOS', 'macos-26-xlarge', - case(matrix.arch == 'x86_64' && startsWith(matrix.toolkit, 'cuda'), 'gpu-t4-4-core', - matrix.arch == 'aarch64', 'ubuntu-22.04-arm', - 'ubuntu-22.04')) - }} - steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup - with: - toolkit: ${{ matrix.toolkit }} - use-ccache: false - - uses: ./.github/actions/test-wheel - with: - toolkit: ${{ matrix.toolkit }} - - pypi-publish-frontend: - name: Publish mlx to PyPI - runs-on: ubuntu-latest - needs: [test_wheel] - permissions: - id-token: write - environment: - name: *pypi-env - url: https://pypi.org/p/mlx - steps: - - uses: actions/download-artifact@v8 - with: - pattern: frontend-* - merge-multiple: true - path: dist - - name: Display structure of downloaded files - run: du -ah dist - - name: Publish package distributions to PyPI - if: *publish - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://upload.pypi.org/legacy/ - - pypi-publish-cuda: - name: Publish mlx-cuda to PyPI - runs-on: ubuntu-latest - needs: [test_wheel] - permissions: - id-token: write - environment: - name: *pypi-env - url: https://pypi.org/p/mlx-cuda - steps: - - uses: actions/download-artifact@v8 - with: - pattern: backend-cuda* - merge-multiple: true - path: dist - - name: Display structure of downloaded files - run: du -ah dist - - name: Publish package distributions to PyPI - if: *publish - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://upload.pypi.org/legacy/ - - pypi-publish-cpu: - name: Publish mlx-cpu to PyPI - runs-on: ubuntu-latest - needs: [test_wheel] - permissions: - id-token: write - environment: - name: *pypi-env - url: https://pypi.org/p/mlx-cpu - steps: - - uses: actions/download-artifact@v8 - with: - pattern: backend-cpu-* - merge-multiple: true - path: dist - - name: Display structure of downloaded files - run: du -ah dist - - name: Publish package distributions to PyPI - if: *publish - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://upload.pypi.org/legacy/ - - pypi-publish-metal: - name: Publish mlx-metal to PyPI - runs-on: ubuntu-latest - needs: [test_wheel] - permissions: - id-token: write - environment: - name: *pypi-env - url: https://pypi.org/p/mlx-metal - steps: - - uses: actions/download-artifact@v8 - with: - pattern: backend-metal-* - path: dist - - name: Display structure of downloaded files - run: du -ah dist - - name: Publish package distributions to PyPI - if: *publish - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://upload.pypi.org/legacy/
diff --git ml-explore/mlx/.github/workflows/update_bypass_list.yml Layr-Labs/mlx/.github/workflows/update_bypass_list.yml deleted file mode 100644 index f5ecb25f7ae679693e7f14158b9da0b929494780..0000000000000000000000000000000000000000 --- ml-explore/mlx/.github/workflows/update_bypass_list.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: 'Update bypass list' -description: 'Update interaction-limits bypass list with eligible contributors' - -on: - workflow_dispatch: - push: - branches: - - main - schedule: - - cron: 33 6 * * * - -permissions: - contents: write - -jobs: - update_bypass_list: - name: 'Update bypass list' - if: github.repository == 'ml-explore/mlx' - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v7 - - env: - # Can only use PAT with permissions: admin:org_hook, public_repo - GITHUB_TOKEN: ${{ secrets.ZCBENZ_TOKEN_UPDATE_BYPASS_LIST }} - run: node .github/scripts/update-bypass-list.js ml-explore mlx
diff --git ml-explore/mlx/AGENTS.md Layr-Labs/mlx/AGENTS.md index 969236055007943976cf084a87730644ed20c59f..06ca2579b7b97c1f0ad224c3ebab6311c7f01ecf 100644 --- ml-explore/mlx/AGENTS.md +++ Layr-Labs/mlx/AGENTS.md @@ -1,5 +1,13 @@ # Instructions for MLX   +## Working in our MLX forks + +The Layr-Labs MLX forks, including Darkbloom, Darkbloom Sandboxes, and related +work, are our repositories. In them, agents MAY work directly: write commit +messages and PR descriptions, run `git push`, create PRs and issues, and reply +to review comments on the user's behalf. The upstream rules below remain in +force for upstream contributions. + ## Agent rules   - Reject vague instructions when user does not show understands of the code
diff --git ml-explore/mlx/CMakeLists.txt Layr-Labs/mlx/CMakeLists.txt index 3f2330483dc85d5b9607c9dc7a25327c02c0dd8e..47b4d608a02e12b44e8a6cb9e79ccdfa1b079cd3 100644 --- ml-explore/mlx/CMakeLists.txt +++ Layr-Labs/mlx/CMakeLists.txt @@ -228,7 +228,11 @@ endif()   set(METAL_CPP_URL https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip) - FetchContent_Declare(metal_cpp URL ${METAL_CPP_URL}) + FetchContent_Declare( + metal_cpp + URL ${METAL_CPP_URL} + URL_HASH + SHA256=4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4) FetchContent_MakeAvailable(metal_cpp) target_include_directories( mlx PUBLIC $<BUILD_INTERFACE:${metal_cpp_SOURCE_DIR}>
diff --git ml-explore/mlx/FORKDIFF.md Layr-Labs/mlx/FORKDIFF.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf57c0adf81c87a5804acd527b17692cbb0dda7 --- /dev/null +++ Layr-Labs/mlx/FORKDIFF.md @@ -0,0 +1,147 @@ +# Fork diff: what this fork changes, and keeping that page honest + +This repository is a fork of [`ml-explore/mlx`](https://github.com/ml-explore/mlx). +Everything it changes relative to upstream is published as a browsable page: + +**https://layr-labs.github.io/mlx/** + +The page is rendered by [`protolambda/forkdiff`](https://github.com/protolambda/forkdiff) +from [`fork.yaml`](fork.yaml) at the repo root, in the style of +[op-geth's go-ethereum fork diff](https://op-geth.optimism.io/). `fork.yaml` +groups the changed files into sections with a paragraph each, names the exact +upstream commit the fork is based on (`base.hash`), and lists files that are +not code (`ignore`). Every push to `main` re-renders and redeploys it +(`.github/workflows/forkdiff-pages.yml`). + +**One-time setup.** GitHub Pages has to be switched on by a repo admin: +Settings → Pages → Source: **GitHub Actions**. The workflow token cannot do +this itself. Until it's done the deploy workflow still builds the page (kept +as a run artifact, `forkdiff-page`) and exits with a notice instead of failing. + +## Native CI + +The Linux lint job, ASAN/UBSAN tests, fork-diff check and page renderer use only +Darkbloom Linux ARM64 runners. All eight Mac jobs in `fork-tests.yml` use only +Darkbloom macOS ARM64 runners. Each names its VM size ([Job sizes](#job-sizes)). +They keep their original steps, tests and job timeouts. +The sanitizer jobs use the qualified image's compilers and dependencies, with a +tool preflight in place of installing packages through sudo, and are capped +at 60 minutes. When compatible capacity is busy they wait; these jobs have no GitHub-hosted or Blacksmith +fallback. The current profile qualification lifetime is one hour, and the +existing watchdog can cancel or retry a job after its 30-minute wait threshold. +The watchdog can rerun a stranded workflow once, then cancel another stranded +attempt. These jobs keep native labels on a rerun; the watchdog cannot send them +to hosted runners. These bounds are not a promise of a 24-hour native queue. +The `DARKBLOOM_ROUTING` variable controls the separate dynamic route workflow; +it does not turn off these native-only jobs. + +The Fedora aarch64 job runs the unchanged Fedora script on a Darkbloom Linux +ARM64 runner. The sandbox has no Docker, so `.github/scripts/fedora-proot/` +unpacks the archived Fedora 42 container rootfs (pinned by digest) and runs the +script under PRoot, built from pinned source with its missing ARM64 `faccessat2` +entry added. PRoot fakes root through ptrace and is not an isolation boundary; +the job VM is. The Fedora x86_64 job keeps its hosted runner: emulating x86 on +ARM was not qualified. The GitHub-hosted Pages job still packages and publishes +the rendered artifact through its protected environment. If its first deploy +fails before it creates a deployment (the packaged artifact is not listed yet), +it waits 20 seconds and tries once more. The disabled native CodeQL workflow keeps its separate routing +and activation rules. + +### Job sizes + +Each Darkbloom macOS job names its VM size in its runner label, for example +`darkbloom-macos-arm64-4x16` (4 vCPUs, 16 GiB). A job without a size gets the +size that the approval pins (12 vCPUs, 32 GiB). The image pipeline signs +4x16, 4x24, 8x16 and 12x32. A job gets the smallest signed size that has 30% +headroom over its measured memory peak. A job that took less than 10 minutes +must stay under 10 minutes. + +The peak of a job is the larger of two sampler figures: used memory (app + +wired + compressed) and the sum of the lifetime peak footprints of the +runner user's processes. The second matters where memory is compressed: +used memory counts compressed pages at their compressed size. The idle VM +uses about 6 GiB. Pull request runs 44750715218 and 44754340762 measured +every job. + +| Job | Size | Wall time on 12 vCPUs (runs 43368507444 to 43569480732) | Hosted 3 vCPUs, 7 GiB | Measured (size: wall time, peak) | +|---|---|---|---|---| +| `build-wheel` | 4x16 | 153 to 354 s | 575 s (run 43120201853, `macos-26`) | 4x16: 230 and 242 s, 10.65 GiB | +| `build-cpp` | 4x16 | 277 to 620 s; p90 about 480 s. The slow runs spend up to 190 s in the build cache action. | 940 s, of which the compile is 632 s (run 43120201853) | 8x16: 302 s, 10.42 GiB; 4x16: 374 s, 10.56 GiB | +| `python-gpu` (2 shards) | 4x24 | 171 to 541 s | 297 to 635 s (run 43531506709, `xcode-27`) | 4x16: 182 to 307 s. Shard 1 used 11.65 GiB with 4.1 GiB compressed; its processes' footprints sum to 13.21 GiB. 16 GiB is less than 1.3 times that. | +| `python-cpu` (3 shards) | 12x32 | 152 to 444 s | 279 to 546 s | 4x16: 190 to 258 s, 13.20 GiB used with 7.1 GiB compressed, memory pressure at warning. 4x24: 163 to 273 s, 19.26 GiB used (footprints 17.89 GiB). 24 GiB is less than 1.3 times 19.26 GiB, and 12x32 is the next signed size with more memory. | +| `metal-build-and-test` | 4x16 | 34 to 190 s | 20 to 23 s | 4x16: 36 and 38 s, 6.07 GiB | + +`test_init_reduce_large_output` needs a 4 GiB Metal buffer on the GPU and a +`memory_size` of 16 GiB on the CPU. The GPU shards (a Metal buffer can have +half of the VM's memory) and the CPU shards give both, so the test still +runs. Runs 44750715218 and 44754340762 ran it on both. + +Every macOS job runs `.github/scripts/ci-resource-sampler.py`, a copy of the +sampler of Layr-Labs/d-inference (wrapped to this repository's ruff rules), from +its checkout on. Its last step, +"Report the resource samples", prints the memory peak of each class, the +three largest processes, the busy vCPUs and the sampled time scaled to 4 and +8 vCPUs. Use these numbers to change a size. Check Lint runs +`.github/scripts/test-runner-sizes.py`. It fails when a macOS job names no +size, a size that is not signed, or a size other than the one its table +gives. + +## The gate + +A fork-diff page is only useful while it is true, and two things make it go +stale silently. `scripts/check_forkdiff.py` runs on every PR and on every push +to `main` (`.github/workflows/forkdiff-check.yml`) and fails on both: + +| Drift | Check | Why it matters | +|-------|-------|----------------| +| **Merge of newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a merge the old base makes upstream's own commits look like fork changes: thousands of files, none of them ours. | +| **New fork change nobody described** | every path in `git diff --name-only base.hash HEAD` must match a section glob or a global `ignore` | An undescribed file is a change the page can't explain. | +| **Section describing code we no longer carry** | every glob must match at least one changed path | Stale sections are as misleading as missing ones. | + +The check also renders the page, so a `fork.yaml` that forkdiff itself rejects +cannot merge. The deploy workflow runs the same check before publishing, so a +stale analysis is never served. + +## Day to day + +**Adding or changing fork files in a PR.** If the check lists uncovered files, +add each to the section that explains it in `fork.yaml` (or start a new +section with a short description). Files that are not code go under the +top-level `ignore`. Keep globs specific: a `mlx/**` catch-all would swallow +upstream's changes after a bad rebase and defeat the gate. + +**Upstream sync policy (2026-10-22).** The fork merges upstream `main` when +David directs it. Use a merge commit. Do not rebase. Each merge does these steps: + +1. Set `base.hash` to the new merge-base, `git merge-base HEAD upstream/main`. +2. Read each `fork.yaml` section again. Remove a section when upstream now has + the same change. Change a section when the merge changed the fork code. +3. Delete again the upstream workflows and actions that the fork removes. The + "Fork tooling" section lists them. +4. Run the check below until it passes. + +Between merges, port an upstream fix that the fork needs as its own commit. +Describe the port in its own `fork.yaml` section. The check compares the fork +with `base.hash`: + +``` +python3 -m pip install pyyaml +python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main +``` + +**Previewing the page locally** (Go 1.21+): + +``` +go run github.com/protolambda/forkdiff@v0.1.1 -repo . -fork fork.yaml -out tmp/index.html +open tmp/index.html +``` + +## Design notes + +- `base.hash` is a full 40-hex commit id, never a branch name: a symbolic base + would move underneath the page and the gate alike. +- Section `ignore` lists count as coverage (forkdiff still lists those files, + grayed out); the top-level `ignore` is for things that aren't code at all. +- The glob semantics are forkdiff's: `*` and `?` stop at `/`, `**` spans + directories (and may match none), `[!x]` negates a class. +- The check is pure git + PyYAML so the same command runs locally and in CI.
diff --git ml-explore/mlx/README.md Layr-Labs/mlx/README.md index fb30a24f2ce87d6f81822fc51e01c9fb6d38de28..b316d5a61bb3f321fc5befe81bc75ae2969875ad 100644 --- ml-explore/mlx/README.md +++ Layr-Labs/mlx/README.md @@ -6,6 +6,8 @@ [**Examples**](#examples)   [![CircleCI](https://circleci.com/gh/ml-explore/mlx.svg?style=svg)](https://circleci.com/gh/ml-explore/mlx)   +> **This is a fork.** `Layr-Labs/mlx` tracks [`ml-explore/mlx`](https://github.com/ml-explore/mlx) and carries the kernel, allocator and Metal-runtime work behind Layr-Labs' Apple-silicon inference stack (`mlx` → `mlx-c` → `mlx-swift` → `mlx-swift-lm`). Everything changed relative to upstream is published as a fork diff at **https://layr-labs.github.io/mlx/**, described in [`fork.yaml`](fork.yaml) and kept honest by CI — see [FORKDIFF.md](FORKDIFF.md). + MLX is an array framework for machine learning on Apple silicon, brought to you by Apple machine learning research.
diff --git ml-explore/mlx/docs/ci-codeql-native.md Layr-Labs/mlx/docs/ci-codeql-native.md new file mode 100644 index 0000000000000000000000000000000000000000..8128ab3e03efa2583d682e1ce82cfffd57e6b7e9 --- /dev/null +++ Layr-Labs/mlx/docs/ci-codeql-native.md @@ -0,0 +1,55 @@ +# Native CodeQL activation + +`codeql-native.yml` is inactive unless the repository variable `CODEQL_NATIVE` +is exactly `on`. Merging the workflow does not switch GitHub's default setup or +change its security coverage. The operator must review that switch separately. + +The scan job has `contents: read` only. It runs the pinned CodeQL2.27.4 ARM64 +bundle against the Actions event commit, without building repository code. It +uses the same default query suites for Actions, C/C++ and Python. The Darkbloom +route has one `codeql` Linux ARM64 lane; hosted fallback is also ARM64. + +The separate GitHub-hosted upload job has only `contents: read`, `actions: read` +and `security-events: write`. It does not check out or run repository code. Its +only inputs are the same run's three SARIF files and a bounded manifest, checked +against the event repository, commit, ref, run and attempt. Unexpected files, +symlinks, changed hashes, different tools and missing fingerprints are refused. +The official pinned uploader preserves these categories: + +- `/language:actions` +- `/language:c-cpp` +- `/language:python` + +Native CodeQL already records the primary-line fingerprints. The uploader gets +an empty directory as `checkout_path`; it preserves the supplied fingerprints +and uses the Actions event SHA/ref. No source files are transferred to this job. +GitHub permits code-scanning uploads for `pull_request` runs, including runs with +read-only token scopes. The uploader ignores ref/SHA overrides for fork PRs. + +## Operator gates + +1. Keep `CODEQL_NATIVE` unset/off while reviewing and merging this source. Verify + default setup remains enabled and its three analyses are current. Record its + settings and latest successful analysis IDs for rollback. +2. Approve the single `codeql` lane for the reviewed Linux image and its existing + network template. Confirm the image/worker and capacity before switching. +3. Switch GitHub from default to advanced setup with admin authorization. Default + setup blocks CodeQL API uploads, so it must not remain the active uploader. + Ensure the new workflow is enabled, then set `CODEQL_NATIVE=on` and dispatch + `main`. The weekly schedule and subsequent main pushes/PRs use this workflow. +4. Require successful native compute, all three processed GitHub analyses on the + expected commit/categories, and physical runner retirement. Also qualify a + fork PR upload using its merge ref and unprivileged PR token. An artifact-only + scan does not prove the upload/alert integration. +5. After the new analyses are healthy, review any stale default-setup analysis + configuration before removing it; category names alone do not merge distinct + workflow configurations. Never delete the last working coverage first. + +Rollback: turn `CODEQL_NATIVE` off, restore the recorded default-setup settings, +and require its three initial analyses to succeed. Do not leave both modes active. + +References: + +- [Default versus advanced setup](https://docs.github.com/en/code-security/reference/code-scanning/troubleshoot-analysis-errors/results-different-than-expected) +- [PR uploads with read-only scopes](https://docs.github.com/en/enterprise-cloud@latest/code-security/reference/code-scanning/troubleshoot-analysis-errors/resource-not-accessible) +- [Pinned uploader inputs](https://github.com/github/codeql-action/blob/33d7b85da1a04171e211befe2c739303b9a4c066/upload-sarif/action.yml)
diff --git ml-explore/mlx/python/tests/test_conv.py Layr-Labs/mlx/python/tests/test_conv.py index 24ec142180bf4def0e34965def2ef03e430e38af..8ec1b054a3a673d1629f69701ebca2f3704c30da 100644 --- ml-explore/mlx/python/tests/test_conv.py +++ Layr-Labs/mlx/python/tests/test_conv.py @@ -1438,6 +1438,11 @@ self.assertTrue(mx.allclose(g_gpu, g_cpu, atol=1e-4))   @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_conv2d_winograd_batch_tiling(self): + # Winograd and its batch tiling exist only in the Metal backend. On + # the CPU every run takes the same path, so the fallback checks + # cannot tell the paths apart. + if mx.default_device() != mx.gpu: + self.skipTest("Winograd batch tiling is specific to the GPU device") # Use envs to test tiling without allocating large buffers. tile_key = "MLX_CONV_WINOGRAD_TILE_BATCH" ws_key = "MLX_CONV_WINOGRAD_WORKING_SET" @@ -1516,6 +1521,10 @@ self.assertTrue(np.allclose(capped, cpu_ref, atol=1e-3))   @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_conv2d_winograd_disable(self): + # Winograd exists only in the Metal backend. On the CPU every run + # takes the same path, so the check cannot tell the paths apart. + if mx.default_device() != mx.gpu: + self.skipTest("Winograd is specific to the GPU device") # N * iH * iW >= 4096 selects Winograd only from a batch of 3. np.random.seed(0) x = mx.array(np.random.normal(size=(1, 40, 40, 128)).astype(np.float32))
diff --git ml-explore/mlx/python/tests/test_fft.py Layr-Labs/mlx/python/tests/test_fft.py index 0e410c7c59e283655ad7d6606b08f7dc219e230c..cd19165f268643539d1a0933c3d13b79bd39b310 100644 --- ml-explore/mlx/python/tests/test_fft.py +++ Layr-Labs/mlx/python/tests/test_fft.py @@ -226,6 +226,9 @@ @unittest.skipIf( not mx.metal.is_available(), "the size limit is specific to the Metal FFT plan" ) def test_fft_too_large(self): + # The CPU FFT has no size limit, so this runs only on the GPU device. + if mx.default_device() != mx.gpu: + self.skipTest("the size limit is specific to the GPU device") # Larger than the four step plan can decompose, so it has to throw # rather than run a kernel that silently returns the wrong answer. # CUDA hands this to cuFFT instead and has no such limit.
diff --git ml-explore/mlx/python/tests/test_reduce.py Layr-Labs/mlx/python/tests/test_reduce.py index b46dcee1e2231ae62e305869ebca23af7535d229..71f7476b1a6ef1fb68bd94059cdb0fb28255d53f 100644 --- ml-explore/mlx/python/tests/test_reduce.py +++ Layr-Labs/mlx/python/tests/test_reduce.py @@ -163,6 +163,16 @@ z = np.array(x).sum((0, 2, 3)) self.assertTrue(np.all(z == y))   def test_zero_size(self): + for op in ["all", "any"]: + for shape, axis in [((0,), None), ((0, 3), 0), ((3, 0), 1), ((0, 3), 1)]: + with self.subTest(op=op, shape=shape, axis=axis): + a_np = np.zeros(shape, dtype=np.bool_) + expected = getattr(np, op)(a_np, axis=axis) + actual = getattr(mx, op)(mx.array(a_np), axis=axis) + mx.eval(actual) + self.assertEqual(actual.shape, expected.shape) + self.assertEqual(actual.tolist(), expected.tolist()) + # max and min have no identity, so they are only undefined when an axis # being reduced is itself empty. An array that is empty because of some # other axis reduces into an empty result. @@ -363,6 +373,16 @@ self.assertFalse(x.all().item())   @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_init_reduce_large_output(self): + # The output is 4 GiB. The macOS runners of the fork CI have a 3.5 GiB + # Metal buffer limit and 7 GB of memory, so skip where it cannot fit. + size = 4 * 2**30 + info = mx.device_info(mx.gpu) + if mx.default_device() == mx.gpu: + fits = info["max_buffer_length"] >= size + else: + fits = info["memory_size"] >= 4 * size + if not fits: + self.skipTest("the 4 GiB output does not fit on this device") out = mx.all(mx.zeros((0, 4, 2**30), dtype=mx.bool_), axis=0) mx.eval(out) self.assertTrue(mx.all(out).item())
diff --git ml-explore/mlx/scripts/check_forkdiff.py Layr-Labs/mlx/scripts/check_forkdiff.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff1210829d3f70c873b34ef337041c3078af290 --- /dev/null +++ Layr-Labs/mlx/scripts/check_forkdiff.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Gate: ``fork.yaml`` must describe this fork as it is *now*. + +The fork-diff page (rendered with protolambda/forkdiff and published on GitHub +Pages) is only useful while it is true. Two things make it go stale silently: + +1. **A rebase onto newer upstream.** ``base.hash`` still points at the old + upstream commit, so the page shows upstream's own changes as if the fork + made them. This script requires ``base.hash`` to equal + ``git merge-base HEAD <upstream>``; a rebase moves the merge-base, and the + gate stays red until the hash is bumped. +2. **A new fork change nobody described.** Every path in + ``git diff --name-only base.hash HEAD`` must match a glob in some section + (or a global ``ignore``), and every glob must still match something — a + section describing code the fork no longer carries is as misleading as a + missing one. + +Both are pure git + YAML, so the same check runs locally:: + + python3 scripts/check_forkdiff.py # coverage only + python3 scripts/check_forkdiff.py --upstream-ref upstream/main + +Exit status is non-zero on any violation. ``--review-status-out`` writes the +JSON the CI comment synthesizer consumes (same shape as history-check). +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path +from typing import Iterable + +import yaml + +GLOB_CLASS_RE = re.compile(r"\[([^\]]*)\]") + + +def glob_to_regex(glob: str) -> re.Pattern[str]: + """Translate a forkdiff glob into a regex over the repo-relative path. + + Semantics follow the doublestar rules forkdiff uses: ``*`` and ``?`` never + cross a ``/``; ``**`` matches any number of directories (``a/**/b`` also + matches ``a/b``); ``[...]`` character classes pass through, with a leading + ``!`` meaning negation. + """ + out: list[str] = [] + i = 0 + while i < len(glob): + c = glob[i] + if c == "*": + if glob.startswith("**", i): + if glob.startswith("**/", i): + out.append("(?:.*/)?") + i += 3 + continue + out.append(".*") + i += 2 + continue + out.append("[^/]*") + elif c == "?": + out.append("[^/]") + elif c == "[": + end = glob.find("]", i + 1) + if end == -1: + out.append(re.escape(c)) + else: + cls = glob[i + 1 : end] + if cls.startswith("!"): + cls = "^" + cls[1:] + out.append("[" + cls + "]") + i = end + 1 + continue + else: + out.append(re.escape(c)) + i += 1 + return re.compile("^" + "".join(out) + "$") + + +def collect_globs(node: dict, path: str = "def") -> list[tuple[str, str]]: + """Every glob in the section tree as ``(section path, glob)``. + + A section's ``ignore`` list counts as coverage too: forkdiff still lists + those files under the section (grayed out), so they are described. + """ + found: list[tuple[str, str]] = [] + title = node.get("title") or "(untitled)" + here = f"{path} › {title}" if path != "def" else title + for g in node.get("globs") or []: + found.append((here, str(g))) + for g in node.get("ignore") or []: + found.append((here, str(g))) + for child in node.get("sub") or []: + found.extend(collect_globs(child, here)) + return found + + +def git(*args: str, cwd: Path) -> str: + result = subprocess.run( + ["git", *args], cwd=cwd, capture_output=True, text=True, check=False + ) + if result.returncode != 0: + raise RuntimeError(f"git {' '.join(args)} failed: {result.stderr.strip()}") + return result.stdout.strip() + + +def changed_paths(repo: Path, base: str, head: str) -> list[str]: + out = git("diff", "--name-only", f"{base}..{head}", cwd=repo) + return [line for line in out.splitlines() if line] + + +def check_coverage( + paths: Iterable[str], globs: list[tuple[str, str]] +) -> tuple[list[str], list[tuple[str, str]], dict[str, int]]: + """Return ``(uncovered paths, stale globs, matches per glob)``.""" + compiled = [(section, g, glob_to_regex(g)) for section, g in globs] + hits: dict[str, int] = {g: 0 for _, g in globs} + uncovered: list[str] = [] + for p in paths: + matched = False + for _, g, rx in compiled: + if rx.match(p): + hits[g] += 1 + matched = True + if not matched: + uncovered.append(p) + stale = [(section, g) for section, g in globs if hits[g] == 0] + return uncovered, stale, hits + + +def check_base(repo: Path, base: str, head: str, upstream_ref: str | None) -> list[str]: + problems: list[str] = [] + if not re.fullmatch(r"[0-9a-f]{40}", base): + problems.append( + f"base.hash must be a full 40-hex commit id, got {base!r} — a short or " + "symbolic ref would silently move under the page." + ) + return problems + try: + git("cat-file", "-e", f"{base}^{{commit}}", cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not present in this repository. The fork must " + "sit on top of it (fetch upstream if the clone is shallow)." + ) + return problems + if upstream_ref is None: + return problems + try: + git("merge-base", "--is-ancestor", base, upstream_ref, cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must " + "name a commit on upstream main, not a fork commit." + ) + merge_base = git("merge-base", head, upstream_ref, cwd=repo) + if merge_base != base: + problems.append( + f"base.hash {base[:12]} != merge-base({head}, {upstream_ref}) = " + f"{merge_base[:12]}. The fork was rebased onto newer upstream; update " + "fork.yaml's base.hash and re-describe the sections (see docs/forkdiff.md)." + ) + return problems + + +def review_status(problems: list[str], detail: str) -> list[dict]: + if not problems: + return [] + return [ + { + "source": "fork diff analysis", + "results": [ + { + "kind": "action_required", + "title": "fork.yaml no longer describes the fork", + "summary": ( + problems[0] + if len(problems) == 1 + else f"{len(problems)} issues: {problems[0]}" + ), + "detail": detail, + "how_to_fix": ( + "See FORKDIFF.md. After an upstream merge: set base.hash " + "to `git merge-base HEAD upstream/main`. For new files: add " + "them to the section that explains them (or to a global " + "`ignore` if they are not code). Then run " + "`python3 scripts/check_forkdiff.py " + "--upstream-ref upstream/main` locally." + ), + } + ], + } + ] + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--repo", default=".", help="path to the fork checkout") + ap.add_argument("--fork", default="fork.yaml", help="fork page definition") + ap.add_argument("--head", default="HEAD", help="the fork revision to describe") + ap.add_argument( + "--upstream-ref", + default=None, + help="a ref holding upstream main (e.g. refs/remotes/upstream/main); " + "enables the merge-base check", + ) + ap.add_argument( + "--review-status-out", default=None, help="write review-status JSON here" + ) + args = ap.parse_args(argv) + + repo = Path(args.repo).resolve() + fork_path = repo / args.fork + spec = yaml.safe_load(fork_path.read_text(encoding="utf-8")) or {} + base = str((spec.get("base") or {}).get("hash") or "").strip() + problems: list[str] = [] + lines: list[str] = [] + + problems += check_base(repo, base, args.head, args.upstream_ref) + + globs = collect_globs(spec.get("def") or {}) + globs += [("(global ignore)", str(g)) for g in spec.get("ignore") or []] + + paths: list[str] = [] + if re.fullmatch(r"[0-9a-f]{40}", base): + try: + paths = changed_paths(repo, base, args.head) + except RuntimeError as exc: + problems.append(str(exc)) + + uncovered, stale, hits = check_coverage(paths, globs) + if uncovered: + problems.append( + f"{len(uncovered)} changed file(s) are not described by any fork.yaml " + "section" + ) + lines.append("Uncovered files (add each to the section that explains it):") + lines += [f" - {p}" for p in uncovered] + if stale: + problems.append(f"{len(stale)} glob(s) match nothing the fork changes") + lines.append("Stale globs (the fork no longer changes anything they name):") + lines += [f" - {g} [{section}]" for section, g in stale] + + covered = len(paths) - len(uncovered) + print( + f"fork.yaml: base {base[:12]} head {args.head} changed files {len(paths)} " + f"described {covered} sections+ignores {len(globs)}" + ) + if args.upstream_ref is None: + print(" (no --upstream-ref: merge-base check skipped)") + for line in lines: + print(line) + for p in problems: + print(f"::error::{p}") + + if args.review_status_out: + Path(args.review_status_out).write_text( + json.dumps(review_status(problems, "\n".join(lines))), encoding="utf-8" + ) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main())
diff --git ml-explore/mlx/.github/workflows/forkdiff-check.yml Layr-Labs/mlx/.github/workflows/forkdiff-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcaef3e0d1aabe4de60db7a9eff80902d3d05af4 --- /dev/null +++ Layr-Labs/mlx/.github/workflows/forkdiff-check.yml @@ -0,0 +1,76 @@ +name: Fork Diff Check + +# Fails a PR whose `fork.yaml` no longer describes this fork. +# +# The fork-diff page (https://layr-labs.github.io/mlx/, rendered by +# protolambda/forkdiff from `fork.yaml`, deployed by forkdiff-pages.yml) is +# only useful while it is true, and two things make it go stale silently: +# +# 1. A rebase onto newer upstream. `base.hash` keeps pointing at the old +# upstream commit, so the page shows upstream's own changes as the fork's. +# `scripts/check_forkdiff.py` requires base.hash == merge-base(HEAD, +# upstream/main); a rebase moves the merge-base and the gate stays red +# until the hash — and the sections — are brought up to date. +# 2. A fork change nobody described. Every file in the base..HEAD diff must +# match a section glob (or a global ignore), and every glob must still +# match something. +# +# The page is also rendered here so a fork.yaml that forkdiff itself rejects +# cannot merge. See FORKDIFF.md. + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + analysis-up-to-date: + name: fork.yaml describes the fork + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # full history: merge-base with upstream, and forkdiff diffs against base.hash + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx.git \ + main:refs/remotes/upstream/main + echo "upstream/main = $(git rev-parse --short refs/remotes/upstream/main)" + echo "merge-base = $(git merge-base HEAD refs/remotes/upstream/main | cut -c1-12)" + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Verify fork.yaml against the real diff + run: | + python3 -m pip install --quiet pyyaml + python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Render the fork-diff page + # fork.yaml names refs/heads/main; on a PR the checkout is a detached + # merge commit, so point the local branch at what we are checking. + run: | + git update-ref refs/heads/main HEAD + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + echo "rendered $(wc -c < tmp/pages/index.html) bytes" + + - name: Upload rendered page + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 7
diff --git ml-explore/mlx/.github/workflows/forkdiff-pages.yml Layr-Labs/mlx/.github/workflows/forkdiff-pages.yml new file mode 100644 index 0000000000000000000000000000000000000000..6777acc29a40ce280cc180b4392005f75c71440c --- /dev/null +++ Layr-Labs/mlx/.github/workflows/forkdiff-pages.yml @@ -0,0 +1,135 @@ +name: Deploy Fork Diff + +# Renders `fork.yaml` with protolambda/forkdiff and publishes the result as the +# repository's GitHub Pages site — the same setup ethereum-optimism/op-geth +# uses for its go-ethereum fork diff. Runs the analysis gate first, so a page +# that lies about the fork is never published. + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: "pages" + cancel-in-progress: true + +jobs: + render: + name: Render fork diff + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # forkdiff diffs against base.hash, deep in history + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx.git \ + main:refs/remotes/upstream/main + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Refuse to publish a stale analysis + run: | + python3 -m venv "$RUNNER_TEMP/forkdiff-venv" + "$RUNNER_TEMP/forkdiff-venv/bin/python" -m pip install --quiet pyyaml + "$RUNNER_TEMP/forkdiff-venv/bin/python" scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Build forkdiff + run: | + # Render this exact checkout on main and on manual branch canaries. + git update-ref refs/heads/main HEAD + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + touch tmp/pages/.nojekyll + + - name: Keep the rendered page as an artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 30 + + deploy: + name: Deploy fork diff + needs: render + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url || steps.deployment-retry.outputs.page_url }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + pages: write + id-token: write + steps: + - name: Is GitHub Pages enabled? + # Pages must be switched on once by a repo admin (Settings → Pages → + # Source: "GitHub Actions"). The workflow token cannot do that itself + # (`configure-pages` enablement needs an admin PAT), so until then the + # page is built and kept as an artifact but not deployed — a notice, + # not a red run. + id: pages + env: + GH_TOKEN: ${{ github.token }} + run: | + if gh api "repos/${GITHUB_REPOSITORY}/pages" --silent 2>/dev/null; then + echo "enabled=true" >> "$GITHUB_OUTPUT" + else + echo "enabled=false" >> "$GITHUB_OUTPUT" + echo "::notice::GitHub Pages is not enabled for ${GITHUB_REPOSITORY}; built the page but skipped the deploy. Enable it once under Settings → Pages (Source: GitHub Actions) and re-run this workflow." + fi + + - name: Setup Pages + if: steps.pages.outputs.enabled == 'true' + uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0 + + - name: Download the rendered page + if: steps.pages.outputs.enabled == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: forkdiff-page + path: tmp/pages + + - name: Prepare the static page + if: steps.pages.outputs.enabled == 'true' + run: touch tmp/pages/.nojekyll + + - name: Upload Pages artifact + if: steps.pages.outputs.enabled == 'true' + uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0 + with: + path: tmp/pages + + # deploy-pages looks the github-pages artifact up in this run's artifact + # list as soon as it starts, and that list can lag the upload above: the + # first try then fails with "No artifacts named github-pages were found" + # (seen on 2026-11-14). Only when the first try failed before it created a + # deployment (no page_url), wait and try once more. + - name: Deploy to GitHub Pages + if: steps.pages.outputs.enabled == 'true' + id: deployment + continue-on-error: true + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5 + + - name: Wait before the second try + if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == '' + run: sleep 20 + + - name: Deploy to GitHub Pages (second try) + if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == '' + id: deployment-retry + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5
diff --git ml-explore/mlx/fork.yaml Layr-Labs/mlx/fork.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e245c8cbfbe83a36c3c873537c99c199f79b523 --- /dev/null +++ Layr-Labs/mlx/fork.yaml @@ -0,0 +1,896 @@ +title: "Layr-Labs/mlx - MLX fork diff overview" +footer: | + Fork-diff overview of [`Layr-Labs/mlx`](https://github.com/Layr-Labs/mlx), a fork of + [`ml-explore/mlx`](https://github.com/ml-explore/mlx) &middot; created with + [Forkdiff](https://github.com/protolambda/forkdiff) +base: + name: ml-explore/mlx + url: https://github.com/ml-explore/mlx + # The upstream commit this fork is based on: upstream main on 2026-10-23, the + # head that the fork merged on that date. CI (`scripts/check_forkdiff.py`) + # requires this hash to equal `git merge-base HEAD upstream/main`. Each upstream + # merge moves the merge-base, so the gate fails until this hash and the + # sections below are brought up to date. + hash: afc03c51105a8e25e70fa2ba0befb214e4f5ec6f +fork: + name: Layr-Labs/mlx + url: https://github.com/Layr-Labs/mlx + ref: refs/heads/main +def: + title: "Layr-Labs/mlx" + description: | + This is an overview of the changes in [`Layr-Labs/mlx`](https://github.com/Layr-Labs/mlx), + a fork of [`ml-explore/mlx`](https://github.com/ml-explore/mlx). + + The fork is the core of Layr-Labs' Apple-silicon inference stack — `mlx` → `mlx-c` → + `mlx-swift` → `mlx-swift-lm` — and carries the kernel, allocator and Metal-runtime work + that serving production MoE models (Gemma 4, Qwen 3.5/3.6, GPT-OSS) needed before or + beyond what upstream ships: sorted expert-tile quantized matmul routes, a masked-tail + MXFP4 decode kernel, FP32-safe SDPA partials, coherent allocator accounting for admission + control, declared-mutable custom-kernel inputs for paged KV, and a use-after-free fix in + Metal eval. Every change is meant to be additive and rebasable; each is gated by shape, + device or environment checks so the upstream path stays the default elsewhere. + + The fork also changes JACCL, the RDMA-over-Thunderbolt backend that runs one model across + two Macs: it zeroes the unused tail of every send frame, and a progress guard fails a call + that gets no completion, closes its group and by default releases the GPU memory and exits + the process with status 75. These two are not gated. The zeroing is always on, and the + guard is on with a 30 s limit that `JACCL_PROGRESS_TIMEOUT_MS=0` removes; + `JACCL_TIMEOUT_ACTION=throw` keeps the process alive and throws instead. + sub: + - title: "Metal eval: use-after-free with mid-eval synchronization" + description: | + `gpu::eval` captured the `MTL::CommandBuffer*` before `eval_gpu` ran and attached the + input-buffer liveness handler to it afterwards. Any primitive that calls + `CommandEncoder::synchronize()` mid-eval — the expert-tile route's sortedness-retract + check does — commits and replaces the encoder's buffer, so the handler landed on a + dangling pointer (latent on Gemma E=128, a deterministic SIGSEGV on Qwen E=256). The + buffer is now fetched from the encoder *after* `eval_gpu`, so inputs outlive exactly the + tail of the primitive's work. (PR #5) + globs: + - "mlx/backend/metal/eval.cpp" + - title: "Sorted expert-tile quantized matmul (Gemma 4 E=128, Qwen 3.5/3.6 E=256)" + description: | + An opt-in route (`MLX_GATHER_QMM_EXPERT_SLICES=1|trust`) for gathered, affine-quantized + MoE expert matmuls: a descriptor kernel builds sorted expert tiles on device (one + instantiation per expert count) and a single expert-count-agnostic tile kernel consumes + them. `classify_gemma4_expert_qmm` is a pure route table admitting exactly the shapes + the kernel is built for; availability is all-or-nothing on a source-matched metallib so + an older library fails the route closed; `trust` skips the descriptor-retract readback + when the caller guarantees sorted indices. A retracted call runs the unsorted gather + route, because the sorted `gather_qmm_rhs` kernels read per-expert offsets and give a + correct result only for sorted indices (PR #27). Diagnostics counters + (`mlx_metal_gemma4_expert_qmm_diagnostics_*`) are exposed through a C ABI so mlx-c / + mlx-swift can arm, snapshot and reset them. + globs: + - "mlx/backend/common/gemma4_expert_qmm.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/kernels/quantized.h" + - "mlx/backend/metal/kernels/quantized.metal" + - "mlx/backend/metal/quantized.cpp" + - "tests/gpu_tests.cpp" + - title: "Thread-scoped command-buffer commit limits" + description: | + `mlx_metal_set_thread_command_buffer_limits(max_ops, max_mb, ...)` overrides, for the + calling thread only, when its command buffers commit: after `max_ops` operations or + `max_mb` megabytes of distinct inputs instead of the device defaults (zero keeps a + default; the previous values are returned for restoring). Evaluation encodes on the + thread that calls `eval`/`async_eval`, so a caller can give single-token decode steps + larger buffers (the CPU encodes further ahead of the GPU) while prefill keeps the + defaults and their memory bound. The Ultra defaults (50 ops / 50 MB) count weight + inputs, so multi-GB expert banks commit after almost every MoE operation. + Partitioning work into command buffers does not change results. + globs: + - "mlx/backend/common/command_buffer_limits.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - title: "Steel affine quantized matmul: prompt-sized output tiles" + description: | + On a GPU without neural accelerators the steel `affine_qmm_t` kernel computed every + product in 32 x 32 output tiles (2 x 2 fragments a SIMD group). A product of at least + 256 rows with a 64-aligned output width now takes a 64-row x 32-column tile for 16-bit + inputs and a 32 x 64 tile for FP32 inputs by default (measured on the M3 Ultra at 512 + rows: BF16 products 4-6% faster; FP32's 64 x 64 tile was slower), JIT-instantiated from + the same `qmm_t_impl`. Every output element still accumulates the same 8-wide K slabs + in the same order with the same simdgroup multiply-accumulates over the same + dequantized values, so no bit changes; the split-K decision (made from 32 x 32 tiles) + and the NAX route are unchanged. + `MLX_QMM_STEEL_TILE` picks 32 (as before), 64, 6432, 3264 or 6464 (64 x 64 with K depth + 64 for 16-bit inputs in groups of 64 or more; FP32 tiles that deep would exceed 32 KiB of + threadgroup memory); `MLX_QMM_STEEL_TILE_MIN_GROUPS` keeps 32 x 32 below a 64 x 64 + threadgroup count; `mlx_metal_set_thread_qmm_steel_tile` overrides the tile for the + calling thread (tests and benches compare the tiles' bytes in one process). Both + variables are documented in `docs/src/usage/environment_variables.rst`. + Only builds that compile kernels at run time take these tiles: the precompiled + library instantiates `affine_qmm_t` at 32 x 32 only, so CMake builds with the default + `MLX_METAL_JIT=OFF` keep 32 x 32 (`kernels_jit_compiled()`, defined by + `jit_kernels.cpp` and `nojit_kernels.cpp`). `tests/quantized_tile_tests.cpp` runs + 512 x 1024 products (one qmm, no split-K) at K = 96 (no NAX route) and K = 192 in + groups of 64 at every tile, checks the 32 x 32 result against the dequantized + product, and every other tile against its bytes. A wide tile passes upstream's + template arguments in order (global scale, then BM, BK, BN); upstream's own 64 x 64 + FP4 tile (half-loader `fp_qmm_t`, precompiled) keeps its name and its selection. + globs: + - "mlx/backend/common/command_buffer_limits.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/quantized.cpp" + - "mlx/backend/metal/kernels.h" + - "mlx/backend/metal/jit_kernels.cpp" + - "mlx/backend/metal/nojit_kernels.cpp" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" + - "tests/quantized_tile_tests.cpp" + - title: "Batch-invariant quantized matmul rows (opt-in)" + description: | + Opt-in (`MLX_QMV_BATCH_INVARIANT=1`, read once in each process). A quantized `x @ w.T` + with fewer rows than the vector limit (`get_qmv_batch_limit`) then runs only the vector + kernels, as upstream did before two of its routes: `qmv` for one row, and `qmv_wide` + from two rows (`qmv` where `qmv_wide` does not serve the mode on the GPU). These + routes do not run below the limit: `qmv_mma`/`qmv_nax` for 6 to 16 rows of the + floating-point modes ([ml-explore/mlx#4712](https://github.com/ml-explore/mlx/pull/4712)) + and the staged NAX split-K kernel for affine products from 8 rows + ([ml-explore/mlx#4682](https://github.com/ml-explore/mlx/pull/4682)). Each row then has + the same bits at each row count from 2 to the limit - 1, so the rows of several + requests in one launch (for example their speculative verify windows) get the bits + that each request gets alone. A row alone (`qmv`) can have other bits than the same + row among two or more rows, as before. From the limit on, and without the switch, + the routes do not change. `tests/qmv_batch_invariant_tests.cpp` compares each window + of rows with the same rows in a larger launch at GLM and Qwen tensor-parallel shapes, + for affine and NVFP4 weights with bfloat16 and float32 inputs. The tests binary runs + it without the switch (up to 5 rows), and the `qmv_batch_invariant` ctest entry, which + Fork Tests runs, runs it with the switch (every count below the limit). + globs: + - "mlx/utils.h" + - "mlx/backend/metal/quantized.cpp" + - "docs/src/usage/environment_variables.rst" + - "tests/qmv_batch_invariant_tests.cpp" + - "tests/CMakeLists.txt" + - ".github/workflows/fork-tests.yml" + - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" + description: | + GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's + 512-element alignment and fell to the general path. `fp_gather_qmv_fast_tail` runs five + full blocks plus a 320-value tail read only by the participating lanes, preserving FP32 + accumulation and the gathered indices/strides. It is enabled automatically only on the + physical M4 Max architecture (`applegpu_g16s`) for the exact MXFP4/group-32/4-bit, + E=32, K=2880, N=2880|5760, FP32/BF16 shape; `MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL=0` + restores the original route and `MLX_GPTOSS_MXFP4_PREFILL_TILE=m32n32k32` opts into a + separately measured prefill tile (`gptoss_mxfp4_policy.h`). (PR #14) + `fp_quantized.metal` also builds the two m32n32k32 prefill-tile kernels (float and + bfloat16) ahead of time, so CMake builds with the default `MLX_METAL_JIT=OFF` can load + them. (PR #24) + globs: + - "mlx/backend/metal/gptoss_mxfp4_policy.h" + - "mlx/backend/metal/kernels/fp_quantized.h" + - "mlx/backend/metal/kernels/fp_quantized.metal" + - "mlx/backend/metal/quantized.cpp" + - "tests/gptoss_mxfp4_tests.cpp" + - "tests/CMakeLists.txt" + - title: "Coherent allocator accounting for admission control" + description: | + Admission accounting used to combine independent reads of the allocator counters with + logical buffer sizes, so concurrent allocator activity could produce an incoherent + snapshot and alignment / cache reuse could make the real backing larger than the + request. `get_memory_snapshot()` reads active / cache / peak under one lock; + `get_allocation_size_upper_bound()` and the detached, lock-free + `AllocationFootprintPolicy` bound a buffer including alignment and the (now inclusive, + overflow-checked) cache-reuse limit shared with `BufferCache`. Metal, CPU and CUDA + allocators implement the same interface; the allocator's own behaviour stays the + authority. These describe allocator accounting, not process RSS. (PR #15) + The public process-allocation cap API adds install-once Metal backing enforcement. + Reservations include pending allocations and the fixed heap. Owned page-aligned VM + regions use Metal no-copy buffers; credit returns after the deallocator unmaps them. + Foreign wrappers retain caller ownership. CPU/CUDA reject this optional API; soft + memory limits are unchanged. Residency insertion rolls back failed registration before + callers release buffers, including ordinary uncapped allocations. Standalone CPU and + real-Metal tests cover delayed release, churn, and injected construction failures. + `tests/CMakeLists.txt` builds them as their own executables, because the cap is + install-once in each process, and gives one ctest entry to each case of the Metal test. + The Metal test uses `allocator().malloc` / `allocator().free`, which return and free a + plain `Buffer`, because upstream #4634 made `allocator::malloc` return an owning `Data`. + The allocator makes no fixed heap on a virtual GPU (the GitHub-hosted runner), so the + cases check the heap charge and heap use that match the device. The registration cases + fill one residency set with a page first, so that the injected failure of a new set is + reached with or without the heap in set 0. + When the device has no residency sets (`ResidencySets::enabled()` is false: no Metal 3 + GPU family or macOS before 15, as on the virtual GPU of the hosted runner), the path + these cases test does not exist. They then print the reason and exit with 77, which + ctest reports as skipped (`SKIP_RETURN_CODE`). David ruled on 2026-10-24 to skip by + capability, like the 4 GiB capability skip below. + Capped no-copy pages are first touched on the CPU so process physical + footprint accounts for pages later written by the GPU. + The native footprint contract is documented in `docs/src/usage/unified_memory.rst`. + globs: + - "mlx/memory.h" + - "mlx/backend/common/allocation_footprint.h" + - "mlx/backend/common/process_allocation_cap.h" + - "tests/standalone/process_allocation_cap*.cpp" + - "tests/CMakeLists.txt" + - "mlx/backend/common/buffer_cache.h" + - "mlx/backend/metal/allocator.h" + - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/metal/resident.cpp" + - "mlx/backend/cuda/allocator.h" + - "mlx/backend/cuda/allocator.cpp" + - "mlx/backend/no_gpu/allocator.cpp" + - "tests/allocator_tests.cpp" + - "docs/src/usage/unified_memory.rst" + - title: "FP32 partial sums in two-pass vector SDPA" + description: | + The two-pass vector SDPA cast unnormalized partial sums to the input dtype before + combining them: BF16 lost cancellation residuals and FP16 could overflow even when the + final output was representable. Partials now stay FP32 through the second pass and only + the final result is cast; kernel entry names change so a stale shader cannot silently + satisfy the new buffer contract. Python regressions cover cancellation and overflow + across D64/D128/D256, 32/128 partitions, masked and unmasked. (PR #16) + globs: + - "mlx/backend/metal/kernels/sdpa_vector.h" + - "mlx/backend/metal/kernels/scaled_dot_product_attention.metal" + - "mlx/backend/metal/scaled_dot_product_attention.cpp" + - "python/tests/test_fast_sdpa.py" + - title: "Declared-mutable inputs for Metal custom kernels" + description: | + `metal_kernel_with_mutable_inputs` lets a caller declare which custom-kernel inputs will + be written, so paged-KV consumers keep writes on the original allocation and Metal sees + the read/write hazard. Mutable names must identify exactly one input; mutable `device` + pointers are generated (including for small/scalar storage) and take part in the + compiled-kernel identity; an implicit contiguous copy of declared-mutable storage is + rejected; allocations are registered for writes as well as reads. A separate + `MutableInputCustomKernel` primitive serializes the declaration while the existing + `CustomKernel` export schema is untouched. (PR #18) + globs: + - "mlx/fast.h" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/export.cpp" + - title: "Cross-thread compile-cache cleanup" + description: | + Compile caches became thread-local upstream; bindings built before that (the mlx-c / + mlx-swift consumers) still call the process-wide `compile_erase` / `compile_clear_cache`. + A process-lifetime registry records each thread's cache once at construction so those + entrypoints can erase or clear every live cache, with no per-call hot-path work. (PR #10) + globs: + - "mlx/compile.cpp" + - "mlx/compile_impl.h" + - "tests/compile_tests.cpp" + - title: "Freed compiled closures leave every thread cache" + description: | + `compile(std::function)` keys a closure by the address of a heap copy of it. Upstream, + the deleter of that copy erases the key only from the cache of the thread that called + `compile()`. Each call records its trace in the cache of the calling thread, so a trace + from another thread stayed after the copy was freed. The trace kept its arrays alive, + and a later closure at the same address could replay it. The deleter now erases the key + from every live thread cache through the registry above, before the delete. The test + `test freeing a compiled closure erases every thread cache` records a trace on a second + thread, frees the closure, and checks that the captured array is uniquely referenced. + (PR #43) + globs: + - "mlx/compile.cpp" + - "tests/compile_tests.cpp" + - title: "Freed Python compiled functions leave every thread cache" + description: | + The Python binding keys the traces of `mx.compile(fun)` by the address of `fun`. Upstream, + `PyCompiledFun` keeps the cache of the thread that called it last, and its destructor + erases the key only from that cache. Each call records its trace in the cache of the + calling thread, so a trace from another thread stayed after the free. The trace kept its + arrays alive, and a later compile of a callable at the same address replayed it without a + new trace. The destructor now erases the key from every live thread cache through the + registry above, before it releases `fun`, and `PyCompiledFun` no longer keeps a cache. + The test `test_compile_free_erases_every_thread_cache` calls a compiled function on two + threads, frees it on the thread that called it last, and compiles the same callable + again on the other thread. It expects a new trace there. (PR #44) + globs: + - "python/src/transforms.cpp" + - "python/tests/test_compile.py" + - title: "Integer floor_divide tests" + description: | + The fork keeps its regression tests for integer `floor_divide` from PR #32. Upstream + now does the fix itself: ml-explore/mlx #4515 fixes `floor_divide` in `ops.cpp` and + #4642 adds a `FloorDivide` primitive that rounds down. The fork dropped its own flooring `Divide` functors when it merged + upstream on 2026-10-22, so integer `Divide` truncates again, as in upstream. The tests + check negative operands of every signed integer type, the SIMD and scalar paths, + unsigned and floating-point division, and compiled graphs. On the CPU they also check + that `x // 0` gives 0 and `min // -1` gives the minimum value. Upstream's CPU + `floor_divide` divided `min` by -1, which overflows and traps on x86 (SIGFPE). The + fork divides by 1 there, as PR #32 did, so the result wraps to `min`. + globs: + - "mlx/backend/cpu/simd/base_simd.h" + - "mlx/backend/cpu/simd/accelerate_simd.h" + - "tests/ops_tests.cpp" + - "python/tests/test_ops.py" + - title: "Validated custom Metal threadgroups and bounded compiler retry" + description: | + Custom kernels refuse invalid axes, counts beyond UINT32_MAX and axes beyond + the device limits before allocating outputs. A nonempty grid with complete + x-axis multiples of the group width and groups (512,1,1) or (1024,1,1) may retry an insufficient + pipeline with max_total_threads_per_threadgroup(requestedWidth) on its unique generated + declaration. The original capable pipeline is retained; retry compilation + and the selected pipeline's actual capacity remain authoritative. Other + geometries refuse without clamping. Shader math and dispatch axes do not change. + globs: + - "python/tests/test_metal_threadgroup_bounds.py" + - "docs/src/dev/custom_metal_kernels.rst" + - title: "JACCL: zeroed send-frame tails, a progress guard and the advertised GID" + description: | + JACCL is the RDMA-over-Thunderbolt backend. Upstream has changed none of the three + things below. + + Send frames: JACCL posts every frame at the full size of its scratch buffer, so a + payload shorter than the buffer went to the peer followed by the bytes of earlier + sends. `stage_send_frame` (`send_frame.h`) copies the payload and zeroes the rest of + the frame, and every mesh and ring send path stages through + `SharedBuffer::stage_send`. The posted sizes and the receive paths are unchanged. + + Progress guard: the polling loops waited for completions without a limit and never + read `wc.status`, so a rank whose peer had died spun on a full core until it was + killed, and a failed completion was used as data. `ProgressGuard` + (`progress_guard.h`) is called after every poll of every mesh and ring loop. A + completion with a failure status, or a failed `ibv_poll_cq`, is an error at once; no + completion for longer than `JACCL_PROGRESS_TIMEOUT_MS` / + `MLX_JACCL_PROGRESS_TIMEOUT_MS` (default 30000 ms; `0` or a negative value removes + the limit) is an error. The clock is read once per 1024 polls that return nothing, so + the polling fast path gains a counter and no clock read. The failed call first + destroys the group's queue pairs and completion queues and deregisters its buffers; + the ring does so only after all wires have returned. Then, by default + (`JACCL_TIMEOUT_ACTION` / `MLX_JACCL_TIMEOUT_ACTION` = `teardown-exit`), it prints the + reason, runs the memory release hook that MLX's `jaccl.cpp` registers + (`set_wired_limit(0)`, then `clear_cache()`, at most 10 s) and leaves through + `std::_Exit(75)`, a restartable status. With `throw` it throws a `[jaccl]` + `std::runtime_error` instead; every later call on that group throws immediately and + the group cannot be reopened in the process. The ring keeps its own guarded + `dispatch_wires`, which also reports the errors of the ring pool wires that it used + to drop. A mesh with more than one wire (upstream's second cable) has one `MeshImpl`, + and so one guard, for each wire, and the wires of a `MeshGroup` share one failure + flag: a failed wire closes its own queue pairs and buffers, a wire that waits in the + same call stops with `WireStopped` and closes its own, and every later call on the + group is refused. The mesh runs its wires through the + shared `dispatch_wires` in `threadpool.h`, which upstream lets drop the error of a + pool wire; the fork throws that error after all wires returned. A region that the + verbs refuse to deregister is reported and kept for the destructor, as a refused + queue pair or completion queue is. Each completion + queue has four times the entries its queue pair can have outstanding + (`COMPLETION_QUEUE_DEPTH`, used by `mesh.cpp` and `ring.cpp` when they create the + queues). MLX's `jaccl.cpp` registers the release hook each time it wraps a new JACCL + group. + + Startup readiness: a per-group one-shot budget of 1..900000 ms replaces the + idle limit until its fixed monotonic deadline. Progress never renews it. Begin/end + refuse running calls; callers drain queued work and serialize scheduling. End + restores the original idle policy and refuses expired or closed groups. A mesh gives + the budget to each of its wires. The MLX Group API forwards to JACCL only; + unsupported backends refuse without fallback. + + Advertised GID: `Connection::info()` advertises the IPv4-mapped GID of the port, but + `queue_pair_rtr` sent from GID index 1 whatever the index of that GID. The connection + now remembers the index where the advertised GID was found and sends from it; + behaviour is unchanged where that index is 1. + + `tests/jaccl` is a separate CMake project that the MLX build does not build; the + `build-cpp` job of Fork Tests builds it and runs it. It + compiles the real mesh, ring and RDMA headers against simulated verbs and checks the + frame tails, the guard and the release path under ASan, UBSan and TSan. + globs: + - "mlx/distributed/jaccl/jaccl.cpp" + - "mlx/distributed/jaccl/lib/README.md" + - "mlx/distributed/jaccl/lib/jaccl/mesh.cpp" + - "mlx/distributed/jaccl/lib/jaccl/mesh_impl.h" + - "mlx/distributed/jaccl/lib/jaccl/progress_guard.h" + - "mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h" + - "mlx/distributed/jaccl/lib/jaccl/group.h" + - "mlx/distributed/jaccl/lib/jaccl/mesh.h" + - "mlx/distributed/jaccl/lib/jaccl/ring.h" + - "mlx/distributed/distributed.h" + - "mlx/distributed/distributed_impl.h" + - "mlx/distributed/distributed.cpp" + - "mlx/distributed/jaccl/lib/jaccl/rdma.cpp" + - "mlx/distributed/jaccl/lib/jaccl/rdma.h" + - "mlx/distributed/jaccl/lib/jaccl/ring.cpp" + - "mlx/distributed/jaccl/lib/jaccl/ring_impl.h" + - "mlx/distributed/jaccl/lib/jaccl/send_frame.h" + - "mlx/distributed/jaccl/lib/jaccl/threadpool.h" + - "docs/src/usage/distributed.rst" + - "docs/src/usage/environment_variables.rst" + - "tests/jaccl/*" + - "tests/jaccl/fake_verbs/infiniband/verbs.h" + - title: "Two-rank sealed all-sum" + description: | + The embedding program installs an authenticated frame codec for a two-rank + floating-point all-sum. The CPU communication stream seals each partial, + gathers the frames, opens the peer frame and adds in rank order. Missing + codecs and authentication failures refuse evaluation without a plaintext + fallback. The distributed primitive retains its temporary arrays until + the queued work completes. On a two-rank JACCL mesh the sum streams in 256 KiB + pieces, each with its own AES-256-GCM tag, over `MeshImpl::exchange`: a piece is + sent as soon as it is sealed and opened and added as soon as it lands. Other + groups keep the seal-gather-open path. Non-Apple builds use synchronous + piece sealing and opening without Apple dispatch or QoS APIs, preserving + the authenticated wire format and rank-ordered arithmetic. Apple keeps + its existing parallel path. + globs: + - "mlx/distributed/CMakeLists.txt" + - "mlx/distributed/primitives.h" + - "mlx/distributed/sealed.cpp" + - "mlx/distributed/sealed.h" + - "mlx/distributed/sealed_stream.h" + - "tests/distributed_sealed_stream_tests.cpp" + - title: "Fast fence waits order earlier kernels in the same Metal pass" + description: | + An ordinary fast-synchronization GPU fence wait follows both pending + command passes and earlier kernels in the current concurrent encoder. + The in-pass buffer barrier matches the existing fenced-input consumer + path. Without it, a spinning wait can run before a GPU producer needed + by the CPU work it awaits. Arithmetic and command-buffer limits do not + change. A standalone bounded test checks exact GPU-to-CPU-to-GPU chains, + shared side roots, chains where two GPU streams feed the CPU, and request-array + retirement at several buffer sizes. + Fork Tests executes the three CTest processes on its Metal runner and + rejects a missing test registration. This component coverage does not + establish an installed RDMA model fix. + globs: + - "mlx/backend/metal/fence.cpp" + - "tests/metal_fence_chain.cpp" + - "tests/CMakeLists.txt" + - "docs/src/usage/using_streams.rst" + - ".github/workflows/fork-tests.yml" + - title: "GPU streams wait for each other on events" + description: | + With fast synch (`MLX_METAL_FAST_SYNCH=1`) a fence wait on the GPU is a one-thread + kernel that spins until the producer's timestamp arrives. That is safe when the + producer is a CPU stream (a thread always progresses), but not when it is another + GPU stream: Metal does not promise that a second command queue runs while a pass of + the first one spins, so the producing queue can starve and both stop. An eval whose + graph spans two GPU streams therefore waits for the other GPU stream on a shared + event (the non-fast path), while CPU <-> GPU waits keep the fast path. An array read + both by the CPU and by another GPU stream updates both fences, the fast fence first: + its cross-device update can move the array (CUDA moves it to unified memory), and the + event must be recorded after the move. `MLX_EAGER_FENCE_COMMIT` commits after both + updates. Synchronization only: results do not change. + globs: + - "mlx/fence.h" + - "mlx/transforms.cpp" + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/no_gpu/fence.cpp" + - "mlx/backend/cuda/fence.cpp" + - "docs/src/usage/using_streams.rst" + - title: "Helper ops keep the caller's stream" + description: | + `quantized_matmul` cast `x`, `scales` and `biases`, `gather` and `scatter` broadcast + their indices, the gather matmuls cast their indices, and `affine_quantize` selected + its scales on the thread's default stream instead of the stream the caller passed. + mlx-swift passes its own process-wide stream to every op, so each of these helpers + put a second GPU stream into the graph: a 4-bit projection with float32 input and + bfloat16 scales crossed streams twice, and every crossing is a fence wait. They now + use the caller's stream. Where an op runs does not change what it computes. + globs: + - "mlx/ops.cpp" + - "tests/ops_tests.cpp" + - title: "Fused cross-device fence update" + description: | + Opt-in (`MLX_METAL_FUSED_FENCE_UPDATE=1`, fast synch only). A GPU array that the CPU + reads in the same eval is made coherent and its fence timestamp is written in one + dispatch (`fence_update_coherent`) instead of `input_coherent` then `fence_update`. + Every word is still rewritten with system-coherent stores before a system-scope fence. + The last threadgroup to finish writes the timestamp. The fence buffer carries an + arrival count that only increases, so an unfinished earlier dispatch can delay a + timestamp but cannot release it early. Synchronization only: results do not change. + globs: + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/metal/kernels/fence.metal" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" + - title: "Fenced custom-kernel inputs" + description: | + Opt-in (`MLX_METAL_FENCED_INPUTS=1`, fast synch only). `metal_kernel_with_fenced_inputs` + declares inputs that can come from a CPU stream in the same eval, such as a CPU-stream + all-sum. The source calls `MLX_FENCED_INPUT_WAIT(name)` before it reads such an input. + MLX then gives the CPU fence and the value of the update it waits for to the kernel + instead of a `fence_wait` dispatch, and thread 0 of each threadgroup spins on it. The + kernel starts after every pass and kernel encoded before it (`wait_for_all_pending` + and a barrier), as the `fence_wait` pass does, so the CPU work it waits for never + waits for it. MLX keeps the separate wait when the input is copied first, when another + GPU stream feeds the CPU in the same eval, and while exporting. A fenced input is + always in the device address space, never `constant`, because the GPU may load a + small constant buffer before the kernel's wait. The kernel takes its waits before any + argument check can throw, so no wait is left for a later kernel. The declaration is not + part of the exported schema. Synchronization only: results do not change. + + The `fence_wait` dispatch itself makes its pass wait for every pass in flight + (`wait_for_all_pending`), and a buffer barrier orders it after the earlier kernels of + the same pass. Upstream ([ml-explore/mlx#4689](https://github.com/ml-explore/mlx/pull/4689)) + gets the same order with a pass of its own for each wait (`end_encoding()` before the + dispatch, `end_encoding(true)` after it). The fork keeps the wait in the current pass, + so a wait adds no encoder boundary; `end_encoding(true)` stays available and waits as + `wait_for_all_pending` does. Fence waits use the value that the producer's update + returned, as upstream does since + [ml-explore/mlx#4552](https://github.com/ml-explore/mlx/pull/4552). + globs: + - "mlx/fence.h" + - "mlx/transforms.cpp" + - "mlx/fast.h" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/metal/fenced_input.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/no_gpu/fence.cpp" + - "mlx/backend/cuda/fence.cpp" + - "mlx/utils.h" + - "docs/src/usage/environment_variables.rst" + - title: "Cheaper custom-kernel launches and graph bookkeeping" + description: | + Host time only: generated sources, kernel names, buffers and dispatch order do not + change. Custom-kernel primitives share the cached generated source and resolve the + pipeline once per source; repeat launches skip rebuilding the name, template string + and cache key, and bind inputs directly when none needs a contiguous copy. Graph + teardown dedups node inputs with a small vector, `eval_impl`'s per-node map is a flat + open-addressing map, and allocation reads the device's maximum buffer length once. + globs: + - "mlx/array.cpp" + - "mlx/transforms.cpp" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/cuda/custom_kernel.cpp" + - title: "Quantized tile bounds and distinct loader symbols" + description: | + Sorted gathered matrix products use the remaining reduction width for a + partial activation tile. Safe affine and floating-quantized weight loaders + check row and packed-column bounds on both legacy and NAX paths before + reading weights or scales, then + zero invalid lanes. This prevents finite tails from reading the next row, + including a following NaN row. Exact Python regressions cover affine, + MXFP4, MXFP8 and directly packed NVFP4 with FP16 and BF16 inputs. + Each affine/floating-point, legacy/NAX loader has a distinct type name. + Their layouts or bodies differ; sharing a name corrupts MXFP4 results + when the offline Metal linker combines the translation units. The + incompatible affine/FP pack-factor helpers and legacy/NAX vector loaders + also use distinct names. + Aligned dispatch and accumulation precision remain unchanged. + globs: + - "mlx/backend/metal/kernels/quantized.h" + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "python/tests/test_quantized.py" + - title: "CPU quantized accumulation precision" + description: | + Scalar affine, MXFP4, MXFP8 and NVFP4 matrix products accumulate in FP32 + and convert once when writing each output. Both matrix orientations and + the FP group sum preserve partial sums instead of rounding every addition + to BF16 or FP16. Exact CPU regressions compare constant products with + dequantized matmul, including sorted and unsorted gathered affine paths. + Quantization, packing, indexing and Metal kernels remain unchanged. + globs: + - "mlx/backend/cpu/quantized.cpp" + - "python/tests/test_quantized.py" + - title: "Every simdgroup runs the MMA in the sorted gather_qmm NAX kernels" + description: | + The fork reverts one upstream change in two NAX kernels: the simdgroup skip of + [ml-explore/mlx#4352](https://github.com/ml-explore/mlx/pull/4352) (`c7ff35d9`, kept by + [ml-explore/mlx#4572](https://github.com/ml-explore/mlx/pull/4572) as + `sg_active = sgp_sm > 0`). `fp_gather_qmm_rhs_nax` and `affine_gather_qmm_rhs_nax` run + the MMA in every simdgroup. With the skip, mixture-of-experts serving on a two-Mac + JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB wired + until a reboot. Stores stay bounded by `sgp_sm`, so the output does not change. Keep + the revert at every upstream merge. Upstream added the row-tile scheduling of #4567 + and #4572, which the fork had carried as a backport in PR #27, so only this revert + remains. + globs: + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - title: "NAX small-M K-split affine GEMM and double-buffered NVFP4 GEMM/QMV" + description: | + Two M5-series NAX quantized Metal kernel optimizations ported from the Muse + Glimmer 30B challenge line (`Layr-Labs/mlxfast-muse-glimmer-30b-engine` + commits `80b35945` and `9976cc74`): + - `qmm_t_nax_staged_ksplit_impl` in `quantized_nax.h`: when `M <= SM` (`M <= 16`, + reachable at `8 <= M <= 16` on M5+ NAX via `qmm_splitk_nax` and `qmm_nax`) + and `(BM / SM) * 16 == BK` (`BM=64, BK=64, BN=64, WM=4, WN=1`), splits each + `BK` step into 16-column slices across all 4 simdgroups instead of leaving 3 + simdgroups idle, then reduces FP32 partial tiles in simdgroup order in + threadgroup memory (FP32 throughout; changes only K-reduction summation order + for `8 <= M <= 16` affine 16-bit products on NAX). Gated via Metal function + constant `use_ksplit` (index 203) through `use_qmm_nax_ksplit(allow_ksplit)` + (`MLX_NAX_KSPLIT`, opt-in default `0`; disabled when `MLX_QMV_BATCH_INVARIANT=1` + or `allow_ksplit=false` for prefill-row invariance coordination with `#71`). + - `FPQuantizedNAXBlockLoader::fetch_nvfp4` / `store_nvfp4`, double-buffered + `Ws` in `fp_qmm_t_impl` / `fp_qmm_t_nax`, and bit-manipulation + `dequantize_fp4_x4_scaled` + `6 <= M <= 8` (`M <= 8`) peeled 1-ahead prefetch + in `fp_qmv_nax` (`fp_quantized_nax.h`): vectorizes NVFP4 (`bits == 4, + group_size == 16, !has_global_scale`, 16-bit `Ws` storage width `Wtype = bfloat` + across `fp_qmm_t_nax`, `fp_gather_qmm_t_nax`, and `fp_gather_qmm_rhs_nax` for + all activation dtypes, plus 16-bit `fp_qmm_n_nax` when instantiated) weight/scale + loads and `half2` E2M1 dequantization (0-ULP bit-identical to stock over all + 4,096 `(fp8_e4m3, fp4_e2m1)` pairs), guarded by `K > 0`, `K % 32 == 0`, and + 16B `wl` / 2B `scales` alignment checks. + - `tests/nax_quantized_kernel_tests.cpp` logs GPU architecture and NAX status, + covers M5-routed affine K-split (split-K and direct staged, asserting bitwise + prefix parity when K-split is off and bitwise K-split dispatch on NAX when + `MLX_NAX_KSPLIT=1` via the `nax_ksplit_enabled` ctest entry), unbatched/batched + double-buffered NVFP4 GEMM, `6 <= M <= 8` peeled QMV, NVFP4 MoE gather + (`fp_gather_qmm_t_nax` and `fp_gather_qmm_rhs_nax`), and genuinely misaligned + 4B/1B offset fallback bitwise parity. + globs: + - "mlx/utils.h" + - "mlx/backend/metal/kernels.h" + - "mlx/backend/metal/jit_kernels.cpp" + - "mlx/backend/metal/nojit_kernels.cpp" + - "mlx/backend/metal/quantized.cpp" + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "docs/src/usage/environment_variables.rst" + - "tests/nax_quantized_kernel_tests.cpp" + - "tests/CMakeLists.txt" + - ".github/workflows/fork-tests.yml" + - title: "Run-time template of the head-dim split NAX attention" + description: | + Upstream's head-dim split attention (`attention_nax_dsplit`, the NAX full-attention + kernel for head dims 256 and 512) has no BV template parameter: its value width is + BD. The precompiled instances (`instantiate_attn_dsplit`) leave BV out, but the + run-time (JIT) build passed the template arguments of `attention_nax`, BV included, + so every value after BD moved one parameter to the left and the source did not + compile ("Unable to build metal library from source"). A JIT build (mlx-swift + builds this way) therefore failed every head-dim 256 or 512 prefill that takes the + NAX full-attention kernel. `get_steel_attention_nax_kernel` now leaves BV out for + the split kernel. Builds with the precompiled library did not have the bug, and the + kernel names do not change. + globs: + - "mlx/backend/metal/jit_kernels.cpp" + - title: "64-bit products in the JACCL ring and the vector SDPA layout check" + description: | + The JACCL ring computes each wire's byte offset as `lr * n_wires * size`. Upstream + multiplies `lr` and `n_wires` as `int` before the product widens to 64 bits, and + compares `size_ * 2 * n_conns_` as `int`. The fork widens the first operand to + `int64_t`, so each product is computed in 64 bits. The values are small, so the result + does not change. The vector SDPA path checks a query layout with + `strides[2] == shape[3] * shape[bidx]`, where the product is `int` and the stride is + 64-bit. The fork widens `shape[3]` to `int64_t` there too. These changes close the CodeQL + alerts `cpp/integer-multiplication-cast-to-long` in these files. + globs: + - "mlx/distributed/jaccl/lib/jaccl/ring_impl.h" + - "mlx/distributed/jaccl/lib/jaccl/ring.cpp" + - "mlx/backend/metal/scaled_dot_product_attention.cpp" + - title: "CPU reductions of empty arrays" + description: | + An empty-input CPU reduction fills its output with the operation's identity + before planning a reduction. A 4 GiB output previously reached a strided + reduction whose 32-bit loop counter wrapped to zero and wrote past the buffer. + The existing large-output regression and empty-array identity tests cover this. + globs: + - "mlx/backend/cpu/reduce.cpp" + - title: "CPU qqmm refuses a global scale" + description: | + The CPU `QQMatmul` kernel has no global scale input. Upstream passes the scales to it, + and the kernel ignores them, so `qqmm` with `global_scale_x` and `global_scale_w` on + a CPU stream returns a wrong result with no error (upstream marks this as a TODO in + `test_quantized.py`). The fork's CPU test pass found it: the error was about 1000 + against a tolerance of 1e-3. `qqmm` now raises "Global scale is only supported on the + GPU" on a stream that is not a GPU stream, as `gather_qmm` already does. + globs: + - "mlx/ops.cpp" + - title: "CPU BLAS gemm clears C when beta is 0" + description: | + The CPU backend calls BLAS gemm with beta = 0 in five places: the float32, float64 + and complex64 `matmul` wrappers in `gemms/cblas.cpp` (used by `Matmul`, `AddMM` + and `SegmentedMM`), `BlockMaskedMM` and `GatherMM` in `masked_mm.cpp`, and the two + explicit-gemm convolutions in `conv.cpp`. BLAS must not read C when beta is 0, but + Accelerate can (seen with M = 1). An output buffer from the allocator cache can + hold old data, for example packed fp4 weights that read as NaN, and NaN * 0 is NaN. + Upstream's `test_fp_gather_qmm_non_multiple_of_32` found it in the fork's CPU test + pass: its float32 reference `x @ w_sel` reused the 266240-byte buffer of the + previous subtest's packed weights. One helper, `clear_gemm_output` in `gemm.h`, + fills the exact C region of each call (rows by columns, with its `ldc`) with zeros + before the call. MLX's own SIMD gemm already skips C when beta is 0. This is a + latent upstream bug. + globs: + - "mlx/backend/cpu/gemm.h" + - "mlx/backend/cpu/gemms/cblas.cpp" + - "mlx/backend/cpu/masked_mm.cpp" + - "mlx/backend/cpu/conv.cpp" + - title: "Reference uniqueness without buffer ownership" + description: | + Upstream [ml-explore/mlx#4634](https://github.com/ml-explore/mlx/pull/4634) (`5dbe9991`) + makes `is_donatable()` also require that MLX owns the buffer, so the allocator never + reuses a wrapped external buffer. The fork's C API (`mlx_array_get_buffer_info`, field + `unique`) used `is_donatable()` to prove that no other array references a buffer. + Callers in mlx-swift-lm use that proof for paged KV segments, checkpoint memory + accounting and the MTP state, also for wrapped host pages. The fork adds + `array::is_uniquely_referenced()`: the same reference-count test without the ownership + test. `is_donatable()` and buffer donation do not change. + globs: + - "mlx/array.h" + - title: "async_eval does not throw a stream task error" + description: | + Upstream #4338 raises a CPU stream task error from `synchronize`, and its test + expects `async_eval` not to throw. But `StreamThread::enqueue` throws the stored + error on the main thread (#3742). `async_eval` enqueues several tasks: when the + stream thread runs a failing task before `async_eval` enqueues the next one, that + enqueue throws. This is a race. It failed `test_async_eval_error_in_synchronize` + in the fork's CPU test pass on some runs. `async_eval` now holds a + `scheduler::DeferStreamErrors` guard, and `enqueue` does not throw while the guard + lives on the thread. `synchronize` throws the error later. `eval` does not change. + A C++ test stores the error first, so it fails without the fix on every run. + The failing task waits until its completion marker is queued, so the test's + setup cannot consume the error before the `async_eval` assertion. + globs: + - "mlx/scheduler.h" + - "mlx/scheduler.cpp" + - "mlx/transforms.cpp" + - "tests/scheduler_tests.cpp" + - title: "half and bfloat16 floor divide in float32" + description: | + Upstream computes float16 and bfloat16 `floor_divide`, and the `divmod` quotient, as + `floor(a / b)` in the half type. The quotient is rounded to the half type before the + floor, so a true quotient that is less than half an ulp below an integer n rounds + to n, and the result is n instead of n - 1. numpy's float16 divmod computes in + float32 from `fmod` (`npy_divmodf`) and gives n - 1. Upstream's unseeded + `test_divmod` fails for this reason in about 4% of runs per device. The fork now + computes these two operations for float16 and bfloat16 in float32 with the same + method as `npy_divmodf` (`mod = fmod(a, b)`, `div = (a - mod) / b`, then a floor + with the sign correction), and rounds the result once to the output type: in the + Metal `FloorDivide` (which `DivMod` uses), in the CPU scalar and SIMD + `floor_divide`, and in the CPU `DivMod`. float32, float64 and integer paths do not + change. `test_floor_divide_half_rounding_window` uses pairs in the rounding window + and compares with numpy on the CPU and the GPU. The CUDA kernels do not change; no + workflow in this fork builds CUDA. + globs: + - "mlx/backend/metal/kernels/binary_ops.h" + - "mlx/backend/cpu/simd/base_simd.h" + - "mlx/backend/cpu/simd/accelerate_simd.h" + - "mlx/backend/cpu/binary.cpp" + - title: "Seeded Python tests" + description: | + Upstream Python tests draw their random input from unseeded `mx.random` and + `np.random`, so each run tests other input. Some tests compare with a reference under + a fixed tolerance that some inputs exceed: `test_double.test_gemm` (float32 8x8 + matmul against float64, `allclose` rtol 1e-5, atol 1e-8) fails when an element of the + product is near zero, because the float32 rounding of partial sums of order 1 is + about 1e-7 and the tolerance there is about 1e-8 + 1e-5 * |y|. It failed for 152 of + 2000 seeds on the CPU. `test_ops.test_scans` (bfloat16 cumsum against a tri-matrix + sum, rtol 0.02) failed for 4 of 100 seeds on the GPU and 2 of 100 on the CPU. The + CPU float32 and float64 gemm paths both clear C (section "CPU BLAS gemm clears C when + beta is 0"), so the gemm failures are tolerance, not a stale output. `MLXTestCase.setUp` + now seeds both generators with 0 before each test, so each test draws the same input + in every run; seed 0 passes both tests. Tests that seed their own generators still + do. The seed search ran in PR #46 (first commit). + globs: + - "python/tests/mlx_tests.py" + - title: "Fork tooling" + description: | + The fork deletes the upstream workflows that cannot run here: the PyPI release build, + the documentation deploy and the daily bypass-list update with its two scripts. + `build_and_test.yml` keeps the lint, sanitizer and Fedora jobs. The fork deletes the + jobs that run only in the upstream repository, and the composite actions that only + the deleted workflows and jobs used. An upstream merge adds these files again, so + delete them again at each merge. + + The gate that keeps this page honest: `check_forkdiff.py` fails CI when `base.hash` is + not the merge-base with upstream, when a file the fork changes is not described by a + section above, or when a section names files the fork no longer changes. + + `fork-tests.yml` builds the fork with Metal and runs its C++ and Python tests on + macOS runners. Two jobs build in parallel. One job builds the Python + wheel. The other job builds the C++ library and tests, and runs the C++ tests with the + GPU and then with the CPU as the default device, and builds and runs the JACCL tests + with simulated verbs (`tests/jaccl`). Then it runs the standalone allocation + cap tests with ctest, one process for each case. The Python tests run in shard jobs: + one set with the GPU as the default device, and one set with the CPU. + `.github/scripts/fork-tests/python-shards.json` gives the shards. + `python_shards.py` fails a job when a test file is in no shard or in two shards, and + the last job fails when a test ran in two shards. The last job also merges the coverage + profiles of all jobs into one report. The `setup` action pins its actions to full + commit SHAs, because the organization blocks actions that are not pinned. The + organization also blocks `hendrikmuhs/ccache-action`, so `setup` installs ccache with + Homebrew and restores the ccache files with `actions/cache`. The macOS setup + also installs pinned Ninja 1.13.2 in its Python environment, so both CMake builds + have their selected generator. Native build jobs fetch the Apple Metal C++ + headers with four bounded attempts, then check the exact size and SHA-256 + before safe ZIP extraction. Both wheel and C++ builds use that verified + directory; CMake also pins the archive hash for other callers. + The `fork-build-cache` + action saves the ccache files. It also keeps a cache of the compiled Metal kernels: the + build jobs put `metal-cache/xcrun` first in `PATH`, and that script gives the kernel + compile and link commands a cache. The key of a kernel is its preprocessed source, + its arguments, the metal compiler version and the SDK build. The ccache key holds + the clang version, and ccache checks the compiler content of each object. + + All eight Mac jobs in `fork-tests.yml` use native macOS ARM64 labels. Each + label names the job's VM size: the `python-cpu` shards ask for 12 vCPUs and + 32 GiB (`darkbloom-macos-arm64-12x32`), the `python-gpu` shards for 4 vCPUs and + 24 GiB, and the other jobs for 4 vCPUs and 16 GiB. + `FORKDIFF.md` (Job sizes) gives the data. Each Mac job runs the report-only + `.github/scripts/ci-resource-sampler.py`, which prints its memory and vCPU + peaks, and `.github/scripts/test-runner-sizes.py` (in Check Lint) fails when a + Mac job names no signed size. They wait for compatible capacity + without a hosted fallback. The Linux lint, ASAN/UBSAN, fork-diff check + and Pages renderer also use native-only labels. The sanitizer jobs use + the qualified compiler image and a tool preflight, retaining their + original test script within a 60-minute cap. The Fedora aarch64 job runs + the same Fedora script natively in the archived Fedora 42 container rootfs + under PRoot (`.github/scripts/fedora-proot/`); the Fedora x86_64 job and + the protected Pages publisher stay on GitHub-hosted runners. + `FORKDIFF.md` describes the qualification and watchdog time bounds. + `AGENTS.md` adds the "Working in our MLX forks" section permitting agent-assisted + contributions in Layr-Labs forks (`56e12b00` on `main`). + `darkbloom-watchdog.yml` remains unchanged; + a rerun keeps these static labels. On a Darkbloom Sandbox that has + no Darkbloom cache, `fork-build-cache` sets `CI_ACTIONS_CACHE=off` and every + cache step is skipped, so that the sandbox does not write GitHub's Actions + cache. The Darkbloom macOS image has Xcode 27.2 on macOS 27. No job selects + an Xcode. Lint uses a Python 3.12 virtual environment and keeps its pre-commit + cache separate by runner architecture. It skips Actions caching when the + sandbox has no Darkbloom cache. + + The native CodeQL workflow remains disabled until the operator switches + from GitHub default setup and enables `CODEQL_NATIVE`. Its read-only ARM + scan uses the pinned CodeQL 2.27.4 bundle and the existing Actions, C/C++ + and Python default query suites. A separate GitHub-hosted job validates + the same run's fingerprinted SARIF before uploading the original category + identities. It checks out and executes no repository source. + + Three Python tests check behavior that exists only in + the Metal backend (Winograd batch tiling, the Winograd switch and the FFT size limit), + so they skip when the default device is not the GPU. Upstream's + `test_init_reduce_large_output` skips only when the default device cannot hold its + 4 GiB output: on the GPU when `max_buffer_length` is less than 4 GiB, on the CPU when + `memory_size` is less than 16 GiB. The hosted `macos-26` runner capped Metal buffers at + 3.5 GiB. The test cannot be smaller: it is the regression test for ml-explore/mlx + #4437, which needs 2^32 output elements (more than one 32-bit grid dimension), and + bool outputs of one byte each give 4 GiB. David ruled on 2026-10-23 to keep this skip + and not to use a larger runner. A Darkbloom Sandbox caps a Metal buffer at half its memory + (12 GiB of the 24 GiB of the GPU shards), and the CPU shards have a `memory_size` of 32 GiB, + so the test runs there on the GPU and on the CPU. When a Python test entry fails, the job prints the end of + its log at once. Upstream tests that run only a GPU path (forced fused SDPA, global-scale + `qqmm` and `gather_qmm`) check on the CPU pass that the documented error is raised. + globs: + - ".github/actionlint.yaml" + - ".github/scripts/fedora-proot/*" + - "CMakeLists.txt" + - ".github/actions/build/action.yml" + - ".github/actions/build-docs/action.yml" + - ".github/actions/build-wheel/action.yml" + - ".github/actions/test-linux/action.yml" + - ".github/actions/test-wheel/action.yml" + - ".github/actions/test-windows/action.yml" + - ".github/workflows/build_and_test.yml" + - ".github/workflows/codeql-native.yml" + - ".github/workflows/documentation.yml" + - ".github/workflows/release.yml" + - ".github/workflows/update_bypass_list.yml" + - ".github/scripts/find-eligible-contributors.js" + - ".github/scripts/codeql_artifacts.py" + - ".github/scripts/codeql_artifacts_test.py" + - ".github/scripts/update-bypass-list.js" + - ".github/scripts/ci-resource-sampler.py" + - ".github/scripts/test-ci-resource-sampler.py" + - ".github/scripts/test-runner-sizes.py" + - "scripts/check_forkdiff.py" + - "AGENTS.md" + - "FORKDIFF.md" + - "docs/ci-codeql-native.md" + - "README.md" + - ".github/actions/setup/action.yml" + - ".github/actions/fork-build-cache/action.yml" + - ".github/scripts/fork-tests/metal-cache/xcrun" + - ".github/scripts/fork-tests/python-shards.json" + - ".github/scripts/fork-tests/python_shards.py" + - ".github/scripts/fork-tests/metal_cpp.py" + - ".github/scripts/fork-tests/test_metal_cpp.py" + - ".github/workflows/fork-tests.yml" + - ".github/workflows/darkbloom-route.yml" + - ".github/workflows/darkbloom-watchdog.yml" + - "python/tests/test_conv.py" + - "python/tests/test_fft.py" + - "python/tests/test_reduce.py" + +# ignored globally, does not count towards line count +ignore: + - "fork.yaml" + - ".github/workflows/forkdiff-check.yml" + - ".github/workflows/forkdiff-pages.yml"