diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 47e35dde0d..3874e136a3 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -124,6 +124,19 @@ Metal 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 diff --git a/fork.yaml b/fork.yaml index 222eefd8dd..40f8fef456 100644 --- a/fork.yaml +++ b/fork.yaml @@ -293,6 +293,13 @@ def: 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; @@ -308,6 +315,13 @@ def: - "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" @@ -318,6 +332,97 @@ def: - "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: "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 diff --git a/mlx/array.cpp b/mlx/array.cpp index cf49a0fe5f..4e2fa92b91 100644 --- a/mlx/array.cpp +++ b/mlx/array.cpp @@ -1,6 +1,7 @@ // Copyright © 2023-2024 Apple Inc. #include #include +#include #include "mlx/array.h" #include "mlx/ops.h" @@ -283,18 +284,50 @@ array::ArrayDesc::~ArrayDesc() { std::vector> 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 input_map; + constexpr size_t linear_max = 32; + // Ids are kept beside the arrays: a moved-out array has no id. + std::vector> distinct; + std::unordered_set 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 @@ array::ArrayDesc::~ArrayDesc() { 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 a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index f253f599aa..b656d33dc5 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -2,7 +2,12 @@ #include #include +#include +#include #include +#include + +#include #include "mlx/backend/common/compiled.h" #include "mlx/backend/metal/metal.h" @@ -50,6 +55,52 @@ Stream resolve_metal_kernel_stream(StreamOrDevice s) { 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_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, @@ -62,10 +113,13 @@ std::string write_signature( const std::vector& attributes, const std::vector>& shape_infos, bool atomic_outputs, - const std::vector& mutable_inputs) { + const std::vector& mutable_inputs, + const char* fence_preamble, + const std::vector& 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()) { @@ -102,10 +156,15 @@ std::string write_signature( 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 = !is_mutable && arr.size() < max_constant_array_size - ? "constant" - : "device"; + 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; @@ -166,6 +225,14 @@ std::string write_signature( } 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; for (const auto& attr : attributes) { @@ -256,6 +323,30 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( 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& input_names, + const std::vector& output_names, + const std::string& source, + const std::vector& mutable_input_names, + const std::vector& fenced_input_names, + const std::string& header, + bool ensure_row_contiguous, + bool atomic_outputs, + const CompileOptions& compile_options) { std::vector mutable_inputs; for (const auto& mutable_name : mutable_input_names) { auto it = std::find(input_names.begin(), input_names.end(), mutable_name); @@ -271,6 +362,38 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( mutable_inputs.push_back(index); } std::sort(mutable_inputs.begin(), mutable_inputs.end()); + std::vector 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(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."); @@ -308,11 +431,32 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::vector 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 source; + }; + struct SourceCache { + std::mutex mtx; + std::unordered_map> entries; + }; + auto source_cache = std::make_shared(); + return [=, shape_infos = std::move(shape_infos), attributes = std::move(attributes)]( @@ -340,66 +484,133 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( 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(arg.index()); + if (auto* v = std::get_if(&arg)) { + key.append(reinterpret_cast(v), sizeof(int)); + } else if (auto* b = std::get_if(&arg)) { + key += *b ? '1' : '0'; + } else { + key += static_cast(std::get(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. + key += '\0'; for (int i = 0; i < inputs.size(); ++i) { const auto& arr = inputs[i]; - kernel_name += "_"; - kernel_name += get_type_string(arr.dtype()); + key += static_cast(arr.dtype().val()); if (std::find(mutable_inputs.begin(), mutable_inputs.end(), i) != mutable_inputs.end()) { - kernel_name += "m"; + key += arr.ndim() == 0 ? 'z' : 'n'; } else if (arr.ndim() == 0) { - kernel_name += "s"; + 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(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, - mutable_inputs); + std::shared_ptr 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{}); + + 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{}(kernel_source), + compile_options.serialize()); + auto entry = std::make_shared(); + entry->kernel_name = std::move(kernel_name); + entry->source = std::make_shared( + 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; } @@ -409,8 +620,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( output_dtypes, std::make_shared( s, - kernel_name, - kernel_source, + generated->kernel_name, + generated->source, grid, threadgroup, shape_infos, @@ -420,16 +631,17 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( false, 0, compile_options.serialize(), - mutable_inputs), + mutable_inputs, + fenced ? fenced_inputs : std::vector{}), inputs); } return array::make_arrays( - std::move(output_shapes), - std::move(output_dtypes), + output_shapes, + output_dtypes, std::make_shared( s, - std::move(kernel_name), - std::move(kernel_source), + generated->kernel_name, + generated->source, grid, threadgroup, shape_infos, @@ -438,8 +650,10 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::vector{}, false, 0, - compile_options.serialize()), - std::move(inputs)); + compile_options.serialize(), + std::vector{}, + fenced ? fenced_inputs : std::vector{}), + inputs); }; } diff --git a/mlx/backend/cuda/custom_kernel.cpp b/mlx/backend/cuda/custom_kernel.cpp index c230656d80..6fede0dbbc 100644 --- a/mlx/backend/cuda/custom_kernel.cpp +++ b/mlx/backend/cuda/custom_kernel.cpp @@ -310,14 +310,15 @@ void CustomKernel::eval_gpu( // 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{}(source_)); + fmt::format("{}_{:x}", name_, std::hash{}(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); diff --git a/mlx/backend/cuda/fence.cpp b/mlx/backend/cuda/fence.cpp index 1b29044df6..d410b46907 100644 --- a/mlx/backend/cuda/fence.cpp +++ b/mlx/backend/cuda/fence.cpp @@ -41,6 +41,10 @@ void Fence::wait(Stream s, const array&, uint32_t value) { } } +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) { auto& f = cast(); if (cross_device) { diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index 6ae5030267..962ce2951c 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -270,8 +270,10 @@ Buffer MetalAllocator::malloc(size_t size) { 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" diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 3ee8f3d029..8b96fee838 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -2,6 +2,7 @@ #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" @@ -20,6 +21,14 @@ void CustomKernel::eval_gpu( (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 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) { @@ -37,7 +46,8 @@ void CustomKernel::eval_gpu( auto& s = stream(); auto& d = metal::device(s.device); - const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); + // The device limit is fixed: query it once rather than per launch. + static const auto device_max = d.mtl_device()->maxThreadsPerThreadgroup(); if (static_cast(tx) > device_max.width || static_cast(ty) > device_max.height || static_cast(tz) > device_max.depth) { @@ -55,6 +65,17 @@ void CustomKernel::eval_gpu( } } + // 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 copies; for (auto& out : outputs) { @@ -76,27 +97,63 @@ void CustomKernel::eval_gpu( return copies.back(); } }; - std::vector 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 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& checked_inputs = + needs_copy ? copied_inputs : inputs; - std::string lib_name = fmt::format( - "{}_{:x}_{}", name_, std::hash{}(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 max_tg_size = kernel->maxTotalThreadsPerThreadgroup(); + // 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{}(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(pipeline->retain(), [](void* p) { + static_cast(p)->release(); + }); + }); + auto kernel = + static_cast(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); + const auto position = source.find(declaration); if (position != std::string::npos && - source_.find(declaration, position + declaration.size()) == + source.find(declaration, position + declaration.size()) == std::string::npos) { // Keep the dispatch geometry and give the compiler its required size. - auto constrained_source = source_; + auto constrained_source = source; constrained_source.insert( position, "[[max_total_threads_per_threadgroup(" + std::to_string(tg_size) + @@ -152,6 +209,24 @@ void CustomKernel::eval_gpu( compute_encoder.set_output_array(out, index); index++; } + 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(); + } MTL::Size group_dims = MTL::Size(std::min(tx, gx), std::min(ty, gy), std::min(tz, gz)); diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index 22a23db6df..c51489aad1 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -365,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(const_cast(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(a.buffer().ptr()); get_command_encoder()->setBuffer(a_buf, a.offset() + offset, idx); } @@ -393,8 +392,7 @@ void CommandEncoder::register_output_array(const array& a) { 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); } } @@ -413,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 { @@ -484,7 +482,7 @@ void CommandEncoder::end_encoding(bool wait_in_flight) { // 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()); @@ -500,7 +498,8 @@ void CommandEncoder::end_encoding(bool wait_in_flight) { buffer_->addCompletedHandler([this, fence = std::move(fence_), temporaries = std::move(temporaries_), - all_outputs = std::move(all_outputs_), + all_outputs = std::vector( + all_outputs_.begin(), all_outputs_.end()), waiting_on = std::move(waiting_on)]( MTL::CommandBuffer*) mutable { std::lock_guard lk(outputs_mtx_); @@ -516,6 +515,7 @@ void CommandEncoder::end_encoding(bool wait_in_flight) { encoder_->endEncoding(); encoder_.reset(); needs_barrier_ = false; + wait_all_pending_ = false; concurrent_ = false; prev_inputs_.clear(); next_inputs_.clear(); @@ -523,6 +523,7 @@ void CommandEncoder::end_encoding(bool wait_in_flight) { next_outputs_.clear(); concurrent_outputs_.clear(); all_inputs_.clear(); + all_outputs_.clear(); } void CommandEncoder::signal_event(Event event, uint64_t value) { @@ -579,10 +580,13 @@ void CommandEncoder::commit(std::function completion) { [&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())) { @@ -617,6 +621,9 @@ void CommandEncoder::commit(std::function completion) { 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() { diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 929458471f..43275dc619 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -3,11 +3,14 @@ #pragma once #include +#include +#include #include #include #include #include #include +#include #include "mlx/array.h" #include "mlx/backend/common/gemma4_expert_qmm.h" @@ -22,6 +25,139 @@ using MTLFCList = 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 + 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_iterator begin() const { + return items_.begin(); + } + std::vector::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(p); + } + static size_t hash(uintptr_t k) { + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + return static_cast(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 items_; + std::vector slots_; + bool indexed_{false}; +}; + class MLX_API CommandEncoder { public: CommandEncoder(Device& d, int index, ResidencySets& residency_sets); @@ -95,6 +231,15 @@ class MLX_API CommandEncoder { } 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); @@ -106,6 +251,17 @@ class MLX_API CommandEncoder { 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 object) { + retained_.push_back(std::move(object)); + } + private: MTL::ComputeCommandEncoder* get_command_encoder(); @@ -135,19 +291,24 @@ class MLX_API CommandEncoder { NS::SharedPtr encoder_; NS::SharedPtr fence_; bool needs_barrier_{false}; + bool wait_all_pending_{false}; bool concurrent_{false}; std::vector temporaries_; - std::unordered_set prev_inputs_; - std::unordered_set prev_outputs_; - std::unordered_set next_inputs_; - std::unordered_set next_outputs_; - std::unordered_set concurrent_outputs_; - std::unordered_set all_inputs_; - std::unordered_set 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> 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> retained_; }; class MLX_API Device { diff --git a/mlx/backend/metal/eval.cpp b/mlx/backend/metal/eval.cpp index aac9771878..b275e1ca76 100644 --- a/mlx/backend/metal/eval.cpp +++ b/mlx/backend/metal/eval.cpp @@ -44,33 +44,32 @@ void eval(array& arr) { encoder.get_command_buffer(), arr.primitive()); arr.primitive().eval_gpu(arr.inputs(), outputs); } - std::unordered_set> 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()); - } - for (auto& s : arr.siblings()) { - buffers.insert(s.data_shared_ptr()); + if (in.data_shared_ptr().get() != out_data) { + encoder.retain_until_completed(in.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 { - // Fetch the command buffer AFTER eval_gpu: primitives that synchronize - // mid-eval (e.g. the expert-tile route's descriptor retract check) - // commit and REPLACE the encoder's buffer, so a pointer captured before - // eval_gpu would be stale here — attaching the buffer-liveness handler - // to it is a use-after-free. The current buffer holds the tail of this - // primitive's work, which is exactly what the inputs must outlive. - encoder.get_command_buffer()->addCompletedHandler( - [buffers = std::move(buffers)](MTL::CommandBuffer* cbuf) {}); + encoder.commit([s]() { scheduler::notify_task_completion(s); }); } } diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 819e2bb1b2..bf5ae3754e 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -4,13 +4,15 @@ #include #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) : cpu_stream(stream.device == Device::cpu) { auto d = metal::device(stream.device).mtl_device(); if (!d->supportsFamily(MTL::GPUFamilyMetal3)) { use_fast = false; @@ -21,13 +23,18 @@ struct FenceImpl { if (!use_fast) { event = std::make_unique(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 fence; std::unique_ptr event; @@ -40,6 +47,49 @@ struct FenceImpl { } }; +namespace { + +std::vector& given_waits() { + static thread_local std::vector waits; + return waits; +} + +void encode_wait( + Stream stream, + const array& x, + const std::shared_ptr& fence, + uint32_t value) { + auto& f = *static_cast(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(stream); } @@ -63,26 +113,7 @@ void Fence::wait(Stream stream, const array& x, uint32_t value) { 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 +137,36 @@ uint32_t Fence::update(Stream stream, const array& x, bool cross_device) { 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(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 +192,54 @@ uint32_t Fence::update(Stream stream, const array& x, bool cross_device) { 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(fence_.get()); + if (!env::metal_fenced_inputs() || !f.use_fast || !f.cpu_stream || + stream.device != Device::gpu) { + return false; + } + auto kernel = dynamic_cast(&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 take_fenced_inputs(const Primitive* consumer) { + auto& waits = given_waits(); + std::vector 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(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 a/mlx/backend/metal/fenced_input.h b/mlx/backend/metal/fenced_input.h new file mode 100644 index 0000000000..fb3f5e5cbe --- /dev/null +++ b/mlx/backend/metal/fenced_input.h @@ -0,0 +1,32 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include +#include + +#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 fence; + uint32_t count; +}; + +// Remove the waits given to `consumer` and return them. Discard all others. +std::vector 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 diff --git a/mlx/backend/metal/kernels/fence.metal b/mlx/backend/metal/kernels/fence.metal index cd5f9016b9..44e5b29dc0 100644 --- a/mlx/backend/metal/kernels/fence.metal +++ b/mlx/backend/metal/kernels/fence.metal @@ -36,6 +36,55 @@ constexpr constant metal::thread_scope thread_scope_system = 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)]], diff --git a/mlx/backend/no_gpu/fence.cpp b/mlx/backend/no_gpu/fence.cpp index 2e027032d9..48547869b5 100644 --- a/mlx/backend/no_gpu/fence.cpp +++ b/mlx/backend/no_gpu/fence.cpp @@ -22,6 +22,10 @@ void Fence::wait(Stream s, const array&, uint32_t 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) { auto& f = cast(); f.count++; diff --git a/mlx/distributed/CMakeLists.txt b/mlx/distributed/CMakeLists.txt index 807fd0fbdb..dba62b2720 100644 --- a/mlx/distributed/CMakeLists.txt +++ b/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 a/mlx/distributed/distributed.cpp b/mlx/distributed/distributed.cpp index d8fca8b160..98cba6d7ac 100644 --- a/mlx/distributed/distributed.cpp +++ b/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>& diff --git a/mlx/distributed/distributed.h b/mlx/distributed/distributed.h index 0d6e4d41ef..fd312e133a 100644 --- a/mlx/distributed/distributed.h +++ b/mlx/distributed/distributed.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include @@ -61,6 +62,20 @@ struct MLX_API Group { */ 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& raw_group() const { return group_; } diff --git a/mlx/distributed/distributed_impl.h b/mlx/distributed/distributed_impl.h index d889587abc..32ac950a84 100644 --- a/mlx/distributed/distributed_impl.h +++ b/mlx/distributed/distributed_impl.h @@ -21,6 +21,15 @@ class GroupImpl { virtual int size() = 0; virtual std::shared_ptr 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 @@ class GroupImpl { 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& /* ready */, + const std::function& /* arrived */) { + throw std::runtime_error("[distributed] This group cannot exchange."); + } }; /* Define the MLX stream that the communication should happen in. */ diff --git a/mlx/distributed/jaccl/jaccl.cpp b/mlx/distributed/jaccl/jaccl.cpp index e13fc549f5..b18c465d3e 100644 --- a/mlx/distributed/jaccl/jaccl.cpp +++ b/mlx/distributed/jaccl/jaccl.cpp @@ -80,6 +80,27 @@ class JACCLGroup : public GroupImpl { 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& ready, + const std::function& 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(); auto out_ptr = output.data(); diff --git a/mlx/distributed/jaccl/lib/README.md b/mlx/distributed/jaccl/lib/README.md index 92d80c3199..5e2bb9c713 100644 --- a/mlx/distributed/jaccl/lib/README.md +++ b/mlx/distributed/jaccl/lib/README.md @@ -372,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 a/mlx/distributed/jaccl/lib/jaccl/group.h b/mlx/distributed/jaccl/lib/jaccl/group.h index 603765a511..c413287f17 100644 --- a/mlx/distributed/jaccl/lib/jaccl/group.h +++ b/mlx/distributed/jaccl/lib/jaccl/group.h @@ -3,7 +3,10 @@ #pragma once #include +#include +#include #include +#include namespace jaccl { @@ -17,6 +20,13 @@ class Group { 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 @@ class Group { 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& /* ready */, + const std::function& /* arrived */) { + throw std::runtime_error("[jaccl] This group cannot exchange."); + } }; /** diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh.h b/mlx/distributed/jaccl/lib/jaccl/mesh.h index aa19fddb8c..d31da3d977 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh.h @@ -33,6 +33,19 @@ class MeshGroup : public Group { 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; @@ -52,6 +65,20 @@ class MeshGroup : public Group { void barrier() override; + bool supports_exchange() override { + return size_ == 2; + } + + void exchange( + const char* input, + char* output, + size_t n_bytes, + const std::function& ready, + const std::function& arrived) override { + // An exchange runs on the first wire only. + meshes_[0].exchange(input, output, n_bytes, ready, arrived); + } + private: template void all_reduce( diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index 7b62f3e746..aa6ae9e2cd 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -37,6 +37,14 @@ class MeshImpl { 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 void all_reduce(const T* in, T* out, int64_t size, ReduceOp reduce_op) { // Fully connected all reduce with deterministic reduction order. @@ -50,7 +58,11 @@ class MeshImpl { 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(size); int num_peers = size_ - 1; @@ -291,6 +303,90 @@ class MeshImpl { } } + // 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& ready, + const std::function& 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(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(), + length(received)); + received++; + if (recv_posted < frames) { + post_recv(); + } + arrived(size_t(std::min(n_bytes, received * N))); + } + } + post_ready_sends(); + } + } + template void sum_scatter( const T* in, @@ -558,7 +654,7 @@ class MeshImpl { class Call : public ProgressGuard { public: Call(MeshImpl& mesh, const char* op) - : ProgressGuard(op, *mesh.failed_), + : ProgressGuard(op, *mesh.failed_, mesh.wait_budget_.get()), mesh_(mesh), exceptions_(std::uncaught_exceptions()) { require_open(*mesh.failed_); @@ -681,6 +777,8 @@ class MeshImpl { std::span buffers_; std::span scatter_buffers_; std::unique_ptr staging_mem_; + std::unique_ptr wait_budget_ = + std::make_unique(); // 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> failed_ = diff --git a/mlx/distributed/jaccl/lib/jaccl/progress_guard.h b/mlx/distributed/jaccl/lib/jaccl/progress_guard.h index a2009dd972..4a56deb37c 100644 --- a/mlx/distributed/jaccl/lib/jaccl/progress_guard.h +++ b/mlx/distributed/jaccl/lib/jaccl/progress_guard.h @@ -17,6 +17,8 @@ #include #include +#include "jaccl/startup_wait_budget.h" + namespace jaccl { constexpr int64_t DEFAULT_PROGRESS_TIMEOUT_MS = 30000; @@ -186,12 +188,30 @@ inline void require_open(const std::atomic& failed) { * owner of the group closes it and then, unless failure_action() is Throw, * calls teardown_exit(). */ -class ProgressGuard { +template +class BasicProgressGuard { public: - ProgressGuard(const char* op, std::atomic& failed) - : op_(op), failed_(failed), timeout_ms_(progress_timeout_ms()) {} + BasicProgressGuard( + const char* op, + std::atomic& failed, + BasicStartupWaitBudget* 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++) { @@ -221,10 +241,10 @@ class ProgressGuard { if (failed_.load()) { throw WireStopped(); } - if (timeout_ms_ <= 0) { + if (startup_deadline_ || timeout_ms_ <= 0) { return; } - auto now = std::chrono::steady_clock::now(); + auto now = Clock::now(); // The first sample after a completion starts the measurement. if (idle_polls_ == PROGRESS_SAMPLE_POLLS) { idle_since_ = now; @@ -254,8 +274,13 @@ class ProgressGuard { std::atomic& failed_; int64_t timeout_ms_; int64_t idle_polls_{0}; - std::chrono::steady_clock::time_point idle_since_; + typename Clock::time_point idle_since_; + std::optional::Call> call_; + std::optional startup_deadline_; + uint64_t startup_polls_{0}; std::string failure_; }; +using ProgressGuard = BasicProgressGuard<>; + } // namespace jaccl diff --git a/mlx/distributed/jaccl/lib/jaccl/rdma.h b/mlx/distributed/jaccl/lib/jaccl/rdma.h index 2193d8de74..6b719b69c4 100644 --- a/mlx/distributed/jaccl/lib/jaccl/rdma.h +++ b/mlx/distributed/jaccl/lib/jaccl/rdma.h @@ -24,7 +24,7 @@ constexpr int MAX_RECV_WR = 32; // 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 = 8; +constexpr int BUFFER_SIZES = 9; constexpr int NUM_BUFFERS = 2; constexpr int FRAME_SIZE = 4096; diff --git a/mlx/distributed/jaccl/lib/jaccl/ring.h b/mlx/distributed/jaccl/lib/jaccl/ring.h index c901c15a85..56a05153b5 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring.h +++ b/mlx/distributed/jaccl/lib/jaccl/ring.h @@ -34,6 +34,14 @@ class RingGroup : public Group { 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 a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h index b7fb0134cf..604531f828 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h @@ -55,6 +55,14 @@ class RingImpl { 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 { template @@ -373,7 +381,7 @@ class RingImpl { } }; - ProgressGuard guard("ring reduce_scatter", *failed_); + 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. @@ -511,7 +519,8 @@ class RingImpl { }; set_limits(); - ProgressGuard guard("ring all_reduce/all_gather", *failed_); + 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. @@ -649,7 +658,7 @@ class RingImpl { } // Main loop - ProgressGuard guard("ring send", *failed_); + ProgressGuard guard("ring send", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -724,7 +733,7 @@ class RingImpl { } // Main loop - ProgressGuard guard("ring recv", *failed_); + ProgressGuard guard("ring recv", *failed_, wait_budget_.get()); while (in_flight > 0) { // Poll the hardware for completions. // @@ -805,6 +814,7 @@ class RingImpl { // teardown_exit(). template void dispatch_wires(int n_wires, Fn&& fn) { + StartupWaitBudget::Call call(*wait_budget_); require_open(*failed_); auto run = [&](int lw) { @@ -884,6 +894,8 @@ class RingImpl { std::span send_buffers_; std::span recv_buffers_; ThreadPool* pool_; + std::unique_ptr wait_budget_ = + std::make_unique(); std::unique_ptr> failed_ = std::make_unique>(false); }; diff --git a/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h b/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h new file mode 100644 index 0000000000..8b0e0b53ff --- /dev/null +++ b/mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h @@ -0,0 +1,112 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace jaccl { + +constexpr int64_t MAX_STARTUP_WAIT_BUDGET_MS = 900000; + +// Clock injection is local to the type; production uses steady_clock. +template +class BasicStartupWaitBudget { + public: + using TimePoint = typename Clock::time_point; + + void begin(int64_t timeout_ms, const std::atomic& 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 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(Duration::max()) + .count() >= MAX_STARTUP_WAIT_BUDGET_MS); + const auto delta = std::chrono::duration_cast( + 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& failed) { + std::lock_guard 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 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 lock(owner_.mutex_); + --owner_.calls_; + } + + const std::optional& deadline() const { + return deadline_; + } + + private: + BasicStartupWaitBudget& owner_; + std::optional deadline_; + }; + + private: + enum class State { Unused, Active, Ended }; + + void require_idle_open(const std::atomic& 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 deadline_; +}; + +using StartupWaitBudget = BasicStartupWaitBudget<>; + +} // namespace jaccl diff --git a/mlx/distributed/primitives.h b/mlx/distributed/primitives.h index 18a0d65f5f..ea72abce4d 100644 --- a/mlx/distributed/primitives.h +++ b/mlx/distributed/primitives.h @@ -2,8 +2,10 @@ #pragma once +#include #include "mlx/distributed/distributed.h" #include "mlx/distributed/distributed_impl.h" +#include "mlx/distributed/sealed.h" #include "mlx/primitives.h" namespace mlx::core::distributed { @@ -67,6 +69,71 @@ class AllReduce : public DistPrimitive { 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& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& 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& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& 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& inputs, std::vector& outputs) + override; + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + const char* name() const override { + return "SealedAllGather"; + } + + private: + SealCodec codec_; +}; + class AllGather : public DistPrimitive { public: AllGather(Stream stream, Group group) : DistPrimitive(stream, group) {} diff --git a/mlx/distributed/sealed.cpp b/mlx/distributed/sealed.cpp new file mode 100644 index 0000000000..5b09c3d53f --- /dev/null +++ b/mlx/distributed/sealed.cpp @@ -0,0 +1,608 @@ +// Copyright © 2026 Darkbloom. + +#ifdef __APPLE__ +#include +#endif +#include +#include +#include +#include +#include + +#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 installed_codec; +// One counter for every sealed collective, advanced per evaluation; both +// ranks evaluate the same graph in the same order. +std::atomic 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 lock(codec_mutex); + if (codec.seal == nullptr || codec.open == nullptr) { + installed_codec.reset(); + } else { + installed_codec = codec; + } +} + +std::optional seal_codec() { + std::lock_guard lock(codec_mutex); + return installed_codec; +} + +array all_sum_sealed( + const array& x, + std::optional 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(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_, + 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(stream, group, codec), + {x}); +} + +array all_gather_sealed( + const array& x, + std::optional 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(stream, group, codec), + {x}); +} + +namespace { +template +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( + static_cast(rank0[i]) + static_cast(rank1[i])); + } +} +template <> +void add_span( + 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 +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& inputs, + std::vector& 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(), + dst = sealed.data(), + 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(), + mine = in.data(), + theirs = peer.data(), + dst = out.data(), + 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(r0), + reinterpret_cast(r1), + reinterpret_cast(dst), + n / sizeof(float)); + break; + case bfloat16: + add_in_rank_order( + reinterpret_cast(r0), + reinterpret_cast(r1), + reinterpret_cast(dst), + n / sizeof(bfloat16_t)); + break; + case float16: + add_in_rank_order( + reinterpret_cast(r0), + reinterpret_cast(r1), + reinterpret_cast(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; + break; + case bfloat16: + add = detail::add_piece; + break; + case float16: + add = detail::add_piece; + 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(), + dst = out.data(), + mine = sealed.data(), + theirs = received.data()]() { + 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&, std::vector&) { + 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; + case bfloat16: + return detail::add_piece; + case float16: + return detail::add_piece; + 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(), + theirs = received.data()]() { + 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(), 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(), + 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& inputs, + std::vector& 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(); + 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(), + add, + "[reduce_scatter_sealed]"); + } else { + run_gathered( + codec_, + group, + stream(), + in, + out, + half, + send, + mine, + out.data(), + 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&, + std::vector&) { + 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& inputs, + std::vector& 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() + (rank == 0 ? 0 : n); + char* theirs = out.data() + (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(), 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(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); + } else { + run_gathered( + codec_, + group, + stream(), + in, + out, + n, + in.data(), + nullptr, + theirs, + nullptr, + "[all_gather_sealed]"); + } + if (!inputs[0].flags().row_contiguous) { + encoder.add_temporary(in); + } +} + +void SealedAllGather::eval_gpu(const std::vector&, std::vector&) { + throw std::runtime_error( + "[SealedAllGather::eval_gpu] has no GPU implementation."); +} + +} // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed.h b/mlx/distributed/sealed.h new file mode 100644 index 0000000000..655d8d308b --- /dev/null +++ b/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 +#include +#include + +#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 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 = 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 = 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 = std::nullopt, + StreamOrDevice s = {}); + +} // namespace mlx::core::distributed diff --git a/mlx/distributed/sealed_stream.h b/mlx/distributed/sealed_stream.h new file mode 100644 index 0000000000..445613a81c --- /dev/null +++ b/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 +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/distributed/sealed.h" + +namespace mlx::core::distributed::detail { + +using ReadyFn = std::function; +using ArrivedFn = std::function; +// 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(std::numeric_limits::max())) { + throw std::invalid_argument( + std::string(name) + " a sealed frame is longer than 2^31 - 1 bytes"); + } + return static_cast(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(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 +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( + static_cast(mine[i]) + static_cast(out[i])); + } + } else { + for (size_t i = 0; i < n; ++i) { + out[i] = static_cast( + static_cast(out[i]) + static_cast(mine[i])); + } + } +} + +using AddPieceFn = void (*)(int rank, const char* mine, char* out, size_t len); + +template +void add_piece(int rank, const char* mine, char* out, size_t len) { + add_peer_in_rank_order( + rank, + reinterpret_cast(mine), + reinterpret_cast(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[]>(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(k), + static_cast(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(k), + static_cast(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[]> ready_; + std::atomic next_seal_{0}; + std::atomic failed_{false}; +}; + +} // namespace mlx::core::distributed::detail diff --git a/mlx/fast.h b/mlx/fast.h index 8f026c6c48..7d86fe74ba 100644 --- a/mlx/fast.h +++ b/mlx/fast.h @@ -105,6 +105,23 @@ MLX_API CustomKernelFunction metal_kernel_with_mutable_inputs( 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& input_names, + const std::vector& output_names, + const std::string& source, + const std::vector& mutable_input_names, + const std::vector& 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& input_names, diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index bbe7d5b0c9..6d5effd791 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1,5 +1,7 @@ // Copyright © 2024-2026 Apple Inc. +#include +#include #include #include @@ -505,12 +507,29 @@ class Quantize : public Custom { using ScalarArg = std::variant; +// 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 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 source, std::tuple grid, std::tuple threadgroup, std::vector> shape_infos, @@ -520,7 +539,8 @@ class CustomKernel : public Primitive { bool is_precompiled, int shared_memory, CompileOptions::Data compile_options = {}, - std::vector mutable_inputs = {}) + std::vector mutable_inputs = {}, + std::vector fenced_inputs = {}) : Primitive(stream), name_(std::move(name)), source_(std::move(source)), @@ -533,7 +553,38 @@ class CustomKernel : public Primitive { is_precompiled_(is_precompiled), shared_memory_(shared_memory), compile_options_(compile_options), - mutable_inputs_(std::move(mutable_inputs)) {} + 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 grid, + std::tuple threadgroup, + std::vector> shape_infos, + bool ensure_row_contiguous, + std::optional init_value, + std::vector scalar_arguments, + bool is_precompiled, + int shared_memory, + CompileOptions::Data compile_options = {}, + std::vector mutable_inputs = {}) + : CustomKernel( + stream, + std::move(name), + std::make_shared(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& inputs, std::vector& outputs) override { @@ -544,10 +595,20 @@ class CustomKernel : public Primitive { 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_, @@ -561,7 +622,7 @@ class CustomKernel : public Primitive { private: std::string name_; - std::string source_; + std::shared_ptr source_; std::tuple grid_; std::tuple threadgroup_; std::vector> shape_infos_; @@ -574,6 +635,9 @@ class CustomKernel : public Primitive { protected: std::vector 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 fenced_inputs_; }; class MutableInputCustomKernel : public CustomKernel { diff --git a/mlx/fence.h b/mlx/fence.h index fd6bc116a4..a76d96e745 100644 --- a/mlx/fence.h +++ b/mlx/fence.h @@ -29,6 +29,15 @@ class Fence { 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 auto& cast() const { return *static_cast(fence_.get()); diff --git a/mlx/scheduler.h b/mlx/scheduler.h index c05765e433..7d9df759d4 100644 --- a/mlx/scheduler.h +++ b/mlx/scheduler.h @@ -37,6 +37,7 @@ class MLX_API Scheduler { { std::lock_guard lk(mtx); n_active_tasks_++; + n_active_cpu_tasks_ += stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -45,6 +46,7 @@ class MLX_API Scheduler { { std::lock_guard lk(mtx); n_active_tasks_--; + n_active_cpu_tasks_ -= stream.device.type == Device::cpu; } completion_cv.notify_all(); } @@ -53,6 +55,11 @@ class MLX_API Scheduler { 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 lk(mtx); int n_tasks_old = n_active_tasks(); @@ -69,6 +76,7 @@ class MLX_API Scheduler { StreamThread& get_thread(Stream s); int n_active_tasks_{0}; + int n_active_cpu_tasks_{0}; std::unordered_map> threads_; std::shared_mutex threads_mtx_; std::condition_variable completion_cv; @@ -113,6 +121,10 @@ 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) { scheduler().notify_new_task(stream); } diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 70dbe1e246..f5ae87cde3 100644 --- a/mlx/transforms.cpp +++ b/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(k) & mask_; + } + void grow() { + std::vector keys(std::max(64, 2 * keys_.size()), 0); + std::vector 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 keys_; + std::vector 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. @@ -98,6 +205,9 @@ array eval_impl(std::vector outputs, bool async) { }; std::unordered_map needs_fence; + // GPU streams with an array that a CPU primitive reads + std::unordered_set gpu_to_cpu; + auto synchronizer = array( {}, bool_, std::make_shared(stream), std::move(outputs)); @@ -115,7 +225,7 @@ array eval_impl(std::vector outputs, bool async) { { // Record the degree of each input - std::unordered_map cache; + DegreeMap cache; std::stack, int>> dfs; dfs.emplace(synchronizer, 0); @@ -156,19 +266,22 @@ array eval_impl(std::vector outputs, bool async) { if (!inserted) { it->second.cross_device |= device_switch; } + 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()]++; } @@ -210,9 +323,9 @@ array eval_impl(std::vector outputs, bool async) { } 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 +333,7 @@ array eval_impl(std::vector outputs, bool async) { } // Remove input and siblings from cache - cache.erase(it); + cache.erase(in.id()); for (auto& s : in.siblings()) { cache.erase(s.id()); } @@ -252,13 +365,22 @@ array eval_impl(std::vector outputs, bool async) { } } - 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& fence = fences.at(info.stream_index); + if (!one_gpu_stream || + !fence.wait_in_consumer(stream, arr, i, info.value)) { + fence.wait(stream, in, info.value); + } } else if (in.event().valid()) { if (in.event().is_signaled()) { in.detach_event(); @@ -275,7 +397,7 @@ array eval_impl(std::vector outputs, bool async) { 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 @@ -300,6 +422,15 @@ array eval_impl(std::vector outputs, bool async) { } nf->second.value = it->second.update(stream, a, nf->second.cross_device); + // MLX_EAGER_FENCE_COMMIT=1: commit the GPU work now, 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.cross_device && + stream.device == Device::gpu) { + gpu::finalize(stream); + } } }; diff --git a/mlx/utils.h b/mlx/utils.h index 4b7e6d12d9..86d77527e1 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -222,6 +222,18 @@ inline bool metal_fast_synch() { 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() { static bool enable_tf32_ = get_var("MLX_ENABLE_TF32", 1); return enable_tf32_; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8a00f114d8..83876c2f4c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,6 +32,7 @@ target_sources( 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 diff --git a/tests/distributed_sealed_stream_tests.cpp b/tests/distributed_sealed_stream_tests.cpp new file mode 100644 index 0000000000..6f1121f9d8 --- /dev/null +++ b/tests/distributed_sealed_stream_tests.cpp @@ -0,0 +1,265 @@ +// Copyright © 2026 Darkbloom. + +#include +#include +#include +#include +#include +#include +#include +#include + +#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 active{0}; + std::atomic seals{0}; + std::atomic opens{0}; + std::atomic bad_identity{false}; + std::atomic 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( + 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(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(input); + auto out = static_cast(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(context); + ++self.active; + ++self.opens; + auto in = static_cast(input); + auto out = static_cast(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 send, addend, remote, output; + std::vector 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(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(send.data()), + reinterpret_cast(addend.data()), + reinterpret_cast(output.data()), + sent_frame.data(), + received_frame.data(), + add ? detail::add_piece : 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 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::max(); + CHECK(detail::frame_extent(0, "[test]") == 0); + CHECK( + detail::frame_extent(longest, "[test]") == + std::numeric_limits::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); +} diff --git a/tests/jaccl/CMakeLists.txt b/tests/jaccl/CMakeLists.txt index 2f7eec9eee..9768aeea88 100644 --- a/tests/jaccl/CMakeLists.txt +++ b/tests/jaccl/CMakeLists.txt @@ -26,6 +26,21 @@ 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) diff --git a/tests/jaccl/exchange_tests.cpp b/tests/jaccl/exchange_tests.cpp new file mode 100644 index 0000000000..341c12fa89 --- /dev/null +++ b/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 +#include +#include + +#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 pattern(int64_t n, int seed) { + std::vector 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& 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, 2> input{pattern(n, 1), pattern(n, 2)}; + std::array, 2> output{ + std::vector(n + 1, 0x29), std::vector(n + 1, 0x29)}; + std::array, 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, 2> final{pattern(n, 3), pattern(n, 4)}; + std::array, 2> input{ + std::vector(n, char(fixture::sentinel)), + std::vector(n, char(fixture::sentinel))}; + std::array, 2> output{ + std::vector(n), std::vector(n)}; + std::array, 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, 2> input{pattern(n, 5), pattern(n, 6)}; + std::array, 2> output{ + std::vector(n), std::vector(n)}; + std::array 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 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(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(sealed); + crypt(static_cast(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(ctx); + if (self.refused || peer != 1 - self.rank) { + return 1; + } + uint64_t k = key(counter, peer, piece); + auto in = static_cast(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(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 ok{}; + std::array, 2> out; + std::array, 2> partial; +}; + +template +SumResult streamed_sum( + fixture::MeshPair& pair, + std::array& 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 mine(layout.frame(), char(fixture::sentinel)); + std::vector 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); + 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 +std::vector reference(const SumResult& r) { + std::vector sum(r.partial[0].size()); + auto a = reinterpret_cast(r.partial[0].data()); + auto b = reinterpret_cast(r.partial[1].data()); + auto out = reinterpret_cast(sum.data()); + for (size_t i = 0; i < sum.size() / sizeof(T); ++i) { + out[i] = + static_cast(static_cast(a[i]) + static_cast(b[i])); + } + return sum; +} + +template +void identical(size_t elements, size_t piece_bytes, bool jitter) { + fixture::MeshPair pair; + pair.fabric.idle_wait = std::chrono::milliseconds(0); + std::array codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].jitter = codecs[1].jitter = jitter; + auto r = streamed_sum(pair, codecs, elements, piece_bytes, 7); + auto expected = reference(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(4096, piece, false); // decode: one piece + identical(4096, piece, false); + identical(2048 * 1024, piece, false); // 4 MiB, 17 pieces + identical(2048 * 1024, piece, true); + identical(1 << 20, 100000, true); // pieces that straddle frames + identical(4096 * 2048, piece, false); // 16 MiB, 65 pieces +} + +void streamed_sum_tamper() { + fixture::MeshPair pair; + std::array codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].tamper = 5; + auto r = streamed_sum( + 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 codecs; + codecs[0].rank = 0; + codecs[1].rank = 1; + codecs[0].refuse_seal = 3; + auto r = streamed_sum(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 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 a/tests/jaccl/progress_guard_tests.cpp b/tests/jaccl/progress_guard_tests.cpp index 4cf652c187..34890cf953 100644 --- a/tests/jaccl/progress_guard_tests.cpp +++ b/tests/jaccl/progress_guard_tests.cpp @@ -1241,7 +1241,7 @@ void default_exit_check(const char* program) { } // namespace // One mode in each process: -// checks all cases with a limit of 250 ms +// 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 @@ -1267,8 +1267,11 @@ int main(int count, char** arguments) { setenv("JACCL_TIMEOUT_ACTION", "throw", 1); } if (mode == "checks") { - setenv(name, "250", 1); - value(250); + // 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(); diff --git a/tests/jaccl/startup_wait_budget_api_tests.cpp b/tests/jaccl/startup_wait_budget_api_tests.cpp new file mode 100644 index 0000000000..28bd34336f --- /dev/null +++ b/tests/jaccl/startup_wait_budget_api_tests.cpp @@ -0,0 +1,75 @@ +// Copyright © 2026 Apple Inc. +#include +#include +#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 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 +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 a/tests/jaccl/startup_wait_budget_group_tests.cpp b/tests/jaccl/startup_wait_budget_group_tests.cpp new file mode 100644 index 0000000000..3aab8d04e1 --- /dev/null +++ b/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 +#include +#include "fixture.h" + +void require(bool value) { + fixture::require(value, "startup group assertion failed"); +} +template +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 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 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 a/tests/jaccl/startup_wait_budget_tests.cpp b/tests/jaccl/startup_wait_budget_tests.cpp new file mode 100644 index 0000000000..67114bb0ed --- /dev/null +++ b/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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct FakeClock { + using duration = std::chrono::nanoseconds; + using rep = duration::rep; + using period = duration::period; + using time_point = std::chrono::time_point; + static constexpr bool is_steady = true; + static inline std::atomic 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; +using Guard = jaccl::BasicProgressGuard; +using namespace std::chrono_literals; + +void require(bool ok) { + if (!ok) { + throw std::runtime_error("assertion failed"); + } +} +template +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 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 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 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 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 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 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 failed{false}; + Policy p; + for (int64_t n : + {int64_t(-1), + int64_t(0), + int64_t(900001), + std::numeric_limits::max(), + std::numeric_limits::min()}) { + refuses([&] { 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 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 failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::max() - 999999); + refuses([&] { p.begin(1, failed); }); + FakeClock::ms(0); + p.begin(1, failed); + p.end(failed); +} +void exact_clock_limit() { + std::atomic failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::max() - 1000000); + p.begin(1, failed); + Guard g("clock limit", failed, &p); + FakeClock::ticks.store(std::numeric_limits::max()); + refuses([&] { g.check(&success, 1); }); +} +void negative_clock_epoch() { + std::atomic failed{false}; + Policy p; + FakeClock::ticks.store(std::numeric_limits::min()); + p.begin(900000, failed); + p.end(failed); +} +void one_shot() { + std::atomic failed{false}; + Policy p; + refuses([&] { p.end(failed); }); + p.begin(1000, failed); + refuses([&] { p.begin(900000, failed); }); + p.end(failed); + refuses([&] { p.end(failed); }); + refuses([&] { p.begin(1000, failed); }); +} +void expired_end_refuses() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + FakeClock::ms(1000); + refuses([&] { p.end(failed); }, "expired"); + refuses([&] { p.begin(1000, failed); }); + Guard g("still expired", failed, &p); + refuses([&] { g.check(&success, 1); }); + require(failed); +} +void closed_group_stays_closed() { + std::atomic failed{true}; + Policy p; + refuses([&] { p.begin(1000, failed); }); + require(failed); + std::atomic 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 failed{false}; + Policy p; + { + Guard g("default live", failed, &p); + refuses([&] { p.begin(1000, failed); }, "idle"); + } + p.begin(1000, failed); + { + Guard g("startup live", failed, &p); + refuses([&] { p.end(failed); }, "idle"); + } + p.end(failed); +} +void two_groups() { + std::atomic 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 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 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([&] { sample(b); }); +} +void late_wire_keeps_failure_kind() { + std::atomic failed{false}; + Policy p; + p.begin(1000, failed); + failed = true; + Guard late("late wire", failed, &p); + refuses([&] { late.check(&success, 1); }); +} + +void concurrent_begin() { + std::atomic failed{false}; + Policy p; + std::atomic won{0}, refused{0}; + std::vector 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 failed{false}; + Policy p; + p.begin(1000, failed); + std::atomic ready{0}; + std::atomic release{false}; + std::vector 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([&] { p.end(failed); }, "idle"); + release = true; + for (auto& t : threads) { + t.join(); + } + p.end(failed); +} +void hardware_error_preserved() { + std::atomic 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 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 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>> 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"; +}