Layr-Labs/mlx-c

diff: ignored:
+1796
-4
+1251
-0

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

MLX C is the C boundary between the MLX core and every other language binding. Layr-Labs runs an LLM/VLM serving stack on Apple silicon — continuous batching, paged KV caches, MoE and quantized kernels — built as mlx-swift-lm on mlx-swift, which links a forked mlx core through this fork. Every change here is a carry-patch: a thin C wrapper over a function the forked core added, so Swift can reach it. The upstream API and ABI are left untouched; the fork only adds entry points, and pins the core it builds against to the Layr-Labs revision that provides them.

Downstream consumers are named per section so a change here can be traced to the Swift symbol that needs it.

CMakeLists.txt fetches the MLX core from Layr-Labs/mlx at an exact commit instead of an upstream release tag. The C functions below wrap core functions that only exist on the fork, so the pin is what makes them link; it is bumped together with the header changes each time the core gains a new entry point. The current pin is ea318ee0, the core that Layr-Labs/mlx-swift builds for the cluster stack. It contains main’s previous pin ff4bb35b and the sealed reduce-scatter and all-gather (360d11b9) that distributed_sealed.cpp calls. The current pin also preserves 512- and 1024-thread custom Metal launch geometry while retrying an insufficient pipeline with its explicit compiler capacity, orders the fast-synch GPU wait after every pending pass on its queue (a CPU-stream collective between two GPU passes could otherwise leave the GPU spinning forever), and carries 1 MiB JACCL frames, batched buffer retention, a cached custom-kernel source per kernel (host time only), the streamed sealed all-sum (per-piece AES-256-GCM over a two-rank JACCL exchange), opt-in fused fence updates and fenced custom-kernel inputs, and cheaper custom-kernel launches and graph bookkeeping (host time only), and the thread-scoped command-buffer commit limits. The page-backed footprint change is reverted, as on the single-Mac stack.

diff --git ml-explore/mlx-c/CMakeLists.txt Layr-Labs/mlx-c/CMakeLists.txt index 3bf43dabc2e46d8c07badc02d383e4b9632cdbbe..4d612a8d22f8aceff4a4436cce22adb47e55adfb 100644 --- ml-explore/mlx-c/CMakeLists.txt +++ Layr-Labs/mlx-c/CMakeLists.txt @@ -13,6 +13,7 @@ endif()   option(BUILD_SHARED_LIBS "Build mlx C as a shared library" OFF) option(MLX_C_BUILD_EXAMPLES "Build examples for mlx C" ON) +option(MLX_C_BUILD_TESTS "Build tests for mlx C" OFF) option(MLX_C_USE_SYSTEM_MLX "Use system MLX" OFF)   # ----------------------------- mlx ----------------------------- @@ -34,8 +35,8 @@ find_package(MLX REQUIRED) else() FetchContent_Declare( mlx - GIT_REPOSITORY "https://github.com/ml-explore/mlx.git" - GIT_TAG v0.32.4) + GIT_REPOSITORY "https://github.com/Layr-Labs/mlx.git" + GIT_TAG ea318ee053926640c9d19ce10e0ba04f70955f1d) FetchContent_MakeAvailable(mlx) endif()   @@ -48,7 +49,9 @@ ${CMAKE_CURRENT_LIST_DIR}/mlx/c/compile.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/cuda.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/device.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/distributed.cpp + ${CMAKE_CURRENT_LIST_DIR}/mlx/c/distributed_bootstrap.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/distributed_group.cpp + ${CMAKE_CURRENT_LIST_DIR}/mlx/c/distributed_sealed.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/error.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/export.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/fast.cpp @@ -59,6 +62,7 @@ ${CMAKE_CURRENT_LIST_DIR}/mlx/c/io_types.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/linalg.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/map.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/memory.cpp + mlx/c/memory_cap.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/metal.cpp # ${CMAKE_CURRENT_LIST_DIR}/mlx/c/object.cpp ${CMAKE_CURRENT_LIST_DIR}/mlx/c/ops.cpp @@ -84,6 +88,13 @@ endif()   if(MLX_C_BUILD_EXAMPLES) add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/examples) +endif() + +if(MLX_C_BUILD_TESTS) + enable_testing() + add_executable(metal_kernel_options_test tests/metal_kernel_options.cpp) + target_link_libraries(metal_kernel_options_test PRIVATE mlxc) + add_test(NAME metal_kernel_options COMMAND metal_kernel_options_test) endif()   # ----------------------------- Installation -----------------------------

The Swift admission code decides whether a request fits by asking the allocator, and the upstream C API only offered independent counters. The fork adds, in order of arrival:

  • mlx_get_num_resources / mlx_get_resource_limit — the live Metal buffer count and its hard ceiling, the quantity behind the [metal::malloc] Resource limit exceeded crash (consumed as Memory.numResources / Memory.resourceLimit in mlx-swift).
  • mlx_get_memory_snapshot — one coherent active/cache/peak observation instead of three separate calls that can straddle an allocation.
  • mlx_get_allocation_footprint_policy and its checked _bound / _maximum_extra helpers — the allocator’s immutable rounding geometry (alignment, rounding threshold, minimum allocation, power-of-two cut-off, cache page size) so callers can compute the real footprint of a requested size without allocating; bound helpers return 1 on an invalid policy or overflow without raising through the error callback.
  • mlx_get_allocation_size_upper_bound — the same bound for the current policy.

The generator override in python/mlxhooks.py keeps mlx_get_memory_snapshot intact when the bindings are regenerated from the core headers.

diff --git ml-explore/mlx-c/mlx/c/memory.cpp Layr-Labs/mlx-c/mlx/c/memory.cpp index c72b9415b01ca487c829661dc3caa7da35c6f708..fb825ef42a385f5c6626c53d7d94c33c2a6ae6c4 100644 --- ml-explore/mlx-c/mlx/c/memory.cpp +++ Layr-Labs/mlx-c/mlx/c/memory.cpp @@ -4,9 +4,9 @@ /* This file is auto-generated. Do not edit manually. */ /* */   #include "mlx/c/memory.h" +#include "mlx/memory.h" #include "mlx/c/error.h" #include "mlx/c/private/mlx.h" -#include "mlx/memory.h"   extern "C" int mlx_clear_cache(void) { try { @@ -55,9 +55,40 @@ return 1; } return 0; } +extern "C" int mlx_get_memory_snapshot(size_t* active, size_t* cache, size_t* peak) { + try { + auto snapshot = mlx::core::get_memory_snapshot(); + *active = snapshot.active_memory; + *cache = snapshot.cache_memory; + *peak = snapshot.peak_memory; + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_get_num_resources(size_t* res) { + try { + *res = mlx::core::get_num_resources(); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} extern "C" int mlx_get_peak_memory(size_t* res) { try { *res = mlx::core::get_peak_memory(); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} +extern "C" int mlx_get_resource_limit(size_t* res) { + try { + *res = mlx::core::get_resource_limit(); } catch (std::exception& e) { mlx_error(e.what()); return 1; @@ -100,3 +131,37 @@ return 1; } return 0; } + +extern "C" int mlx_get_allocation_size_upper_bound(size_t* res, size_t size) { + try { + *res = mlx::core::get_allocation_size_upper_bound(size); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_get_allocation_footprint_policy(mlx_allocation_footprint_policy* res) { + if (!res) { return 1; } + auto p = mlx::core::get_allocation_footprint_policy(); + *res = {p.alignment, p.rounding_threshold, p.minimum_allocation, + p.power_of_two_below, p.cache_page_size}; + return 0; +} + +static mlx::core::AllocationFootprintPolicy core_policy( + const mlx_allocation_footprint_policy& p) noexcept { + return {p.alignment, p.rounding_threshold, p.minimum_allocation, + p.power_of_two_below, p.cache_page_size}; +} + +extern "C" int mlx_allocation_footprint_policy_bound(size_t* res, + const mlx_allocation_footprint_policy* policy, size_t size) { + return res && policy && core_policy(*policy).upper_bound(size, *res) ? 0 : 1; +} + +extern "C" int mlx_allocation_footprint_policy_maximum_extra(size_t* res, + const mlx_allocation_footprint_policy* policy) { + return res && policy && core_policy(*policy).maximum_extra_bytes(*res) ? 0 : 1; +}
diff --git ml-explore/mlx-c/mlx/c/memory.h Layr-Labs/mlx-c/mlx/c/memory.h index 972142c75383ce0c1f64afd62056634b5260934c..d82e00d6fb38c936dd6e98d095e964c8af31d6bd 100644 --- ml-explore/mlx-c/mlx/c/memory.h +++ Layr-Labs/mlx-c/mlx/c/memory.h @@ -28,12 +28,51 @@ * \defgroup memory Memory operations */ /**@{*/   +/* Process-local, install-once Metal backing cap. Not a host/driver memory cap. + * Released buffers remain charged until their deallocator releases owned pages. + * Foreign wrappers never transfer ownership of caller pages. */ +typedef struct mlx_process_allocation_cap_snapshot { + bool installed; + size_t limit_bytes; + size_t heap_bytes; + size_t live_bytes; + size_t cached_bytes; + size_t pending_bytes; + size_t unreclaimed_bytes; + size_t charged_bytes; + size_t peak_bytes; +} mlx_process_allocation_cap_snapshot; +int mlx_install_process_allocation_cap(size_t bytes); +int mlx_get_process_allocation_cap_snapshot(mlx_process_allocation_cap_snapshot* res); + int mlx_clear_cache(void); int mlx_get_active_memory(size_t* res); +int mlx_get_allocation_size_upper_bound(size_t* res, size_t size); + +/* Immutable allocator geometry. Bound functions return 1 on invalid policy or + * overflow without invoking the error callback or allocating an exception. */ +typedef struct mlx_allocation_footprint_policy { + size_t alignment; + size_t rounding_threshold; + size_t minimum_allocation; + size_t power_of_two_below; + size_t cache_page_size; +} mlx_allocation_footprint_policy; + +int mlx_get_allocation_footprint_policy(mlx_allocation_footprint_policy* res); +int mlx_allocation_footprint_policy_bound(size_t* res, + const mlx_allocation_footprint_policy* policy, size_t size); +int mlx_allocation_footprint_policy_maximum_extra(size_t* res, + const mlx_allocation_footprint_policy* policy); + int mlx_get_array_buffer_size(size_t* res, const mlx_vector_array arrays); int mlx_get_cache_memory(size_t* res); int mlx_get_memory_limit(size_t* res); +int mlx_get_memory_snapshot(size_t* active, size_t* cache, size_t* peak); + +int mlx_get_num_resources(size_t* res); int mlx_get_peak_memory(size_t* res); +int mlx_get_resource_limit(size_t* res); int mlx_reset_peak_memory(void); int mlx_set_cache_limit(size_t* res, size_t limit); int mlx_set_memory_limit(size_t* res, size_t limit);
diff --git ml-explore/mlx-c/python/mlxhooks.py Layr-Labs/mlx-c/python/mlxhooks.py index 96b13ee7c4bc499a1449d35928049a763315641e..8ce4209c5618db5226e64a88f4e088c0a2508422 100644 --- ml-explore/mlx-c/python/mlxhooks.py +++ Layr-Labs/mlx-c/python/mlxhooks.py @@ -391,6 +391,10 @@ const char* header, bool ensure_row_contiguous, bool atomic_outputs); """ + # Retain the fork's mutable-input constructor and explicit per-kernel + # options when regenerating fast.h/fast.cpp. + from metal_kernel_options import extensions + custom_code += extensions(implementation) __implement_mlx_fast_custom_kernel("metal", custom_code, implementation)   @@ -506,6 +510,29 @@ }""" ) pass return True + + +def mlx_get_memory_snapshot(f, implementation): + if not implementation: + print( + "int mlx_get_memory_snapshot(size_t* active, size_t* cache, size_t* peak);" + ) + else: + print( + '''\ +extern "C" int mlx_get_memory_snapshot(size_t* active, size_t* cache, size_t* peak) { + try { + auto snapshot = mlx::core::get_memory_snapshot(); + *active = snapshot.active_memory; + *cache = snapshot.cache_memory; + *peak = snapshot.peak_memory; + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +}''' + )   def mlx_compile(f, implementation):

mlx_install_process_allocation_cap installs the core’s install-once Metal backing cap and mlx_get_process_allocation_cap_snapshot reads its ledger (limit, fixed heap, live, cached, pending, unreclaimed, charged and peak bytes). Both forward to the matching core accounting and report failures through the error handler; CPU and CUDA builds refuse. The standalone example checks that interface. Consumed as Memory.installProcessAllocationCap / Memory.processAllocationCapSnapshot in mlx-swift.

diff --git ml-explore/mlx-c/examples/cap-tests/memory_cap.cpp Layr-Labs/mlx-c/examples/cap-tests/memory_cap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd08fa060c6336f83a32c16f9598f03437a8d0b8 --- /dev/null +++ Layr-Labs/mlx-c/examples/cap-tests/memory_cap.cpp @@ -0,0 +1,58 @@ +// Copyright © 2026 Eigen Labs. +#include <cassert> +#include <iostream> +#include "mlx/c/memory.h" +#include "mlx/memory.h" + +namespace { +mlx::core::allocator::ProcessAllocationCap ledger; +bool unsupported = false; +int errors = 0; +} // namespace +// Link the actual C adapter to a CPU ledger; no Metal/device initialization. +namespace mlx::core { +void install_process_allocation_cap(size_t bytes) { + if (unsupported) { + throw std::runtime_error("unsupported"); + } + ledger.install(bytes, 4); +} +ProcessAllocationCapSnapshot get_process_allocation_cap_snapshot() { + if (unsupported) { + throw std::runtime_error("unsupported"); + } + return ledger.snapshot(); +} +} // namespace mlx::core +extern "C" void _mlx_error(const char*, int, const char*, ...) { + ++errors; +} +int main() { + mlx_process_allocation_cap_snapshot s{}; + assert(mlx_get_process_allocation_cap_snapshot(nullptr) == 1); + assert(mlx_install_process_allocation_cap(3) == 1); + assert(mlx_get_process_allocation_cap_snapshot(&s) == 0 && !s.installed); + assert(mlx_install_process_allocation_cap(16) == 0); + assert(mlx_install_process_allocation_cap(32) == 1); + ledger.reserve(12); + ledger.acquired(12); + ledger.cache(12); + assert(mlx_get_process_allocation_cap_snapshot(&s) == 0); + assert(s.installed && s.limit_bytes == 16 && s.heap_bytes == 4); + assert(s.cached_bytes == 12 && s.charged_bytes == 16 && s.peak_bytes == 16); + ledger.reuse(12); + ledger.relinquish(12); + assert(mlx_get_process_allocation_cap_snapshot(&s) == 0); + assert(s.unreclaimed_bytes == 12 && s.live_bytes == 0 && s.cached_bytes == 0); + ledger.destroyed(12); + assert( + mlx_get_process_allocation_cap_snapshot(&s) == 0 && s.charged_bytes == 4); + unsupported = true; + s.limit_bytes = 99; + assert( + mlx_get_process_allocation_cap_snapshot(&s) == 1 && s.limit_bytes == 99); + assert(mlx_install_process_allocation_cap(16) == 1); + assert(errors == 5); + std::cout + << "PASS: actual C adapter errors, null output, install-once, snapshot fields, unsupported backend, unchanged failed output\n"; +}
diff --git ml-explore/mlx-c/mlx/c/memory_cap.cpp Layr-Labs/mlx-c/mlx/c/memory_cap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adc48b7a5126ef43ab870a84dd2a2b47ea778396 --- /dev/null +++ Layr-Labs/mlx-c/mlx/c/memory_cap.cpp @@ -0,0 +1,38 @@ +// Copyright © 2026 Eigen Labs. +#include "mlx/c/error.h" +#include "mlx/c/memory.h" +#include "mlx/memory.h" + +extern "C" int mlx_install_process_allocation_cap(size_t bytes) { + try { + mlx::core::install_process_allocation_cap(bytes); + return 0; + } catch (const std::exception& e) { + mlx_error("%s", e.what()); + return 1; + } +} + +extern "C" int mlx_get_process_allocation_cap_snapshot( + mlx_process_allocation_cap_snapshot* res) { + try { + if (!res) { + throw std::invalid_argument("null allocation cap snapshot"); + } + const auto s = mlx::core::get_process_allocation_cap_snapshot(); + *res = { + s.installed, + s.limit_bytes, + s.heap_bytes, + s.live_bytes, + s.cached_bytes, + s.pending_bytes, + s.unreclaimed_bytes, + s.charged_bytes, + s.peak_bytes}; + return 0; + } catch (const std::exception& e) { + mlx_error("%s", e.what()); + return 1; + } +}

Two non-evaluating inspections the quantized-inference path in mlx-swift relies on:

  • mlx_array_get_buffer_info — backing metadata (allocated bytes, data offset, element count, row-contiguity, uniqueness) for an already evaluated array. Unavailable backing is reported as available=false rather than forcing an eval or a stream sync; views may report shared backing and the fields confer no ownership. unique comes from array::is_uniquely_referenced() in the Layr-Labs/mlx core: no other array references the array or its data. It does not require MLX to own the buffer, so a wrapped external buffer can be unique (upstream #4634 made is_donatable() require ownership).
  • _mlx_array_constant_cache_identity — the backing descriptor’s identity plus a transform-safety predicate, so a Swift constant cache can reuse an unchanged constant’s exact cast across calls without mistaking a mutated array for its former contents. It refuses compile/autodiff tracing and retained graphs, and never evaluates, hashes, or reads data back. Marked internal: the caller must retain the source descriptor while the identity is cached.
diff --git ml-explore/mlx-c/mlx/c/array.cpp Layr-Labs/mlx-c/mlx/c/array.cpp index 7c7342d3c2318abf2020acf56d8f7c2e6c2fb364..db4e52f28112a75c8ff577fca262d15f6119ecc0 100644 --- ml-explore/mlx-c/mlx/c/array.cpp +++ Layr-Labs/mlx-c/mlx/c/array.cpp @@ -6,6 +6,7 @@ #include "mlx/c/array.h" #include "mlx/c/error.h" #include "mlx/c/private/mlx.h" #include "mlx/c/string.h" +#include "mlx/transforms_impl.h"   extern "C" size_t mlx_dtype_size(mlx_dtype dtype) { return mlx_dtype_to_cpp(dtype).size(); @@ -659,3 +660,49 @@ return 1; } return 0; } + +extern "C" int mlx_array_get_buffer_info( + bool* available, size_t* allocated_bytes, size_t* data_offset, + size_t* data_elements, bool* row_contiguous, bool* unique, + const mlx_array arr) { + *available = false; + *allocated_bytes = 0; + *data_offset = 0; + *data_elements = 0; + *row_contiguous = false; + *unique = false; + try { + const auto& value = mlx_array_get_(arr); + if (!value.is_available() || !value.data_shared_ptr()) { + return 0; + } + *allocated_bytes = value.buffer().ptr() ? value.buffer_size() : 0; + *data_offset = value.offset(); + *data_elements = value.data_size(); + *row_contiguous = value.flags().row_contiguous; + // No other array references this array or its data. Ownership of the + // buffer does not matter here (a wrapped external buffer can be unique). + *unique = value.is_uniquely_referenced(); + *available = true; + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +// Non-evaluating identity for bounded immutable-constant caches. The caller +// retains an array snapshot for every cached identity to prevent address ABA. +extern "C" int _mlx_array_constant_cache_identity( + uintptr_t* identity, bool* can_cache, const mlx_array arr) { + try { + const auto& value = mlx_array_get_(arr); + *identity = value.id(); + *can_cache = !mlx::core::detail::in_tracing() && + !mlx::core::detail::retain_graph() && !value.is_tracer(); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +}
diff --git ml-explore/mlx-c/mlx/c/array.h Layr-Labs/mlx-c/mlx/c/array.h index a3b382bb2a5d4a338c459730f99d1b13db0acd7e..5a7b71c883695cbd20bf35000aeb09a40f5a8a2c 100644 --- ml-explore/mlx-c/mlx/c/array.h +++ Layr-Labs/mlx-c/mlx/c/array.h @@ -387,6 +387,24 @@ * Internal function: use at your own risk. */ int _mlx_array_is_available(bool* res, const mlx_array arr);   +/** Non-blocking backing metadata. Unavailable arrays return available=false. + * Views may report shared backing; these fields do not confer ownership. + * `unique` is true when no other array references the array or its data, + * also for a wrapped external buffer that MLX does not own. */ +int mlx_array_get_buffer_info( + bool* available, size_t* allocated_bytes, size_t* data_offset, + size_t* data_elements, bool* row_contiguous, bool* unique, + const mlx_array arr); + + +/** + * Backing descriptor identity and whether a constant cast may be retained. + * Does not evaluate the array. Retain a snapshot while using the identity. + * Internal function: use at your own risk. + */ +int _mlx_array_constant_cache_identity( + uintptr_t* identity, bool* can_cache, const mlx_array arr); + /** * Wait on the array to be available. After this `_mlx_array_is_available` * returns `true`. Internal function: use at your own risk.
  • mlx_fast_metal_kernel_new_mutable — a second constructor for custom Metal kernels that declares which caller-owned input buffers the kernel writes (the core’s mutable-input contract, used for in-place paged KV updates). The existing constructor and its read-only ABI are unchanged.
  • mlx_fast_metal_kernel_new_fenced — the same with fenced inputs: inputs that can come from a CPU stream in the same eval, which the kernel waits for itself (core metal_kernel_with_fenced_inputs, opt-in MLX_METAL_FENCED_INPUTS=1).
  • mlx_fast_metal_kernel_new_with_options adds an explicit safe, relaxed or fast compiler math mode for one custom kernel, including mutable-input metadata. Legacy constructors remain unchanged; this does not alter process-wide defaults. Non-safe modes require operation-specific numerical and platform qualification. The generator extension retains new_mutable and new_with_options when bindings regenerate. It does not yet emit new_fenced or the prepared-launch functions, so a regeneration must carry those hand edits over.
  • mlx_fast_metal_kernel_launch_new / _apply / _free — a prepared launch: a kernel bound once to a copied config and applied to new inputs without rebuilding the config (host time only). The kernel must outlive the launch. MLX_C_BUILD_TESTS enables constructor/error-contract tests without GPU execution.
diff --git ml-explore/mlx-c/docs/src/fast.rst Layr-Labs/mlx-c/docs/src/fast.rst index 0ba37e668beb3efa7d3576a40743e3a62922c005..9d55037d4165050f957274720d890888ce3105ed 100644 --- ml-explore/mlx-c/docs/src/fast.rst +++ Layr-Labs/mlx-c/docs/src/fast.rst @@ -1,5 +1,20 @@ Fast Custom Ops ===============   +Per-kernel Metal compiler options +--------------------------------- + +``mlx_fast_metal_kernel_new_with_options`` forwards an explicit ``safe``, +``relaxed`` or ``fast`` compiler mode to MLX for that kernel only. Existing +constructors retain the core's safe default. Pass an empty mutable-input vector +for a read-only kernel; nonempty metadata retains the existing write-hazard +contract. Mode selection is fixed at construction and is included in the core +compiled-library cache identity. It does not alter other kernels or global state. + +Changing compiler modes can change numerical results. Qualify the exact +operation, device and input contract before opting in. MLX's platform restrictions +remain in force (in particular, relaxed mode needs macOS 15/iOS 18 or newer). +Unknown enum values invoke the error handler and return an empty handle. + .. doxygengroup:: fast :content-only:
diff --git ml-explore/mlx-c/mlx/c/fast.cpp Layr-Labs/mlx-c/mlx/c/fast.cpp index 2054aebc8e19345efd2aec4f060ad39d1c8dea6c..1a1148c724a876a025c755a17f15b5bf80ffb583 100644 --- ml-explore/mlx-c/mlx/c/fast.cpp +++ Layr-Labs/mlx-c/mlx/c/fast.cpp @@ -525,6 +525,89 @@ } return {nullptr}; }   +extern "C" mlx_fast_metal_kernel mlx_fast_metal_kernel_new_mutable( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names) { + try { + return mlx_fast_metal_kernel({new mlx_fast_metal_kernel_cpp_( + mlx::core::fast::metal_kernel_with_mutable_inputs( + name, mlx_vector_string_get_(input_names), + mlx_vector_string_get_(output_names), source, + mlx_vector_string_get_(mutable_input_names), header, + ensure_row_contiguous, atomic_outputs))}); + } catch (std::exception& e) { + mlx_error(e.what()); + } + return {nullptr}; +} + +extern "C" mlx_fast_metal_kernel mlx_fast_metal_kernel_new_fenced( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + const mlx_vector_string fenced_input_names) { + try { + return mlx_fast_metal_kernel({new mlx_fast_metal_kernel_cpp_( + mlx::core::fast::metal_kernel_with_fenced_inputs( + name, mlx_vector_string_get_(input_names), + mlx_vector_string_get_(output_names), source, + mlx_vector_string_get_(mutable_input_names), + mlx_vector_string_get_(fenced_input_names), header, + ensure_row_contiguous, atomic_outputs))}); + } catch (std::exception& e) { + mlx_error(e.what()); + } + return {nullptr}; +} + +extern "C" mlx_fast_metal_kernel mlx_fast_metal_kernel_new_with_options( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + mlx_fast_metal_kernel_math_mode math_mode) { + try { + mlx::core::CompileOptions options; + switch (math_mode) { + case MLX_FAST_METAL_MATH_SAFE: + options.math_mode = mlx::core::MathMode::Safe; + break; + case MLX_FAST_METAL_MATH_RELAXED: + options.math_mode = mlx::core::MathMode::Relaxed; + break; + case MLX_FAST_METAL_MATH_FAST: + options.math_mode = mlx::core::MathMode::Fast; + break; + default: + throw std::invalid_argument("Unknown custom Metal kernel math mode."); + } + return mlx_fast_metal_kernel({new mlx_fast_metal_kernel_cpp_( + mlx::core::fast::metal_kernel_with_mutable_inputs( + name, mlx_vector_string_get_(input_names), + mlx_vector_string_get_(output_names), source, + mlx_vector_string_get_(mutable_input_names), header, + ensure_row_contiguous, atomic_outputs, options))}); + } catch (std::exception& e) { + mlx_error(e.what()); + } + return {nullptr}; +} + inline mlx::core::fast::CustomKernelFunction& mlx_fast_metal_kernel_get_( mlx_fast_metal_kernel d) { if (!d.ctx) { @@ -550,7 +633,9 @@ const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, const mlx_stream stream) { try { - auto config_ctx = mlx_fast_metal_kernel_config_get_(config); + // By reference: a copy of the config (shapes, template arguments) per + // launch is avoidable host work. + const auto& config_ctx = mlx_fast_metal_kernel_config_get_(config); mlx_vector_array_set_( *outputs, mlx_fast_metal_kernel_get_(cls)( @@ -562,6 +647,59 @@ config_ctx.thread_group, config_ctx.template_args, config_ctx.init_value, config_ctx.verbose, + mlx_stream_get_(stream))); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +struct mlx_fast_metal_kernel_launch_cpp_ { + const mlx::core::fast::CustomKernelFunction* mkf; + mlx_fast_metal_kernel_config_cpp_ config; +}; + +extern "C" mlx_fast_metal_kernel_launch mlx_fast_metal_kernel_launch_new( + mlx_fast_metal_kernel cls, + const mlx_fast_metal_kernel_config config) { + try { + return mlx_fast_metal_kernel_launch( + {new mlx_fast_metal_kernel_launch_cpp_{ + &mlx_fast_metal_kernel_get_(cls), + mlx_fast_metal_kernel_config_get_(config)}}); + } catch (std::exception& e) { + mlx_error(e.what()); + return mlx_fast_metal_kernel_launch({nullptr}); + } +} + +extern "C" void mlx_fast_metal_kernel_launch_free( + mlx_fast_metal_kernel_launch launch) { + delete static_cast<mlx_fast_metal_kernel_launch_cpp_*>(launch.ctx); +} + +extern "C" int mlx_fast_metal_kernel_launch_apply( + mlx_vector_array* outputs, + mlx_fast_metal_kernel_launch launch, + const mlx_vector_array inputs, + const mlx_stream stream) { + try { + if (!launch.ctx) { + throw std::runtime_error("expected a non-empty mlx_fast_metal_kernel_launch"); + } + auto& l = *static_cast<mlx_fast_metal_kernel_launch_cpp_*>(launch.ctx); + mlx_vector_array_set_( + *outputs, + (*l.mkf)( + mlx_vector_array_get_(inputs), + l.config.output_shapes, + l.config.output_dtypes, + l.config.grid, + l.config.thread_group, + l.config.template_args, + l.config.init_value, + l.config.verbose, mlx_stream_get_(stream))); } catch (std::exception& e) { mlx_error(e.what());
diff --git ml-explore/mlx-c/mlx/c/fast.h Layr-Labs/mlx-c/mlx/c/fast.h index e4445f72f12a135482e3110762380437c8c28ec1..81e8365cb2f1c4e7b02d50472e7f6de6b639abe6 100644 --- ml-explore/mlx-c/mlx/c/fast.h +++ Layr-Labs/mlx-c/mlx/c/fast.h @@ -169,11 +169,83 @@ bool atomic_outputs);   void mlx_fast_metal_kernel_free(mlx_fast_metal_kernel cls);   +mlx_fast_metal_kernel mlx_fast_metal_kernel_new_mutable( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names); + +/** + * As mlx_fast_metal_kernel_new_mutable. A fenced input can come from a CPU + * stream in the same eval (a CPU-stream all-sum); with + * MLX_METAL_FENCED_INPUTS=1 the kernel waits for it itself, and MLX encodes + * no separate fence wait. The source calls MLX_FENCED_INPUT_WAIT(name) for + * each fenced input before it reads it, where every thread of the + * threadgroup reaches the call. + */ +mlx_fast_metal_kernel mlx_fast_metal_kernel_new_fenced( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + const mlx_vector_string fenced_input_names); + +/** Compiler math mode for one custom kernel; legacy constructors stay safe. */ +typedef enum mlx_fast_metal_kernel_math_mode_ { + MLX_FAST_METAL_MATH_SAFE = 0, + MLX_FAST_METAL_MATH_RELAXED = 1, + MLX_FAST_METAL_MATH_FAST = 2 +} mlx_fast_metal_kernel_math_mode; + +/** + * Create one kernel with explicit compiler options and mutable-input metadata. + * Pass a valid empty vector when no input is mutable. This does not change + * global defaults. Different modes may produce different numerical results; + * the caller must qualify the selected mode. Invalid modes return an empty + * handle after invoking the error handler. Backend OS restrictions still apply. + */ +mlx_fast_metal_kernel mlx_fast_metal_kernel_new_with_options( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + mlx_fast_metal_kernel_math_mode math_mode); + int mlx_fast_metal_kernel_apply( mlx_vector_array* outputs, mlx_fast_metal_kernel cls, const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, + const mlx_stream stream); + +/** + * A prepared launch: `cls` with a fixed config (template arguments, grid, + * threadgroup, output shapes and dtypes, init value), bound once and applied + * to new inputs without rebuilding the config. `cls` must outlive it. + */ +typedef struct mlx_fast_metal_kernel_launch_ { + void* ctx; +} mlx_fast_metal_kernel_launch; +mlx_fast_metal_kernel_launch mlx_fast_metal_kernel_launch_new( + mlx_fast_metal_kernel cls, + const mlx_fast_metal_kernel_config config); +void mlx_fast_metal_kernel_launch_free(mlx_fast_metal_kernel_launch launch); +int mlx_fast_metal_kernel_launch_apply( + mlx_vector_array* outputs, + mlx_fast_metal_kernel_launch launch, + const mlx_vector_array inputs, const mlx_stream stream);   int mlx_fast_rms_norm(
diff --git ml-explore/mlx-c/python/metal_kernel_options.py Layr-Labs/mlx-c/python/metal_kernel_options.py new file mode 100644 index 0000000000000000000000000000000000000000..f952465298da1f23d497c19fa7e12e8406e4fc07 --- /dev/null +++ Layr-Labs/mlx-c/python/metal_kernel_options.py @@ -0,0 +1,101 @@ +"""Hand-maintained fork extensions emitted with the generated Metal C wrapper.""" + + +def extensions(implementation): + if implementation: + return r''' +extern "C" mlx_fast_metal_kernel mlx_fast_metal_kernel_new_mutable( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names) { + try { + return mlx_fast_metal_kernel({new mlx_fast_metal_kernel_cpp_( + mlx::core::fast::metal_kernel_with_mutable_inputs( + name, mlx_vector_string_get_(input_names), + mlx_vector_string_get_(output_names), source, + mlx_vector_string_get_(mutable_input_names), header, + ensure_row_contiguous, atomic_outputs))}); + } catch (std::exception& e) { + mlx_error(e.what()); + } + return {nullptr}; +} + +extern "C" mlx_fast_metal_kernel mlx_fast_metal_kernel_new_with_options( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + mlx_fast_metal_kernel_math_mode math_mode) { + try { + mlx::core::CompileOptions options; + switch (math_mode) { + case MLX_FAST_METAL_MATH_SAFE: + options.math_mode = mlx::core::MathMode::Safe; + break; + case MLX_FAST_METAL_MATH_RELAXED: + options.math_mode = mlx::core::MathMode::Relaxed; + break; + case MLX_FAST_METAL_MATH_FAST: + options.math_mode = mlx::core::MathMode::Fast; + break; + default: + throw std::invalid_argument("Unknown custom Metal kernel math mode."); + } + return mlx_fast_metal_kernel({new mlx_fast_metal_kernel_cpp_( + mlx::core::fast::metal_kernel_with_mutable_inputs( + name, mlx_vector_string_get_(input_names), + mlx_vector_string_get_(output_names), source, + mlx_vector_string_get_(mutable_input_names), header, + ensure_row_contiguous, atomic_outputs, options))}); + } catch (std::exception& e) { + mlx_error(e.what()); + } + return {nullptr}; +} +''' + return r''' +mlx_fast_metal_kernel mlx_fast_metal_kernel_new_mutable( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names); + +/** Compiler math mode for one custom kernel; legacy constructors stay safe. */ +typedef enum mlx_fast_metal_kernel_math_mode_ { + MLX_FAST_METAL_MATH_SAFE = 0, + MLX_FAST_METAL_MATH_RELAXED = 1, + MLX_FAST_METAL_MATH_FAST = 2 +} mlx_fast_metal_kernel_math_mode; + +/** + * Create one kernel with explicit compiler options and mutable-input metadata. + * Pass a valid empty vector when no input is mutable. This does not change + * global defaults. Different modes may produce different numerical results; + * the caller must qualify the selected mode. Invalid modes return an empty + * handle after invoking the error handler. Backend OS restrictions still apply. + */ +mlx_fast_metal_kernel mlx_fast_metal_kernel_new_with_options( + const char* name, + const mlx_vector_string input_names, + const mlx_vector_string output_names, + const char* source, + const char* header, + bool ensure_row_contiguous, + bool atomic_outputs, + const mlx_vector_string mutable_input_names, + mlx_fast_metal_kernel_math_mode math_mode); +'''
diff --git ml-explore/mlx-c/tests/metal_kernel_options.cpp Layr-Labs/mlx-c/tests/metal_kernel_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91ae76fb3d610eeeaa83fe564d8dc9339bcc446a --- /dev/null +++ Layr-Labs/mlx-c/tests/metal_kernel_options.cpp @@ -0,0 +1,60 @@ +#include "mlx/c/error.h" +#include "mlx/c/fast.h" +#include <cstdio> +#include <initializer_list> +#include <stdexcept> + +// Constructor/validation test only: never applies a kernel or opens a device. +static int errors = 0; +static void capture_error(const char*, void*) { ++errors; } +static void require(bool condition) { + if (!condition) throw std::runtime_error("Metal options constructor contract failed"); +} + +int main() { + mlx_set_error_handler(capture_error, nullptr, nullptr); + auto inputs = mlx_vector_string_new(); + auto outputs = mlx_vector_string_new(); + auto empty = mlx_vector_string_new(); + auto mutable_inputs = mlx_vector_string_new(); + auto invalid_inputs = mlx_vector_string_new(); + mlx_vector_string_append_value(inputs, "x"); + mlx_vector_string_append_value(outputs, "y"); + mlx_vector_string_append_value(mutable_inputs, "x"); + mlx_vector_string_append_value(invalid_inputs, "missing"); + int result = 0; + try { + for (auto mode : {MLX_FAST_METAL_MATH_SAFE, MLX_FAST_METAL_MATH_RELAXED, MLX_FAST_METAL_MATH_FAST}) { + for (auto metadata : {empty, mutable_inputs}) { + auto kernel = mlx_fast_metal_kernel_new_with_options( + "options", inputs, outputs, "y[0] = x[0];", "", true, false, metadata, mode); + require(kernel.ctx != nullptr); + mlx_fast_metal_kernel_free(kernel); + } + } + auto legacy = mlx_fast_metal_kernel_new("legacy", inputs, outputs, "y[0] = x[0];", "", true, false); + require(legacy.ctx != nullptr); + mlx_fast_metal_kernel_free(legacy); + auto legacy_mutable = mlx_fast_metal_kernel_new_mutable( + "legacy_mutable", inputs, outputs, "y[0] = x[0];", "", true, false, mutable_inputs); + require(legacy_mutable.ctx != nullptr); + mlx_fast_metal_kernel_free(legacy_mutable); + require(errors == 0); + auto invalid = mlx_fast_metal_kernel_new_with_options( + "invalid", inputs, outputs, "y[0] = x[0];", "", true, false, empty, + static_cast<mlx_fast_metal_kernel_math_mode>(99)); + require(invalid.ctx == nullptr && errors == 1); + auto bad_mutable = mlx_fast_metal_kernel_new_with_options( + "bad_mutable", inputs, outputs, "y[0] = x[0];", "", true, false, + invalid_inputs, MLX_FAST_METAL_MATH_SAFE); + require(bad_mutable.ctx == nullptr && errors == 2); + std::puts("8 valid constructors and 2 rejected inputs passed; no GPU execution"); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + result = 1; + } + for (auto vector : {inputs, outputs, empty, mutable_inputs, invalid_inputs}) + mlx_vector_string_free(vector); + mlx_set_error_handler(nullptr, nullptr, nullptr); + return result; +}

MLX 0.32 made the default stream’s Metal command encoder thread-local, so a graph built on one thread and evaluated on another — Swift async/await continuations, actor executors — aborts with There is no Stream(gpu, N) in current thread. mlx_thread_unsafe_cpu_stream_new / mlx_thread_unsafe_gpu_stream_new expose the core’s new_thread_unsafe_stream, whose encoder is registered globally, letting mlx-swift restore a single process-wide default stream. “Thread-unsafe” means the caller serializes submission; it is not locked for concurrent multi-thread use. Upstream now binds the same core function as mlx_stream_new_thread_unsafe(dev). The fork keeps its two no-argument names because the Layr-Labs/mlx-swift Stream code calls them. Remove them when mlx-swift calls the upstream name.

diff --git ml-explore/mlx-c/mlx/c/stream.cpp Layr-Labs/mlx-c/mlx/c/stream.cpp index d55254e836fba78f93d3ee03e4b40b7ff296cc15..f32b0cb4a307d270a8cb6ecf0a2a6bcc58522e76 100644 --- ml-explore/mlx-c/mlx/c/stream.cpp +++ Layr-Labs/mlx-c/mlx/c/stream.cpp @@ -204,3 +204,21 @@ mlx_error(e.what()); return mlx_stream_new_(); } } +extern "C" mlx_stream mlx_thread_unsafe_cpu_stream_new(void) { + try { + return mlx_stream_new_( + mlx::core::new_thread_unsafe_stream(mlx::core::Device::DeviceType::cpu)); + } catch (std::exception& e) { + mlx_error(e.what()); + return mlx_stream_new_(); + } +} +extern "C" mlx_stream mlx_thread_unsafe_gpu_stream_new(void) { + try { + return mlx_stream_new_( + mlx::core::new_thread_unsafe_stream(mlx::core::Device::DeviceType::gpu)); + } catch (std::exception& e) { + mlx_error(e.what()); + return mlx_stream_new_(); + } +}
diff --git ml-explore/mlx-c/mlx/c/stream.h Layr-Labs/mlx-c/mlx/c/stream.h index 6df1a63c95b632ecd997de4aafebdf5848cafb9c..22dfad5322d0c4d4cb202ba711b847982b584b28 100644 --- ml-explore/mlx-c/mlx/c/stream.h +++ Layr-Labs/mlx-c/mlx/c/stream.h @@ -150,6 +150,21 @@ * Returns the current default GPU stream. */ mlx_stream mlx_default_gpu_stream_new(void);   +/** + * Returns a new CPU stream usable from ANY thread. + * + * Unlike the per-thread default stream, this stream's command encoder is + * registered globally (mlx::core::new_thread_unsafe_stream), so it stays valid + * when work hops threads (e.g. Swift async/await continuations). The caller is + * responsible for not submitting to it concurrently from multiple threads. + */ +mlx_stream mlx_thread_unsafe_cpu_stream_new(void); + +/** + * Returns a new GPU stream usable from ANY thread (see the CPU variant). + */ +mlx_stream mlx_thread_unsafe_gpu_stream_new(void); + /**@}*/   #ifdef __cplusplus

The gate that keeps this page honest: check_forkdiff.py fails CI when base.hash is not the merge-base with upstream, or when a file the fork changes is not described by a section above. FORKDIFF.md explains the day-to-day; the README links the page.

The fork-diff check and Pages renderer run only on Darkbloom Linux ARM64 runners, waiting for compatible capacity instead of using a hosted fallback. Both retain the upstream checks, rendering steps and 20-minute job limits. The protected Pages publication job stays on GitHub-hosted runners. FORKDIFF.md documents the queue and qualification limits.

The disabled native CodeQL workflow scans Actions, C/C++ and Python with the pinned CodeQL 2.27.4 ARM64 bundle and their existing default suites. It requires CODEQL_NATIVE=on after an operator switches default setup to advanced setup. The separate GitHub-hosted publisher validates the same run’s bounded, fingerprinted SARIF bundle, then uploads the original category identities without checking out or executing repository code. docs/ci-codeql-native.md records activation and rollback gates.

diff --git ml-explore/mlx-c/FORKDIFF.md Layr-Labs/mlx-c/FORKDIFF.md new file mode 100644 index 0000000000000000000000000000000000000000..4958ba31abf287b9af5258be9a98f4797cdcce71 --- /dev/null +++ Layr-Labs/mlx-c/FORKDIFF.md @@ -0,0 +1,98 @@ +# Fork diff: what this fork changes, and keeping that page honest + +This repository is a fork of [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c). +Everything it changes relative to upstream is published as a browsable page: + +**https://layr-labs.github.io/mlx-c/** + +The page is rendered by [`protolambda/forkdiff`](https://github.com/protolambda/forkdiff) +from [`fork.yaml`](fork.yaml) at the repo root, in the style of +[op-geth's go-ethereum fork diff](https://op-geth.optimism.io/). `fork.yaml` +groups the changed files into sections with a paragraph each, names the exact +upstream commit the fork is rebased onto (`base.hash`), and lists files that +are not code (`ignore`). Every push to `main` re-renders and redeploys it +(`.github/workflows/forkdiff-pages.yml`). + +**One-time setup.** GitHub Pages has to be switched on by a repo admin: +Settings → Pages → Source: **GitHub Actions**. The workflow token cannot do +this itself. Until it's done the deploy workflow still builds the page (kept +as a run artifact, `forkdiff-page`) and exits with a notice instead of failing. + +## Where CI runs + +The fork-diff check and page renderer run only on Darkbloom Linux ARM64 +runners. When capacity is busy they wait for a compatible runner; these two +jobs have no GitHub-hosted or Blacksmith fallback. Each retains its 20-minute +job timeout. The current approval also has a one-hour qualification lifetime, +which bounds waiting and execution; this is not a 24-hour native queue promise. + +The check still verifies the real upstream merge-base and renders the page. +The renderer still uploads a regular HTML artifact. The separate GitHub-hosted +job packages that artifact and publishes through the protected `github-pages` +environment. It does not run the renderer or repository code. +If the first deploy fails before it creates a deployment (the packaged artifact +is not listed yet), the job waits 20 seconds and tries once more. + +The native CodeQL workflow remains off until its separate operator activation +gates are complete; see [native CodeQL activation](docs/ci-codeql-native.md). + +## The gate + +A fork-diff page is only useful while it is true, and two things make it go +stale silently. `scripts/check_forkdiff.py` runs on every PR +(`.github/workflows/forkdiff-check.yml`) and fails on both: + +| Drift | Check | Why it matters | +|-------|-------|----------------| +| **Rebase onto newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a rebase the old base makes upstream's own commits look like fork changes: files that are not ours. | +| **New fork change nobody described** | every path in `git diff --name-only base.hash HEAD` must match a section glob or a global `ignore` | An undescribed file is a change the page can't explain. | +| **Section describing code we no longer carry** | every glob must match at least one changed path | Stale sections are as misleading as missing ones. | + +The check also renders the page, so a `fork.yaml` that forkdiff itself rejects +cannot merge. The deploy workflow runs the same check before publishing, so a +stale analysis is never served. + +## Day to day + +**Adding or changing fork files in a PR.** If the check lists uncovered files, +add each to the section that explains it in `fork.yaml` (or start a new +section with a short description). Files that are not code go under the +top-level `ignore`. Keep globs specific: a `mlx/**` catch-all would swallow +upstream's changes after a bad rebase and defeat the gate. + +**Merging newer upstream.** The fork merges upstream `main` with a merge +commit when the owner directs. Each merge moves `base.hash` and re-validates +every section. The gate fails with the new merge-base in its message: + +``` +git fetch https://github.com/ml-explore/mlx-c.git main:refs/remotes/upstream/main +git merge-base HEAD refs/remotes/upstream/main # → new base.hash +``` + +Set `base.hash` to that value, then run the check locally and fix what it +reports — usually files upstream absorbed (stale globs to delete) and files +that moved (globs to rename): + +``` +python3 -m pip install pyyaml +python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main +``` + +**Previewing the page locally** (Go 1.21+): + +``` +go run github.com/protolambda/forkdiff@v0.1.1 -repo . -fork fork.yaml -out tmp/index.html +open tmp/index.html +``` + +## Design notes + +- `base.hash` is a full 40-hex commit id, never a branch name: a symbolic base + would move underneath the page and the gate alike. +- Section `ignore` lists count as coverage (forkdiff still lists those files, + grayed out); the top-level `ignore` is for things that aren't code at all. +- The glob semantics are forkdiff's: `*` and `?` stop at `/`, `**` spans + directories (and may match none), `[!x]` negates a class. +- The check is pure git + PyYAML so the same command runs locally and in CI. + It is shared verbatim across the Layr-Labs MLX forks (`mlx`, `mlx-c`, + `mlx-swift`, `mlx-swift-lm`).
diff --git ml-explore/mlx-c/README.md Layr-Labs/mlx-c/README.md index d57abc96e88b8a25ba4cc33f6475d85728c7baf0..5901c9ae51bc240f0ef52db3feee16f6aae36910 100644 --- ml-explore/mlx-c/README.md +++ Layr-Labs/mlx-c/README.md @@ -1,5 +1,7 @@ # MLX C   +> **This is a fork.** `Layr-Labs/mlx-c` tracks [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c) and adds the C entry points Layr-Labs' Swift inference stack needs from its forked MLX core. Everything changed relative to upstream is published as a fork diff at **https://layr-labs.github.io/mlx-c/**, described in [`fork.yaml`](fork.yaml) and kept honest by CI — see [FORKDIFF.md](FORKDIFF.md). + MLX C is a C API for [MLX](https://github.com/ml-explore/mlx).   MLX is an array framework for machine learning on Apple silicon. MLX C expands @@ -41,3 +43,19 @@ We are grateful for all of [our contributors](ACKNOWLEDGMENTS.md#Individual-Contributors). If you contribute to MLX C and wish to be acknowledged, please add your name to the list in your pull request. + +## Bounded JACCL startup waits + +The initialized-group C API offers `mlx_distributed_group_begin_startup_wait_budget` +and `mlx_distributed_group_end_startup_wait_budget`. Begin accepts 1..900000 ms; +the monotonic deadline includes loading and cannot be renewed by progress or a +second begin. Drain queued work and serialize scheduling around both operations. +End requires an idle, open, unexpired active budget and restores the original +idle policy. Null handles, invalid bounds, unsupported backends and closed groups +are refused through the installed error handler with a nonzero return value. +No call clears failure, changes memory caps or authenticates transport. The +embedding runtime still owns hard startup cancellation and readiness publication. + +These entry points require the matching core startup-wait implementation; the +CMake core pin carries it. Standalone CPU regression instructions are in +`tests/standalone/README.md`; they do not qualify native RDMA or GPU execution.
diff --git ml-explore/mlx-c/docs/ci-codeql-native.md Layr-Labs/mlx-c/docs/ci-codeql-native.md new file mode 100644 index 0000000000000000000000000000000000000000..8128ab3e03efa2583d682e1ce82cfffd57e6b7e9 --- /dev/null +++ Layr-Labs/mlx-c/docs/ci-codeql-native.md @@ -0,0 +1,55 @@ +# Native CodeQL activation + +`codeql-native.yml` is inactive unless the repository variable `CODEQL_NATIVE` +is exactly `on`. Merging the workflow does not switch GitHub's default setup or +change its security coverage. The operator must review that switch separately. + +The scan job has `contents: read` only. It runs the pinned CodeQL2.27.4 ARM64 +bundle against the Actions event commit, without building repository code. It +uses the same default query suites for Actions, C/C++ and Python. The Darkbloom +route has one `codeql` Linux ARM64 lane; hosted fallback is also ARM64. + +The separate GitHub-hosted upload job has only `contents: read`, `actions: read` +and `security-events: write`. It does not check out or run repository code. Its +only inputs are the same run's three SARIF files and a bounded manifest, checked +against the event repository, commit, ref, run and attempt. Unexpected files, +symlinks, changed hashes, different tools and missing fingerprints are refused. +The official pinned uploader preserves these categories: + +- `/language:actions` +- `/language:c-cpp` +- `/language:python` + +Native CodeQL already records the primary-line fingerprints. The uploader gets +an empty directory as `checkout_path`; it preserves the supplied fingerprints +and uses the Actions event SHA/ref. No source files are transferred to this job. +GitHub permits code-scanning uploads for `pull_request` runs, including runs with +read-only token scopes. The uploader ignores ref/SHA overrides for fork PRs. + +## Operator gates + +1. Keep `CODEQL_NATIVE` unset/off while reviewing and merging this source. Verify + default setup remains enabled and its three analyses are current. Record its + settings and latest successful analysis IDs for rollback. +2. Approve the single `codeql` lane for the reviewed Linux image and its existing + network template. Confirm the image/worker and capacity before switching. +3. Switch GitHub from default to advanced setup with admin authorization. Default + setup blocks CodeQL API uploads, so it must not remain the active uploader. + Ensure the new workflow is enabled, then set `CODEQL_NATIVE=on` and dispatch + `main`. The weekly schedule and subsequent main pushes/PRs use this workflow. +4. Require successful native compute, all three processed GitHub analyses on the + expected commit/categories, and physical runner retirement. Also qualify a + fork PR upload using its merge ref and unprivileged PR token. An artifact-only + scan does not prove the upload/alert integration. +5. After the new analyses are healthy, review any stale default-setup analysis + configuration before removing it; category names alone do not merge distinct + workflow configurations. Never delete the last working coverage first. + +Rollback: turn `CODEQL_NATIVE` off, restore the recorded default-setup settings, +and require its three initial analyses to succeed. Do not leave both modes active. + +References: + +- [Default versus advanced setup](https://docs.github.com/en/code-security/reference/code-scanning/troubleshoot-analysis-errors/results-different-than-expected) +- [PR uploads with read-only scopes](https://docs.github.com/en/enterprise-cloud@latest/code-security/reference/code-scanning/troubleshoot-analysis-errors/resource-not-accessible) +- [Pinned uploader inputs](https://github.com/github/codeql-action/blob/33d7b85da1a04171e211befe2c739303b9a4c066/upload-sarif/action.yml)
diff --git ml-explore/mlx-c/scripts/check_forkdiff.py Layr-Labs/mlx-c/scripts/check_forkdiff.py new file mode 100644 index 0000000000000000000000000000000000000000..8e10e811d614f83c414a1d323ddc64c7e6a3193b --- /dev/null +++ Layr-Labs/mlx-c/scripts/check_forkdiff.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Gate: ``fork.yaml`` must describe this fork as it is *now*. + +The fork-diff page (rendered with protolambda/forkdiff and published on GitHub +Pages) is only useful while it is true. Two things make it go stale silently: + +1. **A rebase onto newer upstream.** ``base.hash`` still points at the old + upstream commit, so the page shows upstream's own changes as if the fork + made them. This script requires ``base.hash`` to equal + ``git merge-base HEAD <upstream>``; a rebase moves the merge-base, and the + gate stays red until the hash is bumped. +2. **A new fork change nobody described.** Every path in + ``git diff --name-only base.hash HEAD`` must match a glob in some section + (or a global ``ignore``), and every glob must still match something — a + section describing code the fork no longer carries is as misleading as a + missing one. + +Both are pure git + YAML, so the same check runs locally:: + + python3 scripts/check_forkdiff.py # coverage only + python3 scripts/check_forkdiff.py --upstream-ref upstream/main + +Exit status is non-zero on any violation. ``--review-status-out`` writes the +JSON the CI comment synthesizer consumes (same shape as history-check). +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path +from typing import Iterable + +import yaml + +GLOB_CLASS_RE = re.compile(r"\[([^\]]*)\]") + + +def glob_to_regex(glob: str) -> re.Pattern[str]: + """Translate a forkdiff glob into a regex over the repo-relative path. + + Semantics follow the doublestar rules forkdiff uses: ``*`` and ``?`` never + cross a ``/``; ``**`` matches any number of directories (``a/**/b`` also + matches ``a/b``); ``[...]`` character classes pass through, with a leading + ``!`` meaning negation. + """ + out: list[str] = [] + i = 0 + while i < len(glob): + c = glob[i] + if c == "*": + if glob.startswith("**", i): + if glob.startswith("**/", i): + out.append("(?:.*/)?") + i += 3 + continue + out.append(".*") + i += 2 + continue + out.append("[^/]*") + elif c == "?": + out.append("[^/]") + elif c == "[": + end = glob.find("]", i + 1) + if end == -1: + out.append(re.escape(c)) + else: + cls = glob[i + 1 : end] + if cls.startswith("!"): + cls = "^" + cls[1:] + out.append("[" + cls + "]") + i = end + 1 + continue + else: + out.append(re.escape(c)) + i += 1 + return re.compile("^" + "".join(out) + "$") + + +def collect_globs(node: dict, path: str = "def") -> list[tuple[str, str]]: + """Every glob in the section tree as ``(section path, glob)``. + + A section's ``ignore`` list counts as coverage too: forkdiff still lists + those files under the section (grayed out), so they are described. + """ + found: list[tuple[str, str]] = [] + title = node.get("title") or "(untitled)" + here = f"{path} › {title}" if path != "def" else title + for g in node.get("globs") or []: + found.append((here, str(g))) + for g in node.get("ignore") or []: + found.append((here, str(g))) + for child in node.get("sub") or []: + found.extend(collect_globs(child, here)) + return found + + +def git(*args: str, cwd: Path) -> str: + result = subprocess.run( + ["git", *args], cwd=cwd, capture_output=True, text=True, check=False + ) + if result.returncode != 0: + raise RuntimeError(f"git {' '.join(args)} failed: {result.stderr.strip()}") + return result.stdout.strip() + + +def changed_paths(repo: Path, base: str, head: str) -> list[str]: + out = git("diff", "--name-only", f"{base}..{head}", cwd=repo) + return [line for line in out.splitlines() if line] + + +def check_coverage( + paths: Iterable[str], globs: list[tuple[str, str]] +) -> tuple[list[str], list[tuple[str, str]], dict[str, int]]: + """Return ``(uncovered paths, stale globs, matches per glob)``.""" + compiled = [(section, g, glob_to_regex(g)) for section, g in globs] + hits: dict[str, int] = {g: 0 for _, g in globs} + uncovered: list[str] = [] + for p in paths: + matched = False + for _, g, rx in compiled: + if rx.match(p): + hits[g] += 1 + matched = True + if not matched: + uncovered.append(p) + stale = [(section, g) for section, g in globs if hits[g] == 0] + return uncovered, stale, hits + + +def check_base(repo: Path, base: str, head: str, upstream_ref: str | None) -> list[str]: + problems: list[str] = [] + if not re.fullmatch(r"[0-9a-f]{40}", base): + problems.append( + f"base.hash must be a full 40-hex commit id, got {base!r} — a short or " + "symbolic ref would silently move under the page." + ) + return problems + try: + git("cat-file", "-e", f"{base}^{{commit}}", cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not present in this repository. The fork must " + "sit on top of it (fetch upstream if the clone is shallow)." + ) + return problems + if upstream_ref is None: + return problems + try: + git("merge-base", "--is-ancestor", base, upstream_ref, cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must name " + "a commit on upstream main, not a fork commit." + ) + merge_base = git("merge-base", head, upstream_ref, cwd=repo) + if merge_base != base: + problems.append( + f"base.hash {base[:12]} != merge-base({head}, {upstream_ref}) = " + f"{merge_base[:12]}. The fork was rebased onto newer upstream; update " + "fork.yaml's base.hash and re-describe the sections (see docs/forkdiff.md)." + ) + return problems + + +def review_status(problems: list[str], detail: str) -> list[dict]: + if not problems: + return [] + return [ + { + "source": "fork diff analysis", + "results": [ + { + "kind": "action_required", + "title": "fork.yaml no longer describes the fork", + "summary": problems[0] + if len(problems) == 1 + else f"{len(problems)} issues: {problems[0]}", + "detail": detail, + "how_to_fix": ( + "See docs/forkdiff.md. After a rebase: set base.hash to " + "`git merge-base HEAD upstream/main`. For new files: add them to " + "the section that explains them (or to a global `ignore` if they " + "are not code). Then run `python3 scripts/check_forkdiff.py " + "--upstream-ref upstream/main` locally." + ), + } + ], + } + ] + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--repo", default=".", help="path to the fork checkout") + ap.add_argument("--fork", default="fork.yaml", help="fork page definition") + ap.add_argument("--head", default="HEAD", help="the fork revision to describe") + ap.add_argument( + "--upstream-ref", + default=None, + help="a ref holding upstream main (e.g. refs/remotes/upstream/main); " + "enables the merge-base check", + ) + ap.add_argument("--review-status-out", default=None, help="write review-status JSON here") + args = ap.parse_args(argv) + + repo = Path(args.repo).resolve() + fork_path = repo / args.fork + spec = yaml.safe_load(fork_path.read_text(encoding="utf-8")) or {} + base = str((spec.get("base") or {}).get("hash") or "").strip() + problems: list[str] = [] + lines: list[str] = [] + + problems += check_base(repo, base, args.head, args.upstream_ref) + + globs = collect_globs(spec.get("def") or {}) + globs += [("(global ignore)", str(g)) for g in spec.get("ignore") or []] + + paths: list[str] = [] + if re.fullmatch(r"[0-9a-f]{40}", base): + try: + paths = changed_paths(repo, base, args.head) + except RuntimeError as exc: + problems.append(str(exc)) + + uncovered, stale, hits = check_coverage(paths, globs) + if uncovered: + problems.append( + f"{len(uncovered)} changed file(s) are not described by any fork.yaml section" + ) + lines.append("Uncovered files (add each to the section that explains it):") + lines += [f" - {p}" for p in uncovered] + if stale: + problems.append(f"{len(stale)} glob(s) match nothing the fork changes") + lines.append("Stale globs (the fork no longer changes anything they name):") + lines += [f" - {g} [{section}]" for section, g in stale] + + covered = len(paths) - len(uncovered) + print(f"fork.yaml: base {base[:12]} head {args.head} changed files {len(paths)} " + f"described {covered} sections+ignores {len(globs)}") + if args.upstream_ref is None: + print(" (no --upstream-ref: merge-base check skipped)") + for line in lines: + print(line) + for p in problems: + print(f"::error::{p}") + + if args.review_status_out: + Path(args.review_status_out).write_text( + json.dumps(review_status(problems, "\n".join(lines))), encoding="utf-8" + ) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main())

The feature branch carries the bounded owner-provided bootstrap exchange, sealed two-rank all-sum bridge (whole-frame and streamed per-piece codec callbacks, mlx_distributed_set_streamed_seal_codec), and the sealed two-rank reduce-scatter and all-gather (mlx_distributed_reduce_scatter_sealed, mlx_distributed_all_gather_sealed) on the same codec and counter. Bootstrap validates dimensions and sequences but its owner authenticates the channel. Sealed collective callbacks retain their existing no-reentry contract. These pre-existing feature changes remain present when adding startup waits.

diff --git ml-explore/mlx-c/mlx/c/distributed_bootstrap.cpp Layr-Labs/mlx-c/mlx/c/distributed_bootstrap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e7cd85d99f2984790efe0f85e87ef69564a79f9 --- /dev/null +++ Layr-Labs/mlx-c/mlx/c/distributed_bootstrap.cpp @@ -0,0 +1,42 @@ +#include <memory> + +#include "mlx/c/distributed_group.h" +#include "mlx/c/error.h" +#include "mlx/c/private/distributed_bootstrap.h" +#include "mlx/c/private/mlx.h" + +extern "C" int mlx_distributed_init_jaccl_with_bootstrap( + mlx_distributed_group* res, + int expected_rank, + int expected_size, + size_t maximum_rank_bytes, + size_t maximum_total_bytes, + mlx_distributed_bootstrap_gather gather, + void* context, + mlx_distributed_bootstrap_release release_context) { + try { + mlx::c::detail::BootstrapContext owner(context, release_context); + if (!res) { + throw std::invalid_argument("[distributed] Missing owner bootstrap result"); + } + auto state = std::make_shared<mlx::c::detail::BootstrapState>( + std::move(owner), expected_rank, expected_size, + maximum_rank_bytes, maximum_total_bytes, gather); + auto group = mlx::core::distributed::init( + true, "jaccl", [state](int rank, int size) { + state->bind(rank, size); + return [state](const char* src, char* dst, size_t n_bytes) { + state->all_gather(src, dst, n_bytes); + }; + }); + state->require_fresh(); + mlx_distributed_group_set_(*res, std::move(group)); + return 0; + } catch (std::exception& error) { + mlx_error(error.what()); + return 1; + } catch (...) { + mlx_error("[distributed] Unknown owner bootstrap failure"); + return 1; + } +}
diff --git ml-explore/mlx-c/mlx/c/distributed_group.h Layr-Labs/mlx-c/mlx/c/distributed_group.h index bfbaa80ebc06bc9b686914872d2c6d458874d83f..af4dfb7f5d76d3c2bbd14bcb0c8559ed01a4ebe3 100644 --- ml-explore/mlx-c/mlx/c/distributed_group.h +++ Layr-Labs/mlx-c/mlx/c/distributed_group.h @@ -4,7 +4,10 @@ #ifndef MLX_DISTRIBUTED_GROUP_H #define MLX_DISTRIBUTED_GROUP_H   #include <stdbool.h> +#include <stddef.h> +#include <stdint.h>   +#include "mlx/c/array.h" #include "mlx/c/stream.h"   #ifdef __cplusplus @@ -40,6 +43,117 @@ int mlx_distributed_init( mlx_distributed_group* res, bool strict, const char* bk /* may be null */); + +/** + * Synchronous owner-supplied JACCL bootstrap exchange. Return zero only after + * writing exactly dst_bytes, in rank order. Pointers must not escape the call. + * Callbacks must not throw or reenter MLX. The owner bounds waits and authenticates + * its channel, epoch, rank, sequence, lengths and native topology. + */ +typedef int (*mlx_distributed_bootstrap_gather)( + void* context, int rank, int size, uint64_t sequence, + const char* src, size_t src_bytes, char* dst, size_t dst_bytes); +typedef void (*mlx_distributed_bootstrap_release)(void* context); + +/** + * Strict JACCL initialization through an owner callback, without TCPAllGather. + * Existing cached JACCL initialization is rejected; it is not reauthenticated. + * Both callbacks are required. When release_context is non-null, this call + * consumes one context reference on every path. On success, release runs when + * the last reference to the native group is dropped; the backend cache and + * every group handle and graph that uses the group hold one, so in practice + * release runs at process exit. Do not call this concurrently with any other + * distributed initialization: the native backend cache is not locked. + * Callback failure is permanent. This API itself does not authenticate bytes. + * Bounds: 2..64 ranks, 1..1MiB per rank, at most 8MiB total; the total bound + * must fit all ranks at their per-rank bound. Use a fresh worker per epoch. + */ +int mlx_distributed_init_jaccl_with_bootstrap( + mlx_distributed_group* res, int expected_rank, int expected_size, + size_t maximum_rank_bytes, size_t maximum_total_bytes, + mlx_distributed_bootstrap_gather gather, void* context, + mlx_distributed_bootstrap_release release_context); + +/** + * Sealed all-sum (Darkbloom fork, mlx/distributed/sealed.h): the two ranks' + * partials cross the link only as frames the installed codec seals and opens + * (a frame is plaintext bytes + overhead). Callbacks run on the CPU stream's + * thread, must not reenter MLX and must not throw; nonzero refuses (the + * evaluation fails). counter advances by one per evaluated sealed collective + * (all-sum, reduce-scatter, all-gather), identically on both ranks. It is one + * sequence per process: it starts at 0 in each process and is not reset when + * a codec is installed, so keys must be fresh per process for (key, counter) + * to stay unique. A null seal or a null open removes the codec and returns 0. + * Each graph copies the codec installed when the graph is built, context + * included: context must stay valid until every such graph is evaluated or + * freed, even after the codec is removed or replaced. + */ +typedef int (*mlx_distributed_seal_fn)( + void* context, const void* plaintext, size_t bytes, void* frame, uint64_t counter); +typedef int (*mlx_distributed_open_fn)( + void* context, const void* frame, size_t bytes, void* plaintext, uint64_t counter, int peer); +int mlx_distributed_set_seal_codec( + mlx_distributed_seal_fn seal, mlx_distributed_open_fn open, void* context, size_t overhead); +/** + * The same codec with per-piece callbacks. On a two-rank JACCL mesh a partial + * then crosses as pieces of piece_bytes plaintext bytes (the last can be + * shorter), each sealed as its ciphertext then a 16-byte tag, in order. One + * CPU-stream task sends each piece when it is sealed and opens and adds each + * peer piece when it lands. Other groups use seal and open. The piece + * callbacks run at the same time on worker threads, in any order within one + * counter; they must not reenter MLX or throw; nonzero refuses (the + * evaluation fails). piece_bytes: a multiple of 16 in [4 KiB, 16 MiB]. + */ +typedef int (*mlx_distributed_seal_piece_fn)( + void* context, const void* plaintext, size_t length, void* sealed, + uint64_t counter, uint32_t piece, uint32_t pieces, size_t total); +typedef int (*mlx_distributed_open_piece_fn)( + void* context, const void* sealed, size_t length, void* plaintext, + uint64_t counter, uint32_t piece, uint32_t pieces, size_t total, int peer); +int mlx_distributed_set_streamed_seal_codec( + mlx_distributed_seal_fn seal, mlx_distributed_open_fn open, + mlx_distributed_seal_piece_fn seal_piece, mlx_distributed_open_piece_fn open_piece, + void* context, size_t overhead, size_t piece_bytes); +int mlx_distributed_all_sum_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s); +/** + * Two ranks, x shaped [1, T, ...]: rank r's half of the sealed sum (rows + * r * T / 2 ..< (r + 1) * T / 2, T even), added in rank order as + * mlx_distributed_all_sum_sealed adds; and the sealed all-gather of the + * ranks' [1, T, ...] rows into [1, 2T, ...], rank 0's first. Same codec and + * counters as the sealed all-sum, half its bytes each. + */ +int mlx_distributed_reduce_scatter_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s); +int mlx_distributed_all_gather_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s); + +/** + * Opt in to one bounded JACCL startup wait on this initialized group. + * timeout_ms must be 1..900000; progress cannot renew its absolute deadline. + * Drain queued MLX work and serialize scheduling around begin/end; require + * no running local group operation. Unsupported backends, repeated begin, + * and begin after end refuse. This does not change the global + * progress timeout, memory caps, authentication, or failed-group state. + */ +int mlx_distributed_group_begin_startup_wait_budget( + mlx_distributed_group group, + int64_t timeout_ms); + +/** + * End the one-shot startup budget before publishing READY. Subsequent calls + * use the original progress guard. A closed group is never reopened. + */ +int mlx_distributed_group_end_startup_wait_budget(mlx_distributed_group group);   /** * Get the rank.
diff --git ml-explore/mlx-c/mlx/c/distributed_sealed.cpp Layr-Labs/mlx-c/mlx/c/distributed_sealed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72b2051409952ed6b8acb787b8f18f3902fce86a --- /dev/null +++ Layr-Labs/mlx-c/mlx/c/distributed_sealed.cpp @@ -0,0 +1,101 @@ +/* Copyright © 2026 Darkbloom. */ +/* Hand-written (fork): the sealed all-sum C API. */ + +#include "mlx/c/distributed_group.h" +#include "mlx/c/error.h" +#include "mlx/c/private/mlx.h" +#include "mlx/distributed/sealed.h" + +extern "C" int mlx_distributed_set_seal_codec( + mlx_distributed_seal_fn seal, mlx_distributed_open_fn open, void* context, size_t overhead) { + try { + mlx::core::distributed::SealCodec codec; + codec.seal = seal; + codec.open = open; + codec.ctx = context; + codec.overhead = overhead; + mlx::core::distributed::set_seal_codec(codec); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_distributed_set_streamed_seal_codec( + mlx_distributed_seal_fn seal, mlx_distributed_open_fn open, + mlx_distributed_seal_piece_fn seal_piece, mlx_distributed_open_piece_fn open_piece, + void* context, size_t overhead, size_t piece_bytes) { + try { + mlx::core::distributed::SealCodec codec; + codec.seal = seal; + codec.open = open; + codec.ctx = context; + codec.overhead = overhead; + codec.seal_piece = seal_piece; + codec.open_piece = open_piece; + codec.piece_bytes = piece_bytes; + mlx::core::distributed::set_seal_codec(codec); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_distributed_all_sum_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s) { + try { + mlx_array_set_( + *res, + mlx::core::distributed::all_sum_sealed( + mlx_array_get_(x), + (group.ctx ? std::make_optional(mlx_distributed_group_get_(group)) : std::nullopt), + mlx_stream_get_(s))); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_distributed_reduce_scatter_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s) { + try { + mlx_array_set_( + *res, + mlx::core::distributed::reduce_scatter_sealed( + mlx_array_get_(x), + (group.ctx ? std::make_optional(mlx_distributed_group_get_(group)) : std::nullopt), + mlx_stream_get_(s))); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +} + +extern "C" int mlx_distributed_all_gather_sealed( + mlx_array* res, + const mlx_array x, + const mlx_distributed_group group /* may be null */, + const mlx_stream s) { + try { + mlx_array_set_( + *res, + mlx::core::distributed::all_gather_sealed( + mlx_array_get_(x), + (group.ctx ? std::make_optional(mlx_distributed_group_get_(group)) : std::nullopt), + mlx_stream_get_(s))); + } catch (std::exception& e) { + mlx_error(e.what()); + return 1; + } + return 0; +}
diff --git ml-explore/mlx-c/mlx/c/private/distributed_bootstrap.h Layr-Labs/mlx-c/mlx/c/private/distributed_bootstrap.h new file mode 100644 index 0000000000000000000000000000000000000000..645b7ebc9dbd1ddab13b634f51838087e5269b9f --- /dev/null +++ Layr-Labs/mlx-c/mlx/c/private/distributed_bootstrap.h @@ -0,0 +1,121 @@ +#pragma once + +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <mutex> +#include <stdexcept> +#include <utility> +#include <vector> + +namespace mlx::c::detail { + +using BootstrapGather = int (*)( + void*, int, int, uint64_t, const char*, size_t, char*, size_t); +using BootstrapRelease = void (*)(void*); + +class BootstrapContext { + public: + BootstrapContext(void* value, BootstrapRelease release) + : value_(value), release_(release) {} + BootstrapContext(const BootstrapContext&) = delete; + BootstrapContext& operator=(const BootstrapContext&) = delete; + BootstrapContext(BootstrapContext&& other) noexcept + : value_(other.value_), release_(other.release_) { + other.release_ = nullptr; + } + ~BootstrapContext() { + if (release_) { + release_(value_); + } + } + void* value() const { return value_; } + bool owned() const { return release_ != nullptr; } + + private: + void* value_; + BootstrapRelease release_; +}; + +class BootstrapState { + public: + BootstrapState( + BootstrapContext context, + int rank, + int size, + size_t maximum_rank_bytes, + size_t maximum_total_bytes, + BootstrapGather gather) + : context_(std::move(context)), + rank_(rank), + size_(size), + maximum_rank_bytes_(maximum_rank_bytes), + maximum_total_bytes_(maximum_total_bytes), + gather_(gather) { + if (!context_.owned() || !gather_ || rank < 0 || rank >= size || + size < 2 || size > 64 || maximum_rank_bytes == 0 || + maximum_rank_bytes > 1024 * 1024 || maximum_total_bytes == 0 || + maximum_total_bytes > 8 * 1024 * 1024 || + maximum_rank_bytes > maximum_total_bytes / static_cast<size_t>(size)) { + throw std::invalid_argument("[distributed] Invalid owner bootstrap bounds"); + } + } + + void bind(int rank, int size) { + std::lock_guard<std::mutex> lock(mutex_); + if (failed_ || bound_ || rank != rank_ || size != size_) { + failed_ = true; + throw std::runtime_error("[distributed] Owner bootstrap rank or size differs"); + } + bound_ = true; + } + + void require_fresh() { + std::lock_guard<std::mutex> lock(mutex_); + if (!bound_ || failed_) { + throw std::runtime_error("[distributed] Owner bootstrap requires fresh JACCL initialization"); + } + } + + void all_gather(const char* src, char* dst, size_t n_bytes) { + std::lock_guard<std::mutex> lock(mutex_); + try { + if (failed_ || !bound_ || !src || !dst || n_bytes == 0 || + n_bytes > maximum_rank_bytes_ || + n_bytes > maximum_total_bytes_ / static_cast<size_t>(size_) || + sequence_ == std::numeric_limits<uint64_t>::max()) { + throw std::runtime_error("[distributed] Owner bootstrap contribution is outside bounds"); + } + const size_t total = n_bytes * static_cast<size_t>(size_); + std::vector<char> local(src, src + n_bytes); + std::vector<char> gathered(total); + if (gather_(context_.value(), rank_, size_, sequence_, local.data(), + n_bytes, gathered.data(), total) != 0) { + throw std::runtime_error("[distributed] Owner bootstrap exchange failed"); + } + if (std::memcmp(local.data(), gathered.data() + rank_ * n_bytes, n_bytes) != 0) { + throw std::runtime_error("[distributed] Owner bootstrap local contribution differs"); + } + std::memcpy(dst, gathered.data(), total); + ++sequence_; + } catch (...) { + failed_ = true; + throw; + } + } + + private: + BootstrapContext context_; + int rank_; + int size_; + size_t maximum_rank_bytes_; + size_t maximum_total_bytes_; + BootstrapGather gather_; + std::mutex mutex_; + uint64_t sequence_{0}; + bool bound_{false}; + bool failed_{false}; +}; + +} // namespace mlx::c::detail

The begin/end startup-wait C entry points validate group handles and finite 1..900000 ms bounds, then forward to the matching core Group API. Exceptions report through the existing error handler and return failure. The embedding runtime drains work, serializes transitions and retains cancellation, authentication and memory safeguards. CPU-only standalone tests cover argument refusal, forwarding and unsupported backends.

diff --git ml-explore/mlx-c/mlx/c/distributed_group.cpp Layr-Labs/mlx-c/mlx/c/distributed_group.cpp index d0db5d5aea6aa72a3c41ae06c97f9c25d0e67559..023e2178ede4659e719b25aa77806b5c1486ee34 100644 --- ml-explore/mlx-c/mlx/c/distributed_group.cpp +++ Layr-Labs/mlx-c/mlx/c/distributed_group.cpp @@ -41,6 +41,37 @@ return 1; } }   +extern "C" int mlx_distributed_group_begin_startup_wait_budget( + mlx_distributed_group group, + int64_t timeout_ms) { + if (!group.ctx || timeout_ms <= 0 || timeout_ms > 900000) { + mlx_error("Startup wait requires an initialized group and 1..900000 ms"); + return 1; + } + try { + mlx_distributed_group_get_(group).begin_startup_wait_budget(timeout_ms); + return 0; + } catch (std::exception& e) { + mlx_error("%s", e.what()); + return 1; + } +} + +extern "C" int mlx_distributed_group_end_startup_wait_budget( + mlx_distributed_group group) { + if (!group.ctx) { + mlx_error("Startup wait requires an initialized group"); + return 1; + } + try { + mlx_distributed_group_get_(group).end_startup_wait_budget(); + return 0; + } catch (std::exception& e) { + mlx_error("%s", e.what()); + return 1; + } +} + extern "C" int mlx_distributed_group_rank(mlx_distributed_group group) { try { return mlx_distributed_group_get_(group).rank();
diff --git ml-explore/mlx-c/tests/standalone/README.md Layr-Labs/mlx-c/tests/standalone/README.md new file mode 100644 index 0000000000000000000000000000000000000000..49e41537b379a2c1b8bd5ed7d43dc98852cbb16f --- /dev/null +++ Layr-Labs/mlx-c/tests/standalone/README.md @@ -0,0 +1,16 @@ +# Startup-wait C bridge CPU regression + +Run from the repository root against the matching core startup-wait source: + +```sh +python3 tests/standalone/run_startup_wait_tests.py --core /path/to/mlx --output /path/to/isolated-output +``` + +The test compiles the real C entry points, error handler and core Group +forwarding with address/undefined-behavior sanitizers. A test GroupImpl uses the +real one-shot policy. It checks C ABI types, null/invalid handles, finite duration +bounds, exactly-once forwarding, running/ended/failed/unsupported refusal and +error-handler reporting. Dead stripping excludes unrelated backend operations; +no fake core symbols, RDMA service, Metal framework or GPU evaluator is linked. +This lightweight runner uses the macOS linker and does not qualify native RDMA, +actual hardware, or the full C library.
diff --git ml-explore/mlx-c/tests/standalone/run_startup_wait_tests.py Layr-Labs/mlx-c/tests/standalone/run_startup_wait_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..6140c7a02e9565115d9f06d71c37f8c93133a2c5 --- /dev/null +++ Layr-Labs/mlx-c/tests/standalone/run_startup_wait_tests.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Build the real C bridge and core forwarding without a native backend.""" +import argparse +import pathlib +import subprocess +import sys + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--core", type=pathlib.Path, required=True) +parser.add_argument("--output", type=pathlib.Path, required=True) +parser.add_argument("--compiler", default="clang++") +args = parser.parse_args() +root = pathlib.Path(__file__).resolve().parents[2] +core = args.core.resolve() +output = args.output.resolve() +output.mkdir(parents=True, exist_ok=True) +# Dead stripping keeps only the tested entry points. No fake core symbols, +# RDMA library, Metal framework or GPU evaluator are linked. +command = [ + args.compiler, "-std=c++20", "-O1", "-g", + "-fsanitize=address,undefined", "-fno-omit-frame-pointer", + "-ffunction-sections", "-fdata-sections", "-Wl,-dead_strip", + "-I" + str(root), "-I" + str(core), + "-I" + str(core / "mlx/distributed/jaccl/lib"), + str(root / "tests/standalone/startup_wait_budget.cpp"), + str(root / "mlx/c/distributed_group.cpp"), + str(root / "mlx/c/error.cpp"), + str(core / "mlx/distributed/distributed.cpp"), + "-o", str(output / "startup-wait-c-bridge"), +] +subprocess.run(command, check=True, timeout=120) +subprocess.run([str(output / "startup-wait-c-bridge")], check=True, timeout=30)
diff --git ml-explore/mlx-c/tests/standalone/startup_wait_budget.cpp Layr-Labs/mlx-c/tests/standalone/startup_wait_budget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2de73efa2055c9398248babcedfc28147f46227 --- /dev/null +++ Layr-Labs/mlx-c/tests/standalone/startup_wait_budget.cpp @@ -0,0 +1,183 @@ +/* Copyright © 2026 Apple Inc. */ + +#include <atomic> +#include <iostream> +#include <limits> +#include <memory> +#include <stdexcept> +#include <string> +#include <type_traits> + +#include "jaccl/startup_wait_budget.h" +#include "mlx/c/distributed_group.h" +#include "mlx/c/error.h" +#include "mlx/distributed/distributed_impl.h" + +using namespace mlx::core; +using namespace mlx::core::distributed; + +static_assert(std::is_same_v< + decltype(&mlx_distributed_group_begin_startup_wait_budget), + int (*)(mlx_distributed_group, int64_t)>); +static_assert(std::is_same_v< + decltype(&mlx_distributed_group_end_startup_wait_budget), + int (*)(mlx_distributed_group)>); + +class Unsupported : public detail::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<detail::GroupImpl> split(int, int) override { + return nullptr; + } + void all_sum(const array&, array&, Stream) override {} + void all_max(const array&, array&, Stream) override {} + void all_min(const array&, array&, Stream) override {} + void all_gather(const array&, array&, Stream) override {} + void sum_scatter(const array&, array&, Stream) override {} + void send(const array&, int, Stream) override {} + void recv(array&, int, Stream) override {} +}; + +class BudgetGroup : public Unsupported { + public: + void begin_startup_wait_budget(int64_t timeout_ms) override { + ++begins; + policy.begin(timeout_ms, failed); + } + void end_startup_wait_budget() override { + ++ends; + policy.end(failed); + } + jaccl::StartupWaitBudget policy; + std::atomic<bool> failed{false}; + int begins{0}; + int ends{0}; +}; + +std::string error; +int errors = 0; +void handler(const char* text, void*) { + error = text; + ++errors; +} +void require(bool condition, const char* text) { + if (!condition) { + throw std::runtime_error(text); + } +} +template <typename Fn> +void refuses(Fn fn, const char* text) { + const int before = errors; + error.clear(); + require(fn() != 0, "C entry point accepted invalid operation"); + require(errors == before + 1, "error handler was not called exactly once"); + require(error.find(text) != std::string::npos, "wrong refusal diagnostic"); +} + +int main() { + try { + mlx_set_error_handler(handler, nullptr, nullptr); + mlx_distributed_group empty{nullptr}; + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget(empty, 1); + }, + "initialized"); + refuses( + [&] { return mlx_distributed_group_end_startup_wait_budget(empty); }, + "initialized"); + auto backend = std::make_shared<BudgetGroup>(); + Group group(backend); + mlx_distributed_group handle{&group}; + for (int64_t timeout : + {int64_t(-1), + int64_t(0), + int64_t(900001), + std::numeric_limits<int64_t>::max(), + std::numeric_limits<int64_t>::min()}) { + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget( + handle, timeout); + }, + "1..900000"); + } + require(backend->begins == 0, "invalid duration reached backend"); + refuses( + [&] { return mlx_distributed_group_end_startup_wait_budget(handle); }, + "No active"); + require( + mlx_distributed_group_begin_startup_wait_budget(handle, 900000) == 0, + "valid begin failed"); + require(backend->begins == 1, "valid begin was not forwarded once"); + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget(handle, 1); + }, + "only begin once"); + { + jaccl::StartupWaitBudget::Call running(backend->policy); + refuses( + [&] { return mlx_distributed_group_end_startup_wait_budget(handle); }, + "idle"); + } + require( + mlx_distributed_group_end_startup_wait_budget(handle) == 0, + "valid end failed"); + refuses( + [&] { return mlx_distributed_group_end_startup_wait_budget(handle); }, + "No active"); + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget(handle, 1); + }, + "only begin once"); + backend->failed = true; + refuses( + [&] { return mlx_distributed_group_end_startup_wait_budget(handle); }, + "closed"); + Group unsupported(std::make_shared<Unsupported>()); + mlx_distributed_group unsupported_handle{&unsupported}; + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget( + unsupported_handle, 1); + }, + "require a JACCL"); + refuses( + [&] { + return mlx_distributed_group_end_startup_wait_budget( + unsupported_handle); + }, + "require a JACCL"); + Group null_group(nullptr); + mlx_distributed_group null_handle{&null_group}; + refuses( + [&] { + return mlx_distributed_group_begin_startup_wait_budget( + null_handle, 1); + }, + "null group"); + refuses( + [&] { + return mlx_distributed_group_end_startup_wait_budget(null_handle); + }, + "null group"); + std::cout + << "PASS real C bridge/core forwarding and one-shot policy; refusals=" + << errors << " native_rdma=0 gpu=0\n"; + mlx_set_error_handler(nullptr, nullptr, nullptr); + return 0; + } catch (const std::exception& e) { + std::cerr << "FAIL " << e.what() << '\n'; + return 1; + } +}
diff --git ml-explore/mlx-c/.github/actionlint.yaml Layr-Labs/mlx-c/.github/actionlint.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2a752e0747ab15399f1dd557d8b546f8131523cf --- /dev/null +++ Layr-Labs/mlx-c/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + labels: + - darkbloom-linux-arm64
diff --git ml-explore/mlx-c/.github/scripts/codeql_artifacts.py Layr-Labs/mlx-c/.github/scripts/codeql_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..dacee361744f10718b59c8234eee408850b2f725 --- /dev/null +++ Layr-Labs/mlx-c/.github/scripts/codeql_artifacts.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Bind read-only CodeQL SARIF to the exact Actions run before upload.""" + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess +import urllib.parse +from pathlib import Path, PurePosixPath + +# BEGIN DATA VALIDATOR +LANGUAGES = { + "actions": "/language:actions", + "cpp": "/language:c-cpp", + "python": "/language:python", +} +CODEQL_VERSION = "2.27.4" +MAX_FILE = 16 * 1024 * 1024 +MAX_BUNDLE = 64 * 1024 * 1024 + + +def context(): + return { + key: os.environ[env] + for key, env in { + "repository": "GITHUB_REPOSITORY", + "sha": "GITHUB_SHA", + "ref": "GITHUB_REF", + "run_id": "GITHUB_RUN_ID", + "attempt": "GITHUB_RUN_ATTEMPT", + }.items() + } + + +def relative_path(value): + if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: + raise ValueError("invalid bundle path") + path = PurePosixPath(value) + if path.is_absolute() or any(part in ("..", ".git") for part in path.parts): + raise ValueError("bundle path escapes its data directory") + if path.as_posix() != value: + raise ValueError("bundle path is not canonical") + return path + + +def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def validate_sarif(sarif): + if sarif.get("version") != "2.1.0" or not sarif.get("runs"): + raise ValueError("invalid SARIF") + if not any( + run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"] + ): + raise ValueError("analysis has no rules") + for run in sarif["runs"]: + driver = run.get("tool", {}).get("driver", {}) + if ( + driver.get("name") != "CodeQL" + or driver.get("semanticVersion") != CODEQL_VERSION + ): + raise ValueError("SARIF was not produced by the qualified CodeQL version") + artifacts = run.get("artifacts", []) + for result in run.get("results", []): + locations = result.get("locations", []) + if not locations: + continue + primary = locations[0].get("physicalLocation", {}) + location = primary.get("artifactLocation", {}) + if "uri" not in location and "index" in location: + index = location["index"] + if type(index) is not int or not 0 <= index < len(artifacts): + raise ValueError("invalid artifact index") + location = artifacts[index]["location"] + uri = urllib.parse.urlsplit(location.get("uri", "")) + if uri.scheme or uri.netloc: + raise ValueError("source location is not repository relative") + relative_path(urllib.parse.unquote(uri.path)) + if primary.get("region", {}).get("startLine") is not None: + fingerprint = result.get("partialFingerprints", {}).get( + "primaryLocationLineHash", "" + ) + if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint): + raise ValueError("source-line finding lacks a stable fingerprint") + + +def verify_bundle(root, expected): + root = root.resolve(strict=True) + manifest_file = root / "manifest.json" + if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024: + raise ValueError("invalid manifest") + manifest = json.loads(manifest_file.read_text()) + if manifest.get("context") != expected or manifest.get("version") != 1: + raise ValueError( + "scan belongs to another run, attempt, repository, ref or commit" + ) + if ( + manifest.get("codeql_version") != CODEQL_VERSION + or manifest.get("categories") != LANGUAGES + ): + raise ValueError("unexpected CodeQL recipe") + files = manifest.get("files") + if not isinstance(files, dict) or len(files) != 3: + raise ValueError("invalid file inventory") + required = {f"sarif/{language}.sarif" for language in LANGUAGES} + if not required.issubset(files): + raise ValueError("missing language") + actual = set() + total = 0 + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("symlinks are not scan data") + if not path.is_file(): + if path.is_dir(): + continue + raise ValueError("only regular files are scan data") + rel = path.relative_to(root).as_posix() + if rel == "manifest.json": + continue + relative_path(rel) + if not path.resolve().is_relative_to(root): + raise ValueError("file escapes bundle") + spec = files.get(rel) + size = path.stat().st_size + if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE: + raise ValueError("unexpected or oversized file") + if spec.get("size") != size or spec.get("sha256") != digest(path): + raise ValueError("scan data changed") + if rel not in required: + raise ValueError("only the three SARIF files may be supplied") + actual.add(rel) + total += size + if actual != set(files) or total > MAX_BUNDLE: + raise ValueError("file inventory differs or bundle exceeds limit") + for language in LANGUAGES: + sarif = json.loads((root / f"sarif/{language}.sarif").read_text()) + validate_sarif(sarif) + # The official uploader falls back to event SHA/ref without a checkout. + # Native CodeQL already supplies every primary-line fingerprint. + empty_checkout = root / "empty-checkout" + empty_checkout.mkdir(exist_ok=True) + return empty_checkout + + +# END DATA VALIDATOR + + +def pack_bundle(checkout, results, output): + checkout = checkout.resolve(strict=True) + expected = context() + actual_sha = subprocess.check_output( + ["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True + ).strip() + if actual_sha != expected["sha"]: + raise ValueError("checkout is not the event commit") + output.mkdir(parents=True, exist_ok=False) + (output / "sarif").mkdir() + used = 0 + for language in LANGUAGES: + source = results / f"{language}.sarif" + if source.is_symlink() or source.stat().st_size > MAX_FILE: + raise ValueError("invalid SARIF input") + data = json.loads(source.read_text()) + validate_sarif(data) + used += source.stat().st_size + if used > MAX_BUNDLE: + raise ValueError("bundle exceeds limit") + destination = output / "sarif" / source.name + shutil.copyfile(source, destination) + destination.chmod(0o644) + files = { + path.relative_to(output).as_posix(): { + "sha256": digest(path), + "size": path.stat().st_size, + } + for path in sorted(output.rglob("*")) + if path.is_file() + } + manifest = { + "version": 1, + "context": expected, + "codeql_version": CODEQL_VERSION, + "categories": LANGUAGES, + "files": files, + } + (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + verify_bundle(output, expected) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkout", type=Path, required=True) + parser.add_argument("--results", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + pack_bundle(args.checkout, args.results, args.output)
diff --git ml-explore/mlx-c/.github/scripts/codeql_artifacts_test.py Layr-Labs/mlx-c/.github/scripts/codeql_artifacts_test.py new file mode 100644 index 0000000000000000000000000000000000000000..dae67fdb562a158678506c9eb45b38ffa8c5768c --- /dev/null +++ Layr-Labs/mlx-c/.github/scripts/codeql_artifacts_test.py @@ -0,0 +1,194 @@ +import copy +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location( + "bundle", Path(__file__).with_name("codeql_artifacts.py") +) +bundle = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(bundle) + + +class DataBoundaryTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.expected = { + "repository": "Layr-Labs/mlx", + "sha": "a" * 40, + "ref": "refs/pull/42/merge", + "run_id": "7", + "attempt": "1", + } + (self.root / "sarif").mkdir() + for language in bundle.LANGUAGES: + data = { + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "CodeQL", + "semanticVersion": "2.27.4", + "rules": [{"id": "example"}], + } + }, + "results": [], + } + ], + } + (self.root / f"sarif/{language}.sarif").write_text(json.dumps(data)) + self.manifest = { + "version": 1, + "context": self.expected, + "codeql_version": "2.27.4", + "categories": bundle.LANGUAGES, + } + self.seal() + + def seal(self): + self.manifest["files"] = { + p.relative_to(self.root).as_posix(): { + "sha256": bundle.digest(p), + "size": p.stat().st_size, + } + for p in self.root.rglob("*") + if p.is_file() and p.name != "manifest.json" + } + (self.root / "manifest.json").write_text(json.dumps(self.manifest)) + + def test_valid_bundle_and_fork_merge_attribution(self): + self.assertEqual( + bundle.verify_bundle(self.root, self.expected), + self.root.resolve() / "empty-checkout", + ) + + def test_every_context_dimension_is_bound(self): + for key in self.expected: + changed = copy.deepcopy(self.expected) + changed[key] += "-different" + with self.subTest(key=key), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, changed) + + def test_content_changes_are_rejected(self): + (self.root / "sarif/actions.sarif").write_text("altered content\n") + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_missing_language_is_rejected(self): + (self.root / "sarif/python.sarif").unlink() + self.seal() + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_extra_files_and_incorrect_inventory_are_rejected(self): + (self.root / "unexpected.sh").write_text("exit 0\n") + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + self.seal() + with self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_source_symlinks_are_rejected(self): + (self.root / "link").symlink_to("/etc/passwd") + with self.assertRaisesRegex(ValueError, "symlink"): + bundle.verify_bundle(self.root, self.expected) + + def test_ruleless_or_malformed_sarif_is_rejected(self): + p = self.root / "sarif/actions.sarif" + p.write_text( + json.dumps( + {"version": "2.1.0", "runs": [{"tool": {"driver": {"rules": []}}}]} + ) + ) + self.seal() + with self.assertRaisesRegex(ValueError, "no rules"): + bundle.verify_bundle(self.root, self.expected) + + def test_bounds_are_enforced(self): + with patch.object(bundle, "MAX_BUNDLE", 1), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + with patch.object(bundle, "MAX_FILE", 1), self.assertRaises(ValueError): + bundle.verify_bundle(self.root, self.expected) + + def test_traversal_git_and_ambiguous_paths_are_rejected(self): + for path in ( + "../private", + "/tmp/private", + "source/../private", + "source/.git/config", + "a\\b", + "a//b", + ): + with self.subTest(path=path), self.assertRaises(ValueError): + bundle.relative_path(path) + + def test_primary_locations_and_fingerprints_are_required(self): + primary = { + "artifactLocation": {"uri": "mlx/ops.cpp"}, + "region": {"startLine": 12}, + } + result = { + "locations": [{"physicalLocation": primary}], + "partialFingerprints": {"primaryLocationLineHash": "ab12:1"}, + } + data = { + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "CodeQL", + "semanticVersion": "2.27.4", + "rules": [{"id": "rule"}], + } + }, + "results": [result], + } + ], + } + bundle.validate_sarif(data) + del result["partialFingerprints"] + with self.assertRaisesRegex(ValueError, "fingerprint"): + bundle.validate_sarif(data) + primary["artifactLocation"]["uri"] = "../private" + with self.assertRaises(ValueError): + bundle.validate_sarif(data) + + def test_different_tool_version_is_rejected(self): + p = self.root / "sarif/cpp.sarif" + data = json.loads(p.read_text()) + data["runs"][0]["tool"]["driver"]["semanticVersion"] = "different" + p.write_text(json.dumps(data)) + self.seal() + with self.assertRaisesRegex(ValueError, "CodeQL version"): + bundle.verify_bundle(self.root, self.expected) + + def test_publisher_embeds_the_exact_tested_validator(self): + source = ( + Path(bundle.__file__) + .read_text() + .split("# BEGIN DATA VALIDATOR\n", 1)[1] + .split("# END DATA VALIDATOR", 1)[0] + ) + workflow = ( + Path(__file__) + .parents[1] + .joinpath("workflows/codeql-native.yml") + .read_text() + ) + # YAML removes this common indentation before the shell sees the program. + embedded = "\n".join( + line[10:] if line.startswith(" ") else line + for line in workflow.splitlines() + ) + self.assertIn(source.strip(), embedded) + + +if __name__ == "__main__": + unittest.main()
diff --git ml-explore/mlx-c/.github/workflows/codeql-native.yml Layr-Labs/mlx-c/.github/workflows/codeql-native.yml new file mode 100644 index 0000000000000000000000000000000000000000..82c75ac91dcb605e07561b6b8bdb161c5dbe7a37 --- /dev/null +++ Layr-Labs/mlx-c/.github/workflows/codeql-native.yml @@ -0,0 +1,261 @@ +name: Native CodeQL + +# Enable only after the operator switches GitHub default setup to advanced setup. +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '15 5 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: native-codeql-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + route: + if: ${{ vars.CODEQL_NATIVE == 'on' && (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') }} + uses: ./.github/workflows/darkbloom-route.yml + permissions: {} + with: + lanes: | + codeql linux_arm64 ubuntu-22.04-arm + + scan: + needs: route + runs-on: ${{ fromJSON(needs.route.outputs.routes)['codeql'] }} + timeout-minutes: 45 + permissions: + contents: read + steps: + - name: Require Linux ARM64 + run: | + [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]] + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Check the artifact boundary + run: python3 .github/scripts/codeql_artifacts_test.py + - name: Download the qualified CodeQL 2.27.4 ARM64 bundle + run: | + set -euo pipefail + cd "$RUNNER_TEMP" + curl --fail --location --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 600 --output codeql.tar.zst https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-linux-arm64.tar.zst + echo '1c015b411c6e1c7f7e767eb8c9408fc6a2012d24d78b177cf22f29edc5772d10 codeql.tar.zst' | sha256sum --check + tar --zstd -xf codeql.tar.zst + "$RUNNER_TEMP/codeql/codeql" version --format=json + "$RUNNER_TEMP/codeql/codeql" resolve languages + - name: Run the existing language-default suites without a build + run: | + set -euo pipefail + codeql="$RUNNER_TEMP/codeql/codeql" + mkdir "$RUNNER_TEMP/codeql-dbs" "$RUNNER_TEMP/codeql-results" + for language in actions cpp python; do + "$codeql" database create "$RUNNER_TEMP/codeql-dbs/$language" --source-root="$GITHUB_WORKSPACE" --language="$language" --build-mode=none --threads=4 --ram=8192 + "$codeql" database analyze "$RUNNER_TEMP/codeql-dbs/$language" --format=sarifv2.1.0 --output="$RUNNER_TEMP/codeql-results/$language.sarif" --threads=4 --ram=8192 + done + - name: Bind fingerprinted SARIF to the exact workflow run + run: | + python3 .github/scripts/codeql_artifacts.py --checkout "$GITHUB_WORKSPACE" --results "$RUNNER_TEMP/codeql-results" --output "$RUNNER_TEMP/codeql-bundle" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/codeql-bundle/ + if-no-files-found: error + retention-days: 3 + + publish: + needs: scan + if: ${{ vars.CODEQL_NATIVE == 'on' && needs.scan.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + actions: read + contents: read + security-events: write + steps: + # No checkout or repository code; native SARIF already has fingerprints. + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/codeql-publish/ + - name: Validate the exact run and bounded data-only bundle + id: validate + env: + BUNDLE: ${{ runner.temp }}/codeql-publish + run: | + python3 - <<'PYCODE' + import hashlib, json, os, re, urllib.parse + from pathlib import Path, PurePosixPath + LANGUAGES = { + "actions": "/language:actions", + "cpp": "/language:c-cpp", + "python": "/language:python", + } + CODEQL_VERSION = "2.27.4" + MAX_FILE = 16 * 1024 * 1024 + MAX_BUNDLE = 64 * 1024 * 1024 + + + def context(): + return { + key: os.environ[env] + for key, env in { + "repository": "GITHUB_REPOSITORY", + "sha": "GITHUB_SHA", + "ref": "GITHUB_REF", + "run_id": "GITHUB_RUN_ID", + "attempt": "GITHUB_RUN_ATTEMPT", + }.items() + } + + + def relative_path(value): + if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: + raise ValueError("invalid bundle path") + path = PurePosixPath(value) + if path.is_absolute() or any(part in ("..", ".git") for part in path.parts): + raise ValueError("bundle path escapes its data directory") + if path.as_posix() != value: + raise ValueError("bundle path is not canonical") + return path + + + def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + + def validate_sarif(sarif): + if sarif.get("version") != "2.1.0" or not sarif.get("runs"): + raise ValueError("invalid SARIF") + if not any( + run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"] + ): + raise ValueError("analysis has no rules") + for run in sarif["runs"]: + driver = run.get("tool", {}).get("driver", {}) + if ( + driver.get("name") != "CodeQL" + or driver.get("semanticVersion") != CODEQL_VERSION + ): + raise ValueError("SARIF was not produced by the qualified CodeQL version") + artifacts = run.get("artifacts", []) + for result in run.get("results", []): + locations = result.get("locations", []) + if not locations: + continue + primary = locations[0].get("physicalLocation", {}) + location = primary.get("artifactLocation", {}) + if "uri" not in location and "index" in location: + index = location["index"] + if type(index) is not int or not 0 <= index < len(artifacts): + raise ValueError("invalid artifact index") + location = artifacts[index]["location"] + uri = urllib.parse.urlsplit(location.get("uri", "")) + if uri.scheme or uri.netloc: + raise ValueError("source location is not repository relative") + relative_path(urllib.parse.unquote(uri.path)) + if primary.get("region", {}).get("startLine") is not None: + fingerprint = result.get("partialFingerprints", {}).get( + "primaryLocationLineHash", "" + ) + if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint): + raise ValueError("source-line finding lacks a stable fingerprint") + + + def verify_bundle(root, expected): + root = root.resolve(strict=True) + manifest_file = root / "manifest.json" + if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024: + raise ValueError("invalid manifest") + manifest = json.loads(manifest_file.read_text()) + if manifest.get("context") != expected or manifest.get("version") != 1: + raise ValueError( + "scan belongs to another run, attempt, repository, ref or commit" + ) + if ( + manifest.get("codeql_version") != CODEQL_VERSION + or manifest.get("categories") != LANGUAGES + ): + raise ValueError("unexpected CodeQL recipe") + files = manifest.get("files") + if not isinstance(files, dict) or len(files) != 3: + raise ValueError("invalid file inventory") + required = {f"sarif/{language}.sarif" for language in LANGUAGES} + if not required.issubset(files): + raise ValueError("missing language") + actual = set() + total = 0 + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("symlinks are not scan data") + if not path.is_file(): + if path.is_dir(): + continue + raise ValueError("only regular files are scan data") + rel = path.relative_to(root).as_posix() + if rel == "manifest.json": + continue + relative_path(rel) + if not path.resolve().is_relative_to(root): + raise ValueError("file escapes bundle") + spec = files.get(rel) + size = path.stat().st_size + if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE: + raise ValueError("unexpected or oversized file") + if spec.get("size") != size or spec.get("sha256") != digest(path): + raise ValueError("scan data changed") + if rel not in required: + raise ValueError("only the three SARIF files may be supplied") + actual.add(rel) + total += size + if actual != set(files) or total > MAX_BUNDLE: + raise ValueError("file inventory differs or bundle exceeds limit") + for language in LANGUAGES: + sarif = json.loads((root / f"sarif/{language}.sarif").read_text()) + validate_sarif(sarif) + # The official uploader falls back to event SHA/ref without a checkout. + # Native CodeQL already supplies every primary-line fingerprint. + empty_checkout = root / "empty-checkout" + empty_checkout.mkdir(exist_ok=True) + return empty_checkout + + + source = verify_bundle(Path(os.environ['BUNDLE']), context()) + with open(os.environ['GITHUB_OUTPUT'], 'a') as out: + out.write(f'checkout-path={source}\n') + PYCODE + - name: Upload actions analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/actions.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:actions + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true + - name: Upload cpp analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/cpp.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:c-cpp + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true + - name: Upload python analysis + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: ${{ runner.temp }}/codeql-publish/sarif/python.sarif + checkout_path: ${{ steps.validate.outputs.checkout-path }} + category: /language:python + ref: ${{ github.ref }} + sha: ${{ github.sha }} + wait-for-processing: true
diff --git ml-explore/mlx-c/.github/workflows/darkbloom-route.yml Layr-Labs/mlx-c/.github/workflows/darkbloom-route.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3cbd667cb26f368c1c47d1087d5d5c943085201 --- /dev/null +++ Layr-Labs/mlx-c/.github/workflows/darkbloom-route.yml @@ -0,0 +1,166 @@ +# Copied verbatim from Layr-Labs/d-inference@6ffeaf06c2e9541fa095f4b8194b527c93458523 +# (.github/workflows/darkbloom-route.yml, blob 4528c2c7184e156c418054521c1421a95e188c29, +# last changed there in 11bb2d18cef808014736213502755b6b6074eed6, #1619). Keep the +# lines below this header identical to that file; change d-inference first. + +name: Darkbloom Route + +# Chooses a runner for each read-only CI lane: a Darkbloom Sandbox when the +# plane grants one, otherwise the lane's fallback label. Callers run each job on +# `fromJSON(needs.route.outputs.routes)['<lane>']`. Routing is off unless the +# DARKBLOOM_ROUTING variable is exactly `on`; the plane can never fail this job. +on: + workflow_call: + inputs: + lanes: + description: >- + One lane per line: `<lane> <profile> <fallback-label> [count]`. + Profiles are linux_arm64 and macos_arm64. Count is the number of jobs + that will run (default 1); 0 keeps the fallback without asking. + type: string + required: true + outputs: + routes: + description: JSON object mapping every lane to its runs-on value. + value: ${{ jobs.select.outputs.routes }} + +permissions: {} + +jobs: + select: + name: Select Runners + runs-on: ubuntu-24.04 + permissions: {} + timeout-minutes: 3 + outputs: + routes: ${{ steps.route.outputs.routes }} + steps: + - name: Choose a Darkbloom or fallback runner for each lane + id: route + shell: bash + env: + LANES: ${{ inputs.lanes }} + ROUTING: ${{ vars.DARKBLOOM_ROUTING }} + PLANE_URL: ${{ vars.DARKBLOOM_SANDBOX_URL }} + REPOSITORY: ${{ github.repository }} + EVENT_NAME: ${{ github.event_name }} + HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + set -euo pipefail + + # The only labels a lane can receive besides its fallback. A plane + # decision is used only when it repeats its profile's array exactly. + profiles='{"linux_arm64":["self-hosted","linux","ARM64","darkbloom-linux-arm64"],"macos_arm64":["self-hosted","macOS","ARM64","darkbloom-macos-arm64"]}' + # Plane text is untrusted: keep it short, on one line, and free of + # Markdown, HTML and workflow-command syntax before printing it. + clean='def clean: tostring | gsub("[^A-Za-z0-9 _.,:;/=+()-]"; "?") | .[0:120];' + + configuration_error() { + echo "::error title=Darkbloom route configuration::$1" + exit 1 + } + + configured='[]' + seen=' ' + while read -r lane profile fallback count extra; do + [ -n "$lane" ] || continue + count=${count:-1} + [ -z "$extra" ] || configuration_error "lane $lane has more than four fields" + [[ $lane =~ ^[A-Za-z0-9_-]+$ ]] || configuration_error "invalid lane name: $lane" + jq -e --arg profile "$profile" 'has($profile)' <<<"$profiles" >/dev/null \ + || configuration_error "lane $lane has unknown profile: $profile" + [[ $fallback =~ ^[A-Za-z0-9._-]+$ ]] \ + || configuration_error "lane $lane has invalid fallback label: $fallback" + [[ $count =~ ^(0|[1-9][0-9]?)$ ]] || configuration_error "lane $lane has invalid count: $count" + case $seen in *" $lane "*) configuration_error "lane $lane is listed twice" ;; esac + seen="$seen$lane " + configured=$(jq -c --arg lane "$lane" --arg profile "$profile" --arg fallback "$fallback" \ + --argjson count "$count" '. + [{$lane, $profile, $fallback, $count}]' <<<"$configured") + done <<<"${LANES:-}" + [ "$configured" != '[]' ] || configuration_error "no lanes are configured" + requested=$(jq -c '[.[] | select(.count > 0) | {lane, profile, count}]' <<<"$configured") + + plane_url=${PLANE_URL:-https://api-sandbox.darkbloom.dev} + body=$(mktemp) + trap 'rm -f "$body"' EXIT + reply=/dev/null + fallback_reason="" + if [ "${ROUTING:-}" != on ]; then + fallback_reason="routing is off" + note="Routing is off: DARKBLOOM_ROUTING is not 'on'. No request was sent." + elif [[ ${EVENT_NAME:-} == pull_request* && ${HEAD_REPOSITORY:-} != "${REPOSITORY:-}" ]]; then + fallback_reason="pull request from a fork" + note="Pull requests from forks keep their fallback runners. No request was sent." + elif [ "$requested" = '[]' ]; then + note="No lane has jobs to run. No request was sent." + elif [[ $plane_url != https://* ]]; then + fallback_reason="plane URL is not https" + note="DARKBLOOM_SANDBOX_URL must start with https://. No request was sent." + elif ! [[ ${RUN_ID:-} =~ ^[0-9]+$ && ${RUN_ATTEMPT:-} =~ ^[0-9]+$ ]]; then + fallback_reason="run identity is unavailable" + note="The run ID or attempt is not numeric. No request was sent." + else + request=$(jq -n -c --arg repository "$REPOSITORY" --argjson run_id "$RUN_ID" \ + --argjson run_attempt "$RUN_ATTEMPT" --argjson lanes "$requested" \ + '{$repository, $run_id, $run_attempt, $lanes}') + # One attempt plus at most one retry after a transport failure, + # timeout or transient status; each attempt is bounded to 5 seconds. + for attempt in 1 2; do + status=$(curl --disable --silent --show-error --proto '=https' --max-time 5 \ + --max-filesize 65536 --user-agent darkbloom-route/1 --request POST \ + --header 'Content-Type: application/json' --header 'Accept: application/json' \ + --data-binary @- --output "$body" --write-out '%{http_code}' \ + "${plane_url%/}/v1/ci/routes" <<<"$request") || status=000 + case $status in + 000|408|429|5??) [ "$attempt" = 2 ] || sleep 1 ;; + *) break ;; + esac + done + if [ "$status" != 200 ]; then + fallback_reason="plane request failed (HTTP $status)" + elif ! jq -e -s 'length == 1 and (.[0] | type == "object" + and (.route_id | type == "string" and length > 0) + and (.expires_at | type == "string") + and (.lanes | type == "object"))' "$body" >/dev/null 2>&1; then + fallback_reason="plane reply is malformed" + else + reply=$body + fi + if [ -n "$fallback_reason" ]; then + note="Asked $plane_url: $fallback_reason. Requested lanes keep their fallback runners." + else + note=$(jq -r --arg url "$plane_url" \ + "$clean"'"Asked \($url): route \(.route_id | clean), expires \(.expires_at | clean)."' "$body") + fi + fi + + decisions=$(jq -n -c --argjson configured "$configured" --argjson profiles "$profiles" \ + --arg fallback_reason "$fallback_reason" --slurpfile reply "$reply" "$clean"' + ($reply[0].lanes // {}) as $plane_decisions + | [ $configured[] + | ($plane_decisions[.lane] | if type == "object" then . else {} end) as $decision + | if .count == 0 then .target = "fallback" | .reason = "not requested" + elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason + elif $decision.target == "darkbloom" and $decision.runs_on == $profiles[.profile] + then .target = "darkbloom" | .reason = "granted" + elif $decision.target == "fallback" + then .target = "fallback" | .reason = "plane: " + ($decision.reason // "no reason" | clean) + else .target = "fallback" | .reason = "plane decision is missing or invalid" + end + | .runs_on = (if .target == "darkbloom" then $profiles[.profile] else .fallback end) ]') + routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions") + echo "routes=$routes" >> "$GITHUB_OUTPUT" + + echo "$note" + jq -r '.[] | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason))"' <<<"$decisions" + { + echo "### Darkbloom runner routing" + echo + echo "$note" + echo + echo "| Lane | Profile | Jobs | Runner | Decision |" + echo "| --- | --- | --- | --- | --- |" + jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions" + } >> "$GITHUB_STEP_SUMMARY"
diff --git ml-explore/mlx-c/.github/workflows/forkdiff-check.yml Layr-Labs/mlx-c/.github/workflows/forkdiff-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..d834baf2170d7bd588a7a76104c22cba1e363775 --- /dev/null +++ Layr-Labs/mlx-c/.github/workflows/forkdiff-check.yml @@ -0,0 +1,76 @@ +name: Fork Diff Check + +# Fails a PR whose `fork.yaml` no longer describes this fork. +# +# The fork-diff page (https://layr-labs.github.io/mlx-c/, rendered by +# protolambda/forkdiff from `fork.yaml`, deployed by forkdiff-pages.yml) is +# only useful while it is true, and two things make it go stale silently: +# +# 1. A rebase onto newer upstream. `base.hash` keeps pointing at the old +# upstream commit, so the page shows upstream's own changes as the fork's. +# `scripts/check_forkdiff.py` requires base.hash == merge-base(HEAD, +# upstream/main); a rebase moves the merge-base and the gate stays red +# until the hash — and the sections — are brought up to date. +# 2. A fork change nobody described. Every file in the base..HEAD diff must +# match a section glob (or a global ignore), and every glob must still +# match something. +# +# The page is also rendered here so a fork.yaml that forkdiff itself rejects +# cannot merge. + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + analysis-up-to-date: + name: fork.yaml describes the fork + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # full history: merge-base with upstream, and forkdiff diffs against base.hash + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx-c.git \ + main:refs/remotes/upstream/main + echo "upstream/main = $(git rev-parse --short refs/remotes/upstream/main)" + echo "merge-base = $(git merge-base HEAD refs/remotes/upstream/main | cut -c1-12)" + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Verify fork.yaml against the real diff + run: | + python3 -m pip install --quiet pyyaml + python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Render the fork-diff page + # fork.yaml names refs/heads/main; on a PR the checkout is a detached + # merge commit, so point the local branch at what we are checking. + run: | + git update-ref refs/heads/main HEAD + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + echo "rendered $(wc -c < tmp/pages/index.html) bytes" + + - name: Upload rendered page + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 7
diff --git ml-explore/mlx-c/.github/workflows/forkdiff-pages.yml Layr-Labs/mlx-c/.github/workflows/forkdiff-pages.yml new file mode 100644 index 0000000000000000000000000000000000000000..3d854f689e12cf14961a865e7afa1301d55373db --- /dev/null +++ Layr-Labs/mlx-c/.github/workflows/forkdiff-pages.yml @@ -0,0 +1,132 @@ +name: Deploy Fork Diff + +# Renders `fork.yaml` with protolambda/forkdiff and publishes the result as the +# repository's GitHub Pages site — the same setup ethereum-optimism/op-geth +# uses for its go-ethereum fork diff. Runs the analysis gate first, so a page +# that lies about the fork is never published. + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: "pages" + cancel-in-progress: true + +jobs: + render: + name: Render fork diff + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # forkdiff diffs against base.hash, deep in history + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx-c.git \ + main:refs/remotes/upstream/main + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Refuse to publish a stale analysis + run: | + python3 -m pip install --quiet pyyaml + python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Build forkdiff + run: | + git update-ref refs/heads/main HEAD + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + + - name: Keep the rendered page as an artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 30 + + deploy: + name: Deploy fork diff + needs: render + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url || steps.deployment-retry.outputs.page_url }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + pages: write + id-token: write + steps: + - name: Is GitHub Pages enabled? + # Pages must be switched on once by a repo admin (Settings → Pages → + # Source: "GitHub Actions"). The workflow token cannot do that itself + # (`configure-pages` enablement needs an admin PAT), so until then the + # page is built and kept as an artifact but not deployed — a notice, + # not a red run. + id: pages + env: + GH_TOKEN: ${{ github.token }} + run: | + if gh api "repos/${GITHUB_REPOSITORY}/pages" --silent 2>/dev/null; then + echo "enabled=true" >> "$GITHUB_OUTPUT" + else + echo "enabled=false" >> "$GITHUB_OUTPUT" + echo "::notice::GitHub Pages is not enabled for ${GITHUB_REPOSITORY}; built the page but skipped the deploy. Enable it once under Settings → Pages (Source: GitHub Actions) and re-run this workflow." + fi + + - name: Setup Pages + if: steps.pages.outputs.enabled == 'true' + uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0 + + - name: Download rendered page + if: steps.pages.outputs.enabled == 'true' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: forkdiff-page + path: tmp/pages + + - name: Prepare Pages artifact + if: steps.pages.outputs.enabled == 'true' + run: touch tmp/pages/.nojekyll + + - name: Upload Pages artifact + if: steps.pages.outputs.enabled == 'true' + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: tmp/pages + + # deploy-pages looks the github-pages artifact up in this run's artifact + # list as soon as it starts, and that list can lag the upload above: the + # first try then fails with "No artifacts named github-pages were found" + # (seen on 2026-11-14). Only when the first try failed before it created a + # deployment (no page_url), wait and try once more. + - name: Deploy to GitHub Pages + if: steps.pages.outputs.enabled == 'true' + id: deployment + continue-on-error: true + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 + + - name: Wait before the second try + if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == '' + run: sleep 20 + + - name: Deploy to GitHub Pages (second try) + if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == '' + id: deployment-retry + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
diff --git ml-explore/mlx-c/fork.yaml Layr-Labs/mlx-c/fork.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cbc3fb837c6e2b2a9bef8c23c753a2d511168f3 --- /dev/null +++ Layr-Labs/mlx-c/fork.yaml @@ -0,0 +1,218 @@ +title: "Layr-Labs/mlx-c - MLX C fork diff overview" +footer: | + Fork-diff overview of [`Layr-Labs/mlx-c`](https://github.com/Layr-Labs/mlx-c), a fork of + [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c) &middot; the C bridge in Layr-Labs' + Apple-silicon inference stack ([`mlx`](https://github.com/Layr-Labs/mlx) → + [`mlx-c`](https://github.com/Layr-Labs/mlx-c) → [`mlx-swift`](https://github.com/Layr-Labs/mlx-swift) → + [`mlx-swift-lm`](https://github.com/Layr-Labs/mlx-swift-lm)) &middot; created with + [Forkdiff](https://github.com/protolambda/forkdiff) +base: + name: ml-explore/mlx-c + url: https://github.com/ml-explore/mlx-c + # The last upstream commit merged into this fork. CI (`scripts/check_forkdiff.py`) + # requires this to equal `git merge-base HEAD upstream/main`. Each upstream merge + # moves this hash and re-validates every section below. + # Upstream main as of 2026-10-22 (57731b0, bindings for MLX 0.32.4). + hash: 57731b00e8bed710e0750e7356da9f18f8eb3e20 +fork: + name: Layr-Labs/mlx-c + url: https://github.com/Layr-Labs/mlx-c + ref: refs/heads/main +def: + title: "Layr-Labs/mlx-c" + description: | + This is an overview of the changes in [`Layr-Labs/mlx-c`](https://github.com/Layr-Labs/mlx-c), + a fork of [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c). + + MLX C is the C boundary between the MLX core and every other language binding. Layr-Labs + runs an LLM/VLM serving stack on Apple silicon — continuous batching, paged KV caches, + MoE and quantized kernels — built as [`mlx-swift-lm`](https://github.com/Layr-Labs/mlx-swift-lm) + on [`mlx-swift`](https://github.com/Layr-Labs/mlx-swift), which links a forked + [`mlx`](https://github.com/Layr-Labs/mlx) core through this fork. Every change here is a + **carry-patch**: a thin C wrapper over a function the forked core added, so Swift can reach + it. The upstream API and ABI are left untouched; the fork only adds entry points, and pins + the core it builds against to the Layr-Labs revision that provides them. + + Downstream consumers are named per section so a change here can be traced to the Swift + symbol that needs it. + sub: + - title: "Core pin" + description: | + `CMakeLists.txt` fetches the MLX core from `Layr-Labs/mlx` at an exact commit instead of + an upstream release tag. The C functions below wrap core functions that only exist on the + fork, so the pin is what makes them link; it is bumped together with the header changes + each time the core gains a new entry point. + The current pin is `ea318ee0`, the core that Layr-Labs/mlx-swift builds for the cluster + stack. It contains main's previous pin `ff4bb35b` and the sealed reduce-scatter and + all-gather (`360d11b9`) that `distributed_sealed.cpp` calls. + The current pin also preserves 512- and 1024-thread custom Metal launch geometry + while retrying an insufficient pipeline with its explicit compiler capacity, + orders the fast-synch GPU wait after every pending pass on its queue (a CPU-stream + collective between two GPU passes could otherwise leave the GPU spinning forever), + and carries 1 MiB JACCL frames, batched buffer retention, a cached custom-kernel + source per kernel (host time only), the streamed sealed all-sum (per-piece + AES-256-GCM over a two-rank JACCL exchange), opt-in fused fence updates and + fenced custom-kernel inputs, and cheaper custom-kernel launches and graph + bookkeeping (host time only), and the thread-scoped command-buffer commit limits. The + page-backed footprint change is reverted, as on the single-Mac stack. + globs: + - "CMakeLists.txt" + - title: "Memory: allocator observability and footprint policy" + description: | + The Swift admission code decides whether a request fits by asking the allocator, and the + upstream C API only offered independent counters. The fork adds, in order of arrival: + + - `mlx_get_num_resources` / `mlx_get_resource_limit` — the live Metal buffer *count* and + its hard ceiling, the quantity behind the `[metal::malloc] Resource limit exceeded` + crash (consumed as `Memory.numResources` / `Memory.resourceLimit` in mlx-swift). + - `mlx_get_memory_snapshot` — one coherent active/cache/peak observation instead of three + separate calls that can straddle an allocation. + - `mlx_get_allocation_footprint_policy` and its checked `_bound` / `_maximum_extra` + helpers — the allocator's immutable rounding geometry (alignment, rounding threshold, + minimum allocation, power-of-two cut-off, cache page size) so callers can compute the + real footprint of a requested size without allocating; bound helpers return 1 on an + invalid policy or overflow without raising through the error callback. + - `mlx_get_allocation_size_upper_bound` — the same bound for the current policy. + + The generator override in `python/mlxhooks.py` keeps `mlx_get_memory_snapshot` intact + when the bindings are regenerated from the core headers. + globs: + - "mlx/c/memory.h" + - "mlx/c/memory.cpp" + - "python/mlxhooks.py" + - title: "Memory: optional process allocation cap" + description: | + `mlx_install_process_allocation_cap` installs the core's install-once Metal backing cap + and `mlx_get_process_allocation_cap_snapshot` reads its ledger (limit, fixed heap, live, + cached, pending, unreclaimed, charged and peak bytes). Both forward to the matching core + accounting and report failures through the error handler; CPU and CUDA builds refuse. + The standalone example checks that interface. Consumed as + `Memory.installProcessAllocationCap` / `Memory.processAllocationCapSnapshot` in mlx-swift. + globs: + - "mlx/c/memory_cap.cpp" + - "examples/cap-tests/memory_cap.cpp" + - title: "Array: buffer metadata and constant-cache identity" + description: | + Two non-evaluating inspections the quantized-inference path in mlx-swift relies on: + + - `mlx_array_get_buffer_info` — backing metadata (allocated bytes, data offset, element + count, row-contiguity, uniqueness) for an *already evaluated* array. Unavailable backing + is reported as `available=false` rather than forcing an eval or a stream sync; views may + report shared backing and the fields confer no ownership. + `unique` comes from `array::is_uniquely_referenced()` in the Layr-Labs/mlx core: no other + array references the array or its data. It does not require MLX to own the buffer, so a + wrapped external buffer can be unique (upstream #4634 made `is_donatable()` require + ownership). + - `_mlx_array_constant_cache_identity` — the backing descriptor's identity plus a + transform-safety predicate, so a Swift constant cache can reuse an unchanged constant's + exact cast across calls without mistaking a mutated array for its former contents. It + refuses compile/autodiff tracing and retained graphs, and never evaluates, hashes, or + reads data back. Marked internal: the caller must retain the source descriptor while + the identity is cached. + globs: + - "mlx/c/array.h" + - "mlx/c/array.cpp" + - title: "Fast: mutable and fenced inputs and per-kernel math modes" + description: | + - `mlx_fast_metal_kernel_new_mutable` — a second constructor for custom Metal kernels + that declares which caller-owned input buffers the kernel writes (the core's + mutable-input contract, used for in-place paged KV updates). The existing constructor + and its read-only ABI are unchanged. + - `mlx_fast_metal_kernel_new_fenced` — the same with fenced inputs: inputs that can come + from a CPU stream in the same eval, which the kernel waits for itself (core + `metal_kernel_with_fenced_inputs`, opt-in `MLX_METAL_FENCED_INPUTS=1`). + - `mlx_fast_metal_kernel_new_with_options` adds an explicit safe, relaxed or fast + compiler math mode for one custom kernel, including mutable-input metadata. + Legacy constructors remain unchanged; this does not alter process-wide defaults. + Non-safe modes require operation-specific numerical and platform qualification. + The generator extension retains `new_mutable` and `new_with_options` when bindings + regenerate. It does not yet emit `new_fenced` or the prepared-launch functions, so a + regeneration must carry those hand edits over. + - `mlx_fast_metal_kernel_launch_new` / `_apply` / `_free` — a prepared launch: a kernel + bound once to a copied config and applied to new inputs without rebuilding the + config (host time only). The kernel must outlive the launch. + `MLX_C_BUILD_TESTS` enables constructor/error-contract tests without GPU execution. + globs: + - "mlx/c/fast.h" + - "mlx/c/fast.cpp" + - "python/metal_kernel_options.py" + - "tests/metal_kernel_options.cpp" + - "docs/src/fast.rst" + - title: "Stream: cross-thread default streams" + description: | + MLX 0.32 made the default stream's Metal command encoder thread-local, so a graph built + on one thread and evaluated on another — Swift `async/await` continuations, actor + executors — aborts with `There is no Stream(gpu, N) in current thread`. + `mlx_thread_unsafe_cpu_stream_new` / `mlx_thread_unsafe_gpu_stream_new` expose the + core's `new_thread_unsafe_stream`, whose encoder is registered globally, letting + mlx-swift restore a single process-wide default stream. "Thread-unsafe" means the caller + serializes submission; it is not locked for concurrent multi-thread use. + Upstream now binds the same core function as `mlx_stream_new_thread_unsafe(dev)`. + The fork keeps its two no-argument names because the Layr-Labs/mlx-swift `Stream` + code calls them. Remove them when mlx-swift calls the upstream name. + globs: + - "mlx/c/stream.h" + - "mlx/c/stream.cpp" + - title: "Fork tooling" + description: | + The gate that keeps this page honest: `check_forkdiff.py` fails CI when `base.hash` + is not the merge-base with upstream, or when a file the fork changes is not described + by a section above. `FORKDIFF.md` explains the day-to-day; the README links the page. + + The fork-diff check and Pages renderer run only on Darkbloom Linux ARM64 + runners, waiting for compatible capacity instead of using a hosted fallback. + Both retain the upstream checks, rendering steps and 20-minute job limits. + The protected Pages publication job stays on GitHub-hosted runners. + `FORKDIFF.md` documents the queue and qualification limits. + + The disabled native CodeQL workflow scans Actions, C/C++ and Python with + the pinned CodeQL 2.27.4 ARM64 bundle and their existing default suites. + It requires `CODEQL_NATIVE=on` after an operator switches default setup + to advanced setup. The separate GitHub-hosted publisher validates the + same run's bounded, fingerprinted SARIF bundle, then uploads the original + category identities without checking out or executing repository code. + `docs/ci-codeql-native.md` records activation and rollback gates. + globs: + - ".github/actionlint.yaml" + - ".github/workflows/forkdiff-check.yml" + - ".github/workflows/forkdiff-pages.yml" + - ".github/scripts/codeql_artifacts.py" + - ".github/scripts/codeql_artifacts_test.py" + - ".github/workflows/codeql-native.yml" + - "docs/ci-codeql-native.md" + - "scripts/check_forkdiff.py" + - "FORKDIFF.md" + - "README.md" + + - title: "Cluster bootstrap and sealed collectives" + description: | + The feature branch carries the bounded owner-provided bootstrap exchange, + sealed two-rank all-sum bridge (whole-frame and streamed per-piece codec + callbacks, `mlx_distributed_set_streamed_seal_codec`), and the sealed two-rank + reduce-scatter and all-gather (`mlx_distributed_reduce_scatter_sealed`, + `mlx_distributed_all_gather_sealed`) on the same codec and counter. + Bootstrap validates dimensions and sequences but its owner authenticates + the channel. Sealed collective callbacks retain their existing no-reentry + contract. These + pre-existing feature changes remain present when adding startup waits. + globs: + - "mlx/c/distributed_bootstrap.cpp" + - "mlx/c/private/distributed_bootstrap.h" + - "mlx/c/distributed_group.h" + - "mlx/c/distributed_sealed.cpp" + - title: "Distributed: bounded one-shot startup readiness" + description: | + The begin/end startup-wait C entry points validate group handles and + finite 1..900000 ms bounds, then forward to the matching core Group API. + Exceptions report through the existing error handler and return failure. + The embedding runtime drains work, serializes transitions and retains + cancellation, authentication and memory safeguards. CPU-only standalone + tests cover argument refusal, forwarding and unsupported backends. + globs: + - "mlx/c/distributed_group.cpp" + - "tests/standalone/*" + +# ignored globally, does not count towards line count +ignore: + - "fork.yaml" + - ".github/**"