From d35b1d6355b769d1d3c685a032acf04541662ec5 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 4 Dec 2026 09:50:32 -0800 Subject: [PATCH 1/2] Metal: opt-in sealed pipelines from shipped binary archives MLX builds GPU code at run time: generated kernel sources, compile fusion, custom kernels, and the lowering of each pipeline from AIR. All of it goes through the Metal compiler service of the process. A caller that must serve only GPU code built offline can now turn on sealed pipelines. The mode is off by default and nothing changes when it is off. - metal::set_sealed_pipelines(mode, archive_paths, kernel_pack_path) (C: mlx_metal_set_sealed_pipelines) sets the mode once, before the first GPU kernel. A later call fails and changes nothing. - enforce: pipelines and specialized functions come only from the shipped MTLBinaryArchives with the fail-on-miss options. An empty archive set is a miss (Metal ignores the options without archives). A generated source must be in mlx.metallib or in the kernel pack. A miss throws "Runtime Metal compilation is refused". - compile() runs functions unfused, also for functions compiled before the mode was set (gpu::can_build_kernels()). - Sealed mode uses the non-NAX kernels: metal-tt (Metal toolchain 27.1) cannot translate the NAX kernels. - report: a miss builds the code as before and is counted. - start/stop_pipeline_recording() record the pipelines (function, specialized name, constant values) and generated sources as JSON. - scripts/sealed_pipelines.py builds the kernel pack and one archive per GPU architecture with metal-tt. It prunes mlx.metallib to the recorded functions first, so an archive is about 200 KB, not a copy of the 223 MB metallib. - tests/standalone/sealed_pipelines_metal.cpp: record, build, enforce (same values as the CPU, no miss, no compiler service, unrecorded code fails closed), enforce with no archive, report, and a late call. Each case runs in its own ctest process; fork-tests.yml runs them. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fork-tests.yml | 19 +- fork.yaml | 57 +- mlx/backend/common/sealed_pipelines.h | 71 +++ mlx/backend/cpu/compiled.cpp | 6 +- mlx/backend/cuda/device_info.cpp | 4 + mlx/backend/gpu/device_info.h | 6 + mlx/backend/metal/CMakeLists.txt | 1 + mlx/backend/metal/device.cpp | 243 ++++++++- mlx/backend/metal/device.h | 26 + mlx/backend/metal/device_info.cpp | 4 + mlx/backend/metal/metal.h | 35 ++ mlx/backend/metal/no_metal.cpp | 24 + mlx/backend/metal/sealed_pipelines.cpp | 577 ++++++++++++++++++++ mlx/backend/metal/sealed_pipelines.h | 125 +++++ mlx/backend/no_cpu/compiled.cpp | 3 +- mlx/backend/no_gpu/device_info.cpp | 4 + mlx/compile.cpp | 5 + scripts/sealed_pipelines.py | 321 +++++++++++ tests/CMakeLists.txt | 36 ++ tests/standalone/sealed_pipelines_metal.cpp | 300 ++++++++++ 20 files changed, 1857 insertions(+), 10 deletions(-) create mode 100644 mlx/backend/common/sealed_pipelines.h create mode 100644 mlx/backend/metal/sealed_pipelines.cpp create mode 100644 mlx/backend/metal/sealed_pipelines.h create mode 100644 scripts/sealed_pipelines.py create mode 100644 tests/standalone/sealed_pipelines_metal.cpp diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index 1fce1030e5..dc44c911cf 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -8,8 +8,9 @@ name: Fork Tests # build-cpp builds the C++ library and tests, and runs the C++ tests # with the GPU and then with the CPU as the default device, # and the JACCL tests with simulated verbs (tests/jaccl). -# Then it runs the standalone allocation cap tests, one -# process for each case, and the bounded Metal fence chains. +# Then it runs the standalone allocation cap tests and the +# sealed pipeline tests, one process for each case, and the +# bounded Metal fence chains. # python-gpu runs the Python tests with the GPU as the default device. # python-cpu runs the Python tests with the CPU as the default device. # metal-build-and-test @@ -182,6 +183,20 @@ jobs: ctest --test-dir build -R '^process_allocation_cap' -V \ --no-tests=error + - name: Run the sealed Metal pipeline tests + # The sealed pipeline mode is set once in each process, before the + # first GPU kernel. ctest runs each case in a fresh process: record, + # build the archive with metal-tt, enforce, and three cases without + # an archive (tests/CMakeLists.txt). The build and enforce cases skip + # when the runner has no metal-tt or metal-tt cannot build for its + # GPU; -V prints why. + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/sealed-%p-%m.profraw + run: | + ctest --test-dir build -R '^sealed_pipelines_metal\.' -V \ + --no-tests=error + - name: Run the bounded Metal fence chains # metal_fence_chain runs exact GPU -> CPU -> GPU chains with fast # synchronization at three command buffer sizes, one ctest entry for diff --git a/fork.yaml b/fork.yaml index 144d59b1cb..6f79dc1c9d 100644 --- a/fork.yaml +++ b/fork.yaml @@ -717,6 +717,61 @@ def: do. The seed search ran in PR #46 (first commit). globs: - "python/tests/mlx_tests.py" + - title: "Sealed Metal pipelines (opt-in)" + description: | + MLX builds GPU code at run time: generated kernel sources, compile fusion, custom + kernels, and the lowering of each pipeline from AIR. All of it goes through the Metal + compiler service of the process. Sealed pipelines let a caller serve only GPU code + that was built offline and shipped. The mode is off by default. + `metal::set_sealed_pipelines(mode, archive_paths, kernel_pack_path)` (C: + `mlx_metal_set_sealed_pipelines`) sets it once, before the first GPU kernel; a later + call fails and changes nothing. + + In `enforce` mode, each pipeline and each specialized function comes from a shipped + `MTLBinaryArchive` with the fail-on-miss options. Metal ignores those options when no + archive is given, so MLX treats an empty archive set as a miss. A generated kernel + source must be in the precompiled metallib (each `host_name` is in it) or in the + kernel pack, a file of metallibs keyed by the SHA-256 of the source and the math + mode. A miss throws an error that names the code and says "Runtime Metal compilation + is refused"; MLX builds nothing. `compile` runs the function unfused + (`gpu::can_build_kernels()` is false), also for a function that was compiled before. + `fast::metal_kernel` works only for sources in the kernel pack. MLX uses the non-NAX + kernels, because the offline translator (`metal-tt`, Metal toolchain 27.1) fails on + NAX kernels (Metal 4 cooperative tensors). In `report` mode a miss builds the code as + before and is counted, and `sealed_pipelines_report()` lists it. + + `start_pipeline_recording()` / `stop_pipeline_recording()` record the pipelines + (library, function, specialized name, constant values) and the generated sources of a + workload as JSON. `scripts/sealed_pipelines.py build` turns recordings into the + kernel pack, a Metal pipelines script and one archive for each GPU architecture with + `metal-tt`. It gives `metal-tt` a copy of `mlx.metallib` with only the recorded + functions (`metal-objcopy --keep-symbol`), because an archive holds the AIR of the + libraries it is built from. An archive loads only on the macOS major it was built + for. `tests/standalone/sealed_pipelines_metal.cpp` runs one case in each ctest process: + record, build, enforce (no miss, the same values as the CPU, no compiler service in + `launchctl print`, unrecorded code fails closed), enforce with no archive, report, and + a late call. The build and enforce cases skip (77) when `metal-tt` is missing or + cannot build for the GPU. + globs: + - "mlx/backend/common/sealed_pipelines.h" + - "mlx/backend/metal/sealed_pipelines.h" + - "mlx/backend/metal/sealed_pipelines.cpp" + - "mlx/backend/metal/metal.h" + - "mlx/backend/metal/no_metal.cpp" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/device_info.cpp" + - "mlx/backend/metal/CMakeLists.txt" + - "mlx/backend/gpu/device_info.h" + - "mlx/backend/cuda/device_info.cpp" + - "mlx/backend/no_gpu/device_info.cpp" + - "mlx/backend/cpu/compiled.cpp" + - "mlx/backend/no_cpu/compiled.cpp" + - "mlx/compile.cpp" + - "scripts/sealed_pipelines.py" + - "tests/standalone/sealed_pipelines_metal.cpp" + - "tests/CMakeLists.txt" + - ".github/workflows/fork-tests.yml" - title: "Fork tooling" description: | The fork deletes the upstream workflows that cannot run here: the PyPI release build, @@ -735,7 +790,7 @@ def: wheel. The other job builds the C++ library and tests, and runs the C++ tests with the GPU and then with the CPU as the default device, and builds and runs the JACCL tests with simulated verbs (`tests/jaccl`). Then it runs the standalone allocation - cap tests with ctest, one process for each case. The Python tests run in shard jobs: + cap tests and the sealed pipeline tests with ctest, one process for each case. The Python tests run in shard jobs: one set with the GPU as the default device, and one set with the CPU. `.github/scripts/fork-tests/python-shards.json` gives the shards. `python_shards.py` fails a job when a test file is in no shard or in two shards, and diff --git a/mlx/backend/common/sealed_pipelines.h b/mlx/backend/common/sealed_pipelines.h new file mode 100644 index 0000000000..431ac7fcfc --- /dev/null +++ b/mlx/backend/common/sealed_pipelines.h @@ -0,0 +1,71 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include + +#include "mlx/api.h" + +#if defined(__APPLE__) +#ifdef __cplusplus +extern "C" { +#endif + +/// Modes of sealed Metal pipelines. +/// - OFF: the default. MLX builds GPU code at run time as needed. +/// - REPORT: MLX uses the shipped GPU code. A miss builds the code at run +/// time and is counted. +/// - ENFORCE: MLX uses only the shipped GPU code. A miss is an error. +/// In REPORT and ENFORCE, `compile` runs functions unfused and MLX uses the +/// non-NAX kernels. +enum { + MLX_METAL_SEALED_PIPELINES_OFF = 0, + MLX_METAL_SEALED_PIPELINES_REPORT = 1, + MLX_METAL_SEALED_PIPELINES_ENFORCE = 2, +}; + +/// Sets the sealed pipeline mode, the Metal binary archives (`archive_count` +/// paths) and the kernel pack (NULL for none). Call it before the first GPU +/// kernel; a later call fails. Returns 0, or -1 and a message in `error` +/// (at most `error_size` bytes with the terminating NUL). +MLX_API int mlx_metal_set_sealed_pipelines( + int mode, + const char* const* archive_paths, + size_t archive_count, + const char* kernel_pack_path, + char* error, + size_t error_size); + +/// The current sealed pipeline mode. +MLX_API int mlx_metal_sealed_pipelines_mode(void); + +/// Counts since the process started. A library hit is a generated kernel +/// source found in the precompiled metallib or in the kernel pack. +typedef struct mlx_metal_sealed_pipelines_counts { + uint64_t archive_hits; + uint64_t archive_misses; + uint64_t library_hits; + uint64_t library_misses; +} mlx_metal_sealed_pipelines_counts; + +MLX_API void mlx_metal_get_sealed_pipelines_counts( + mlx_metal_sealed_pipelines_counts* counts); + +/// The misses (at most 1024), one per line. The caller frees the string. +MLX_API char* mlx_metal_sealed_pipelines_misses(void); + +/// Starts to record the pipelines (function and constant values) and the +/// generated kernel sources that the GPU builds. Start it before the first +/// GPU kernel to record a whole workload. Record in REPORT mode, so that MLX +/// selects the same kernels as in ENFORCE mode. +MLX_API void mlx_metal_start_pipeline_recording(void); + +/// Stops the recording and returns it as JSON (schema +/// "mlx-metal-pipelines/1"), or NULL on error. The caller frees the string. +MLX_API char* mlx_metal_stop_pipeline_recording(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mlx/backend/cpu/compiled.cpp b/mlx/backend/cpu/compiled.cpp index 5ef78cba30..52fa3edab4 100644 --- a/mlx/backend/cpu/compiled.cpp +++ b/mlx/backend/cpu/compiled.cpp @@ -14,6 +14,7 @@ #include "mlx/backend/common/compiled.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/jit_compiler.h" +#include "mlx/backend/gpu/device_info.h" #include "mlx/device.h" #include "mlx/graph_utils.h" #include "mlx/version.h" @@ -54,7 +55,10 @@ static CompilerCache& cache() { // usable C++ compiler (MSVC or clang-cl on Windows). namespace detail { bool compile_available_for_device(const Device& device) { - return device == Device::gpu || JitCompiler::available(); + if (device == Device::gpu) { + return gpu::can_build_kernels(); + } + return JitCompiler::available(); } } // namespace detail diff --git a/mlx/backend/cuda/device_info.cpp b/mlx/backend/cuda/device_info.cpp index a4a15e2850..409329ad02 100644 --- a/mlx/backend/cuda/device_info.cpp +++ b/mlx/backend/cuda/device_info.cpp @@ -208,6 +208,10 @@ bool is_available() { return true; } +bool can_build_kernels() { + return true; +} + int device_count() { int count = 0; cudaGetDeviceCount(&count); diff --git a/mlx/backend/gpu/device_info.h b/mlx/backend/gpu/device_info.h index 7adb7f0b7c..7a793bf5fa 100644 --- a/mlx/backend/gpu/device_info.h +++ b/mlx/backend/gpu/device_info.h @@ -12,6 +12,12 @@ namespace mlx::core::gpu { MLX_API bool is_available(); +/** + * Whether the GPU backend can build kernels at run time. When it cannot + * (Metal sealed pipelines), `compile` runs functions unfused. + */ +MLX_API bool can_build_kernels(); + /** * Get the number of available GPU devices. */ diff --git a/mlx/backend/metal/CMakeLists.txt b/mlx/backend/metal/CMakeLists.txt index cccaad8a5c..162b9221a7 100644 --- a/mlx/backend/metal/CMakeLists.txt +++ b/mlx/backend/metal/CMakeLists.txt @@ -155,6 +155,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/ternary.cpp ${CMAKE_CURRENT_SOURCE_DIR}/unary.cpp ${CMAKE_CURRENT_SOURCE_DIR}/resident.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sealed_pipelines.cpp ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp) if(NOT MLX_METAL_PATH) diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index 66f599e35e..432a233169 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -1,5 +1,7 @@ // Copyright © 2023-2024 Apple Inc. +#include + #include #include #include @@ -37,6 +39,19 @@ namespace { constexpr const char* default_mtllib_path = METAL_PATH; +struct PendingSealedPipelines { + std::mutex mtx; + bool set{false}; + SealedPipelines mode{SealedPipelines::off}; + std::vector archive_paths; + std::string kernel_pack_path; +}; + +PendingSealedPipelines& pending_sealed_pipelines() { + static auto* pending = new PendingSealedPipelines; + return *pending; +} + void set_compile_options( MTL::CompileOptions* mtl_options, const CompileOptions& compile_options) { @@ -657,7 +672,10 @@ MTL::ComputeCommandEncoder* CommandEncoder::get_command_encoder() { Device::Device() : device_(load_device()), residency_sets_(device_.get()) { auto pool = new_scoped_memory_pool(); + // Before the first pipeline, so that every pipeline is sealed. + apply_sealed_pipelines(); default_library_ = NS::TransferPtr(load_default_library(device_.get())); + library_labels_[default_library_.get()] = std::string(kDefaultLibraryLabel); std::string expert_qmm_env = env::get_var("MLX_GATHER_QMM_EXPERT_SLICES", ""); std::transform( @@ -747,6 +765,46 @@ Device::Device() : device_(load_device()), residency_sets_(device_.get()) { Device::~Device() = default; +void Device::set_pending_sealed_pipelines( + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path) { + auto& pending = pending_sealed_pipelines(); + std::lock_guard lock(pending.mtx); + pending.set = true; + pending.mode = mode; + pending.archive_paths = archive_paths; + pending.kernel_pack_path = kernel_pack_path; +} + +void Device::apply_sealed_pipelines() { + auto& pending = pending_sealed_pipelines(); + std::lock_guard plock(pending.mtx); + if (!pending.set) { + return; + } + auto& sealed = sealed_pipelines_state(); + if (pending.mode == SealedPipelines::off && + sealed.mode() == SealedPipelines::off) { + pending.set = false; + return; + } + std::unique_lock klock(kernel_mtx_); + std::unique_lock llock(library_mtx_); + if (built_code_.load()) { + pending.set = false; + throw std::runtime_error( + "[metal::set_sealed_pipelines] Set sealed pipelines before the first " + "GPU kernel."); + } + sealed.configure( + device_.get(), + pending.mode, + pending.archive_paths, + pending.kernel_pack_path); + pending.set = false; +} + MTL::Library* Device::get_library( const std::string& name, const std::string& path /* = "" */) { @@ -764,12 +822,17 @@ MTL::Library* Device::get_library( auto new_lib = load_library(device_.get(), name, path.c_str()); library_map_.insert({name, NS::TransferPtr(new_lib)}); + library_labels_[new_lib] = "metallib:" + name; return new_lib; } NS::SharedPtr Device::build_library_( const std::string& source_string, const CompileOptions& compile_options) { + if (sealed_pipelines_state().mode() == SealedPipelines::enforce) { + throw std::runtime_error(sealed_miss_message("a Metal source library")); + } + built_code_ = true; auto pool = new_scoped_memory_pool(); auto ns_code = @@ -834,9 +897,32 @@ NS::SharedPtr Device::get_function_( NS::String::string(specialized_name.c_str(), NS::ASCIIStringEncoding)); desc->setConstantValues(mtl_func_consts); - // Pull kernel from library + // Sealed: the specialized function must come from a binary archive. + auto& sealed = sealed_pipelines_state(); + auto mode = sealed.mode(); + if (mode != SealedPipelines::off) { + desc->setBinaryArchives(sealed.archives()); + desc->setOptions(MTL::FunctionOptionFailOnBinaryArchiveMiss); + } + + // Pull kernel from library. Metal ignores the miss option when no archive + // is given, so an empty archive set is a miss. NS::Error* error = nullptr; - auto mtl_function = NS::TransferPtr(mtl_lib->newFunction(desc, &error)); + NS::SharedPtr mtl_function; + if (mode == SealedPipelines::off || sealed.archives()->count() > 0) { + mtl_function = NS::TransferPtr(mtl_lib->newFunction(desc, &error)); + } + if (!mtl_function && mode != SealedPipelines::off) { + auto what = fmt::format("function {} ({})", specialized_name, name); + sealed.count_archive_miss(what); + if (mode == SealedPipelines::enforce) { + throw std::runtime_error(sealed_miss_message(what)); + } + desc->setBinaryArchives(nullptr); + desc->setOptions(MTL::FunctionOptionNone); + error = nullptr; + mtl_function = NS::TransferPtr(mtl_lib->newFunction(desc, &error)); + } // Throw error if unable to build metal function if (!mtl_function) { @@ -876,10 +962,60 @@ NS::SharedPtr Device::get_kernel_( return kernel; } +NS::SharedPtr Device::get_sealed_kernel_( + const std::string& name, + const MTL::Function* mtl_function, + const MTL::LinkedFunctions* linked_functions) { + if (!mtl_function) { + throw std::runtime_error( + fmt::format("[metal::Device] Unable to load kernel {}\n", name)); + } + auto pool = new_scoped_memory_pool(); + auto& sealed = sealed_pipelines_state(); + auto desc = MTL::ComputePipelineDescriptor::alloc()->init()->autorelease(); + desc->setComputeFunction(mtl_function); + if (linked_functions) { + desc->setLinkedFunctions(linked_functions); + } + desc->setBinaryArchives(sealed.archives()); + // Metal ignores the miss option when no archive is given. + NS::Error* error = nullptr; + NS::SharedPtr kernel; + if (sealed.archives()->count() > 0) { + kernel = NS::TransferPtr(device_->newComputePipelineState( + desc, MTL::PipelineOptionFailOnBinaryArchiveMiss, nullptr, &error)); + } + if (kernel) { + sealed.count_archive_hit(); + return kernel; + } + auto what = fmt::format("pipeline {}", name); + sealed.count_archive_miss(what); + if (sealed.mode() == SealedPipelines::enforce) { + throw std::runtime_error(sealed_miss_message(what)); + } + desc->setBinaryArchives(nullptr); + error = nullptr; + kernel = NS::TransferPtr(device_->newComputePipelineState( + desc, MTL::PipelineOptionNone, nullptr, &error)); + if (!kernel) { + std::ostringstream msg; + msg << "[metal::Device] Unable to load kernel " << name << "\n"; + if (error) { + msg << error->localizedDescription()->utf8String() << "\n"; + } + throw std::runtime_error(msg.str()); + } + return kernel; +} + NS::SharedPtr Device::get_kernel_( const std::string& name, const MTL::Function* mtl_function, const MTL::LinkedFunctions* linked_functions) { + if (sealed_pipelines_state().mode() != SealedPipelines::off) { + return get_sealed_kernel_(name, mtl_function, linked_functions); + } // Check inputs if (!linked_functions) { return get_kernel_(name, mtl_function); @@ -932,15 +1068,95 @@ MTL::Library* Device::get_library( return it->second.get(); } - auto mtl_lib = build_library_(builder(), compile_options); + auto& sealed = sealed_pipelines_state(); + if (sealed.mode() == SealedPipelines::off && !sealed.recording()) { + auto mtl_lib = build_library_(builder(), compile_options); + library_map_.insert({name, mtl_lib}); + return mtl_lib.get(); + } + std::string label; + auto mtl_lib = get_sealed_library_(name, compile_options, builder, label); + library_labels_.emplace(mtl_lib.get(), std::move(label)); library_map_.insert({name, mtl_lib}); return mtl_lib.get(); } +bool Device::in_default_library_(const std::string& source) { + auto names = SealedPipelinesState::host_names(source); + if (names.empty()) { + return false; + } + if (!default_functions_loaded_) { + auto pool = new_scoped_memory_pool(); + auto functions = default_library_->functionNames(); + for (NS::UInteger i = 0; i < functions->count(); ++i) { + auto fn = static_cast(functions->object(i)); + default_functions_.insert(fn->utf8String()); + } + default_functions_loaded_ = true; + } + return std::all_of(names.begin(), names.end(), [this](const auto& n) { + return default_functions_.count(n) > 0; + }); +} + +NS::SharedPtr Device::get_sealed_library_( + const std::string& name, + const CompileOptions& compile_options, + const std::function& builder, + std::string& label) { + auto& sealed = sealed_pipelines_state(); + auto mode = sealed.mode(); + auto source = builder(); + auto key = SealedPipelinesState::source_key(source, compile_options); + bool in_default = in_default_library_(source); + NS::SharedPtr mtl_lib; + label = in_default ? std::string(kDefaultLibraryLabel) : key; + if (mode == SealedPipelines::off) { + mtl_lib = build_library_(source, compile_options); + } else if (auto bytes = sealed.pack_entry(key); !bytes.empty()) { + auto pool = new_scoped_memory_pool(); + auto data = dispatch_data_create( + bytes.data(), bytes.size(), nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + NS::Error* error = nullptr; + mtl_lib = NS::TransferPtr(device_->newLibrary(data, &error)); + dispatch_release(data); + if (!mtl_lib) { + throw std::runtime_error( + fmt::format( + "[metal::Device] Cannot load kernel pack entry {} for {}: {}", + key, + name, + error ? error->localizedDescription()->utf8String() + : "unknown error")); + } + label = key; + sealed.count_library_hit(); + } else if (in_default) { + mtl_lib = default_library_; + sealed.count_library_hit(); + } else { + auto what = fmt::format("generated library {} (source {})", name, key); + sealed.count_library_miss(what); + if (mode == SealedPipelines::enforce) { + throw std::runtime_error(sealed_miss_message(what)); + } + mtl_lib = build_library_(source, compile_options); + } + if (label != kDefaultLibraryLabel) { + sealed.record_library(key, name, compile_options, source); + } + return mtl_lib; +} + void Device::clear_library(const std::string& name) { std::unique_lock wlock(library_mtx_); if (auto it = library_map_.find(name); it != library_map_.end()) { - library_kernels_.erase(it->second.get()); + // A sealed lookup can map a name to the default library. + if (it->second.get() != default_library_.get()) { + library_kernels_.erase(it->second.get()); + library_labels_.erase(it->second.get()); + } library_map_.erase(it); } } @@ -975,6 +1191,7 @@ MTL::ComputePipelineState* Device::get_kernel_( } auto pool = new_scoped_memory_pool(); + built_code_ = true; // Pull kernel from library auto mtl_function = get_function_(base_name, hash_name, func_consts, mtl_lib); @@ -987,6 +1204,20 @@ MTL::ComputePipelineState* Device::get_kernel_( // Add kernel to cache kernel_map_.insert({hash_name, kernel}); + auto& sealed = sealed_pipelines_state(); + if (sealed.recording()) { + std::string label = "unknown"; + { + std::shared_lock lock(library_mtx_); + if (auto it = library_labels_.find(mtl_lib); + it != library_labels_.end()) { + label = it->second; + } + } + sealed.record_pipeline( + label, base_name, hash_name, func_consts, linked_functions.size()); + } + return kernel.get(); } @@ -1085,7 +1316,9 @@ bool is_nax_available() { return can_use_nax; }; static bool is_nax_available_ = _check_nax(); - return is_nax_available_; + // Sealed pipelines use the non-NAX kernels. The offline translator + // (metal-tt) cannot build NAX kernels into a binary archive. + return is_nax_available_ && sealed_pipelines() == SealedPipelines::off; #endif } diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 92e6b4589b..d80d65bb95 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -16,6 +16,7 @@ #include "mlx/backend/common/gemma4_expert_qmm.h" #include "mlx/backend/common/metal_kernel.h" #include "mlx/backend/metal/resident.h" +#include "mlx/backend/metal/sealed_pipelines.h" #include "mlx/device.h" namespace mlx::core::metal { @@ -366,6 +367,14 @@ class MLX_API Device { return residency_sets_; } + // Sealed pipelines (metal.h). The settings wait until the device exists; + // apply_sealed_pipelines() throws if the device already built GPU code. + static void set_pending_sealed_pipelines( + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path); + void apply_sealed_pipelines(); + bool gemma4_expert_qmm_requested() const { return gemma4_expert_qmm_requested_; } @@ -430,6 +439,18 @@ class MLX_API Device { const std::string& name, const MTL::Function* mtl_function, const MTL::LinkedFunctions* linked_functions); + NS::SharedPtr get_sealed_kernel_( + const std::string& name, + const MTL::Function* mtl_function, + const MTL::LinkedFunctions* linked_functions); + + // Library lookup for a generated source in sealed or recording mode. + NS::SharedPtr get_sealed_library_( + const std::string& name, + const CompileOptions& compile_options, + const std::function& builder, + std::string& label); + bool in_default_library_(const std::string& source); MTL::ComputePipelineState* get_kernel_( const std::string& base_name, @@ -445,6 +466,11 @@ class MLX_API Device { std::shared_mutex library_mtx_; std::unordered_map> library_map_; NS::SharedPtr default_library_; + // Record labels of libraries: "mlx" or a generated source's key. + std::unordered_map library_labels_; + std::unordered_set default_functions_; + bool default_functions_loaded_{false}; + std::atomic built_code_{false}; bool gemma4_expert_qmm_requested_{false}; bool gemma4_expert_qmm_trust_sorted_{false}; bool gemma4_expert_qmm_aot_available_{false}; diff --git a/mlx/backend/metal/device_info.cpp b/mlx/backend/metal/device_info.cpp index 3902e6b5e0..7e61e5884c 100644 --- a/mlx/backend/metal/device_info.cpp +++ b/mlx/backend/metal/device_info.cpp @@ -12,6 +12,10 @@ bool is_available() { return metal::is_available(); } +bool can_build_kernels() { + return metal::sealed_pipelines() == metal::SealedPipelines::off; +} + int device_count() { try { metal::device(Device::gpu); diff --git a/mlx/backend/metal/metal.h b/mlx/backend/metal/metal.h index d686c2971a..b152717172 100644 --- a/mlx/backend/metal/metal.h +++ b/mlx/backend/metal/metal.h @@ -2,9 +2,11 @@ #pragma once +#include #include #include #include +#include #include "mlx/api.h" @@ -27,4 +29,37 @@ MLX_API const MLX_API void set_metallib_path(const std::string& path); MLX_API const std::string& get_metallib_path(); +/* Sealed pipelines: MLX builds no GPU code at run time. A generated kernel + * source must be in the precompiled metallib or in the kernel pack, and each + * pipeline must be in a binary archive. `compile` runs functions unfused, and + * MLX uses the non-NAX kernels (metal-tt cannot build NAX kernels offline). + * In report mode a miss builds the code and is counted; in enforce mode a + * miss throws. */ +enum class SealedPipelines { off = 0, report = 1, enforce = 2 }; + +/* Set the mode, the binary archives and the kernel pack. Call before the + * first GPU kernel; a later call throws. */ +MLX_API void set_sealed_pipelines( + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path = ""); +MLX_API SealedPipelines sealed_pipelines(); + +struct SealedPipelinesReport { + SealedPipelines mode; + uint64_t archive_hits; + uint64_t archive_misses; + uint64_t library_hits; + uint64_t library_misses; + std::vector misses; +}; +MLX_API SealedPipelinesReport sealed_pipelines_report(); + +/* Record the pipelines (function and constant values) and the generated + * kernel sources that the GPU builds. Start before the first GPU kernel to + * record a whole workload. Record in report mode, so that MLX selects the + * same kernels as in enforce mode. Stop returns the record as JSON. */ +MLX_API void start_pipeline_recording(); +MLX_API std::string stop_pipeline_recording(); + } // namespace mlx::core::metal diff --git a/mlx/backend/metal/no_metal.cpp b/mlx/backend/metal/no_metal.cpp index 3b72ad005a..7171f8e51e 100644 --- a/mlx/backend/metal/no_metal.cpp +++ b/mlx/backend/metal/no_metal.cpp @@ -28,6 +28,30 @@ const std::string& get_metallib_path() { "[metal::get_metallib_path] Cannot get metallib path without metal backend"); } +void set_sealed_pipelines( + SealedPipelines mode, + const std::vector&, + const std::string&) { + if (mode != SealedPipelines::off) { + throw std::runtime_error( + "[metal::set_sealed_pipelines] Cannot seal pipelines without metal backend"); + } +} + +SealedPipelines sealed_pipelines() { + return SealedPipelines::off; +} + +SealedPipelinesReport sealed_pipelines_report() { + return {SealedPipelines::off, 0, 0, 0, 0, {}}; +} + +void start_pipeline_recording() {} + +std::string stop_pipeline_recording() { + return {}; +} + } // namespace metal } // namespace mlx::core diff --git a/mlx/backend/metal/sealed_pipelines.cpp b/mlx/backend/metal/sealed_pipelines.cpp new file mode 100644 index 0000000000..9fc922d81a --- /dev/null +++ b/mlx/backend/metal/sealed_pipelines.cpp @@ -0,0 +1,577 @@ +// Copyright © 2026 Apple Inc. + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "mlx/backend/common/sealed_pipelines.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/sealed_pipelines.h" +#include "mlx/backend/metal/utils.h" + +namespace mlx::core::metal { + +namespace { + +constexpr char kPackMagic[8] = {'M', 'L', 'X', 'K', 'P', 'A', 'C', 'K'}; +constexpr uint32_t kPackVersion = 1; +constexpr size_t kPackEntrySize = 32 + 8 + 8; +constexpr size_t kMaxMisses = 1024; + +std::string read_file(const std::string& path) { + int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + throw std::runtime_error( + fmt::format( + "[metal::set_sealed_pipelines] Cannot open {}: {}", + path, + std::strerror(errno))); + } + std::string bytes; + struct stat st; + if (::fstat(fd, &st) == 0 && st.st_size > 0) { + bytes.reserve(static_cast(st.st_size)); + } + char buffer[1 << 16]; + off_t offset = 0; + while (true) { + // pread: a /dev/fd path shares the file offset of the original descriptor. + auto n = ::pread(fd, buffer, sizeof(buffer), offset); + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0) { + auto err = errno; + ::close(fd); + throw std::runtime_error( + fmt::format( + "[metal::set_sealed_pipelines] Cannot read {}: {}", + path, + std::strerror(err))); + } + if (n == 0) { + break; + } + bytes.append(buffer, static_cast(n)); + offset += n; + } + ::close(fd); + return bytes; +} + +uint64_t read_le(const char* p, size_t n) { + uint64_t v = 0; + for (size_t i = 0; i < n; ++i) { + v |= static_cast(static_cast(p[i])) << (8 * i); + } + return v; +} + +std::string hex(const unsigned char* p, size_t n) { + static constexpr char digits[] = "0123456789abcdef"; + std::string out(2 * n, '0'); + for (size_t i = 0; i < n; ++i) { + out[2 * i] = digits[p[i] >> 4]; + out[2 * i + 1] = digits[p[i] & 0xf]; + } + return out; +} + +void append_json_string(std::string& out, std::string_view s) { + out += '"'; + for (unsigned char c : s) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + default: + if (c < 0x20) { + out += fmt::format("\\u{:04x}", c); + } else { + out += static_cast(c); + } + } + } + out += '"'; +} + +std::string constants_json(const MTLFCList& constants) { + std::string out = "["; + bool first = true; + for (auto [value, type, index] : constants) { + if (!first) { + out += ", "; + } + first = false; + std::string type_name; + std::string value_text; + switch (type) { + case MTL::DataTypeBool: + type_name = "bool"; + value_text = *static_cast(value) ? "true" : "false"; + break; + case MTL::DataTypeInt: + type_name = "int"; + value_text = std::to_string(*static_cast(value)); + break; + case MTL::DataTypeUInt: + type_name = "uint"; + value_text = std::to_string(*static_cast(value)); + break; + case MTL::DataTypeShort: + type_name = "short"; + value_text = std::to_string(*static_cast(value)); + break; + case MTL::DataTypeUShort: + type_name = "ushort"; + value_text = std::to_string(*static_cast(value)); + break; + case MTL::DataTypeFloat: + type_name = "float"; + value_text = fmt::format("{}", *static_cast(value)); + break; + default: + throw std::runtime_error( + fmt::format( + "[metal::record_pipeline] Unsupported function constant type {}.", + static_cast(type))); + } + out += fmt::format( + "{{\"index\": {}, \"type\": \"{}\", \"value\": {}}}", + index, + type_name, + value_text); + } + out += "]"; + return out; +} + +const char* mode_name(SealedPipelines mode) { + switch (mode) { + case SealedPipelines::off: + return "off"; + case SealedPipelines::report: + return "report"; + case SealedPipelines::enforce: + return "enforce"; + } + return "unknown"; +} + +} // namespace + +SealedPipelinesState& sealed_pipelines_state() { + // Leaked like the device: kernels can resolve during process teardown. + static auto* state = new SealedPipelinesState; + return *state; +} + +std::string sealed_miss_message(std::string_view what) { + return fmt::format( + "[metal::Device] Sealed pipelines: {} is not in the shipped GPU code. " + "Runtime Metal compilation is refused.", + what); +} + +void SealedPipelinesState::configure( + MTL::Device* device, + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path) { + if (mode != SealedPipelines::off) { + if (!__builtin_available(macOS 15, iOS 18, tvOS 18, visionOS 2, *)) { + throw std::runtime_error( + "[metal::set_sealed_pipelines] Sealed pipelines need macOS 15, " + "iOS 18, tvOS 18 or visionOS 2."); + } + } + + auto pool = new_scoped_memory_pool(); + std::vector> refs; + std::vector objects; + for (auto& path : archive_paths) { + auto desc = NS::TransferPtr(MTL::BinaryArchiveDescriptor::alloc()->init()); + desc->setUrl( + NS::URL::fileURLWithPath( + NS::String::string(path.c_str(), NS::UTF8StringEncoding))); + NS::Error* error = nullptr; + auto archive = + NS::TransferPtr(device->newBinaryArchive(desc.get(), &error)); + if (!archive) { + throw std::runtime_error( + fmt::format( + "[metal::set_sealed_pipelines] Cannot load binary archive {}: {}", + path, + error ? error->localizedDescription()->utf8String() + : "unknown error")); + } + objects.push_back(archive.get()); + refs.push_back(std::move(archive)); + } + + std::shared_ptr pack_file; + std::unordered_map pack; + if (!kernel_pack_path.empty()) { + pack_file = + std::make_shared(read_file(kernel_pack_path)); + const std::string& pack_bytes = *pack_file; + auto fail = [&](const char* why) { + throw std::runtime_error( + fmt::format( + "[metal::set_sealed_pipelines] Invalid kernel pack {}: {}.", + kernel_pack_path, + why)); + }; + if (pack_bytes.size() < 16 || + std::memcmp(pack_bytes.data(), kPackMagic, 8) != 0) { + fail("bad header"); + } + if (read_le(pack_bytes.data() + 8, 4) != kPackVersion) { + fail("unsupported version"); + } + uint64_t count = read_le(pack_bytes.data() + 12, 4); + if (count > (pack_bytes.size() - 16) / kPackEntrySize) { + fail("truncated index"); + } + for (uint64_t i = 0; i < count; ++i) { + const char* entry = pack_bytes.data() + 16 + i * kPackEntrySize; + auto key = + hex(reinterpret_cast(entry), + CC_SHA256_DIGEST_LENGTH); + uint64_t offset = read_le(entry + 32, 8); + uint64_t size = read_le(entry + 40, 8); + if (size == 0 || offset > pack_bytes.size() || + size > pack_bytes.size() - offset) { + fail("entry out of bounds"); + } + if (!pack.emplace(key, std::string_view(pack_bytes.data() + offset, size)) + .second) { + fail("duplicate entry"); + } + } + } + + auto array = NS::RetainPtr(NS::Array::array(objects.data(), objects.size())); + archives_ = array; + archive_refs_ = std::move(refs); + pack_bytes_ = std::move(pack_file); + pack_ = std::move(pack); + mode_.store(mode, std::memory_order_release); +} + +std::string_view SealedPipelinesState::pack_entry( + const std::string& key) const { + if (auto it = pack_.find(key); it != pack_.end()) { + return it->second; + } + return {}; +} + +std::string SealedPipelinesState::source_key( + const std::string& source, + const CompileOptions& options) { + std::string header = + fmt::format("mlx-sealed-source-v1\n{}\n", options.serialize()); + CC_SHA256_CTX ctx; + CC_SHA256_Init(&ctx); + CC_SHA256_Update(&ctx, header.data(), static_cast(header.size())); + size_t done = 0; + while (done < source.size()) { + auto n = std::min(source.size() - done, 1u << 30); + CC_SHA256_Update(&ctx, source.data() + done, static_cast(n)); + done += n; + } + unsigned char digest[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256_Final(digest, &ctx); + return hex(digest, sizeof(digest)); +} + +std::vector SealedPipelinesState::host_names( + const std::string& source) { + static constexpr std::string_view open = "host_name(\""; + std::vector names; + size_t pos = 0; + while ((pos = source.find(open, pos)) != std::string::npos) { + pos += open.size(); + auto end = source.find('"', pos); + if (end == std::string::npos) { + break; + } + names.emplace_back(source.substr(pos, end - pos)); + pos = end + 1; + } + return names; +} + +void SealedPipelinesState::count_library_miss(std::string what) { + library_misses_++; + std::lock_guard lock(mtx_); + if (misses_.size() < kMaxMisses) { + misses_.push_back(std::move(what)); + } +} + +void SealedPipelinesState::count_archive_miss(std::string what) { + archive_misses_++; + std::lock_guard lock(mtx_); + if (misses_.size() < kMaxMisses) { + misses_.push_back(std::move(what)); + } +} + +SealedPipelinesReport SealedPipelinesState::report() const { + SealedPipelinesReport r; + r.mode = mode(); + r.archive_hits = archive_hits_.load(); + r.archive_misses = archive_misses_.load(); + r.library_hits = library_hits_.load(); + r.library_misses = library_misses_.load(); + std::lock_guard lock(mtx_); + r.misses = misses_; + return r; +} + +void SealedPipelinesState::start_recording() { + std::lock_guard lock(mtx_); + recorded_libraries_.clear(); + recorded_library_order_.clear(); + recorded_pipelines_.clear(); + recorded_pipeline_order_.clear(); + recording_.store(true, std::memory_order_release); +} + +void SealedPipelinesState::record_library( + const std::string& key, + const std::string& name, + const CompileOptions& options, + const std::string& source) { + std::lock_guard lock(mtx_); + if (!recording_.load(std::memory_order_acquire)) { + return; + } + auto [it, inserted] = recorded_libraries_.emplace( + key, RecordedLibrary{name, options.serialize(), source}); + if (inserted) { + recorded_library_order_.push_back(key); + } +} + +void SealedPipelinesState::record_pipeline( + const std::string& library, + const std::string& function, + const std::string& specialized_name, + const MTLFCList& constants, + size_t linked_function_count) { + auto constants_text = constants_json(constants); + std::lock_guard lock(mtx_); + if (!recording_.load(std::memory_order_acquire)) { + return; + } + auto id = library + "#" + specialized_name; + auto [it, inserted] = recorded_pipelines_.emplace( + id, + RecordedPipeline{ + library, + function, + specialized_name, + std::move(constants_text), + linked_function_count}); + if (inserted) { + recorded_pipeline_order_.push_back(id); + } +} + +std::string SealedPipelinesState::stop_recording( + const std::string& architecture) { + std::lock_guard lock(mtx_); + recording_.store(false, std::memory_order_release); + std::string out = "{\n \"schema\": \"mlx-metal-pipelines/1\",\n"; + out += " \"architecture\": "; + append_json_string(out, architecture); + out += ",\n \"sealed_mode\": "; + append_json_string(out, mode_name(mode())); + out += ",\n \"libraries\": ["; + bool first = true; + for (auto& key : recorded_library_order_) { + auto& lib = recorded_libraries_.at(key); + out += first ? "\n {" : ",\n {"; + first = false; + out += "\"key\": "; + append_json_string(out, key); + out += ", \"name\": "; + append_json_string(out, lib.name); + out += fmt::format(", \"math_mode\": {}, \"source\": ", lib.math_mode); + append_json_string(out, lib.source); + out += "}"; + } + out += first ? "],\n" : "\n ],\n"; + out += " \"pipelines\": ["; + first = true; + for (auto& id : recorded_pipeline_order_) { + auto& p = recorded_pipelines_.at(id); + out += first ? "\n {" : ",\n {"; + first = false; + out += "\"library\": "; + append_json_string(out, p.library); + out += ", \"function\": "; + append_json_string(out, p.function); + out += ", \"name\": "; + append_json_string(out, p.specialized_name); + out += ", \"constants\": " + p.constants_json; + if (p.linked_function_count > 0) { + out += fmt::format(", \"linked_functions\": {}", p.linked_function_count); + } + out += "}"; + } + out += first ? "]\n}\n" : "\n ]\n}\n"; + recorded_libraries_.clear(); + recorded_library_order_.clear(); + recorded_pipelines_.clear(); + recorded_pipeline_order_.clear(); + return out; +} + +void set_sealed_pipelines( + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path) { + Device::set_pending_sealed_pipelines(mode, archive_paths, kernel_pack_path); + // Builds the device if needed. A new device applies the pending settings + // before it makes its first pipeline. + device(mlx::core::Device::gpu).apply_sealed_pipelines(); +} + +SealedPipelines sealed_pipelines() { + return sealed_pipelines_state().mode(); +} + +SealedPipelinesReport sealed_pipelines_report() { + return sealed_pipelines_state().report(); +} + +void start_pipeline_recording() { + sealed_pipelines_state().start_recording(); +} + +std::string stop_pipeline_recording() { + std::string arch; + try { + arch = device(mlx::core::Device::gpu).get_architecture(); + } catch (...) { + } + return sealed_pipelines_state().stop_recording(arch); +} + +} // namespace mlx::core::metal + +namespace { + +char* copy_c_string(const std::string& s) { + auto* out = static_cast(std::malloc(s.size() + 1)); + if (out != nullptr) { + std::memcpy(out, s.data(), s.size()); + out[s.size()] = '\0'; + } + return out; +} + +} // namespace + +extern "C" int mlx_metal_set_sealed_pipelines( + int mode, + const char* const* archive_paths, + size_t archive_count, + const char* kernel_pack_path, + char* error, + size_t error_size) { + auto set_error = [&](const char* text) { + if (error != nullptr && error_size > 0) { + std::snprintf(error, error_size, "%s", text); + } + }; + set_error(""); + if (mode < MLX_METAL_SEALED_PIPELINES_OFF || + mode > MLX_METAL_SEALED_PIPELINES_ENFORCE || + (archive_count > 0 && archive_paths == nullptr)) { + set_error("[metal::set_sealed_pipelines] Invalid arguments."); + return -1; + } + try { + std::vector archives; + for (size_t i = 0; i < archive_count; ++i) { + if (archive_paths[i] == nullptr) { + set_error("[metal::set_sealed_pipelines] Null archive path."); + return -1; + } + archives.emplace_back(archive_paths[i]); + } + mlx::core::metal::set_sealed_pipelines( + static_cast(mode), + archives, + kernel_pack_path == nullptr ? "" : kernel_pack_path); + return 0; + } catch (const std::exception& e) { + set_error(e.what()); + } catch (...) { + set_error("[metal::set_sealed_pipelines] Unknown error."); + } + return -1; +} + +extern "C" int mlx_metal_sealed_pipelines_mode(void) { + return static_cast(mlx::core::metal::sealed_pipelines()); +} + +extern "C" void mlx_metal_get_sealed_pipelines_counts( + mlx_metal_sealed_pipelines_counts* counts) { + if (counts == nullptr) { + return; + } + auto r = mlx::core::metal::sealed_pipelines_report(); + counts->archive_hits = r.archive_hits; + counts->archive_misses = r.archive_misses; + counts->library_hits = r.library_hits; + counts->library_misses = r.library_misses; +} + +extern "C" char* mlx_metal_sealed_pipelines_misses(void) { + auto r = mlx::core::metal::sealed_pipelines_report(); + std::string out; + for (auto& m : r.misses) { + out += m; + out += '\n'; + } + return copy_c_string(out); +} + +extern "C" void mlx_metal_start_pipeline_recording(void) { + mlx::core::metal::start_pipeline_recording(); +} + +extern "C" char* mlx_metal_stop_pipeline_recording(void) { + try { + return copy_c_string(mlx::core::metal::stop_pipeline_recording()); + } catch (...) { + return nullptr; + } +} diff --git a/mlx/backend/metal/sealed_pipelines.h b/mlx/backend/metal/sealed_pipelines.h new file mode 100644 index 0000000000..a3165d4d4c --- /dev/null +++ b/mlx/backend/metal/sealed_pipelines.h @@ -0,0 +1,125 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/backend/common/metal_kernel.h" +#include "mlx/backend/metal/metal.h" + +namespace mlx::core::metal { + +using MTLFCList = + std::vector>; + +// The label of the precompiled metallib in a pipeline record. +inline constexpr std::string_view kDefaultLibraryLabel = "mlx"; + +// Process-wide state of sealed pipelines and of pipeline recording. +class SealedPipelinesState { + public: + SealedPipelines mode() const { + return mode_.load(std::memory_order_acquire); + } + + // Load the archives and the kernel pack, then set the mode. Throws if a + // file cannot be read or parsed. Call it with the device's locks held. + void configure( + MTL::Device* device, + SealedPipelines mode, + const std::vector& archive_paths, + const std::string& kernel_pack_path); + + // The loaded binary archives (an empty array if there are none). + NS::Array* archives() const { + return archives_.get(); + } + + // The metallib bytes for a generated source, or an empty view. + std::string_view pack_entry(const std::string& key) const; + + // SHA-256 (hex) of the source and the options that select its code. + static std::string source_key( + const std::string& source, + const CompileOptions& options); + + // The kernel names in `[[host_name("...")]]` attributes of the source. + static std::vector host_names(const std::string& source); + + void count_library_hit() { + library_hits_++; + } + void count_archive_hit() { + archive_hits_++; + } + void count_library_miss(std::string what); + void count_archive_miss(std::string what); + SealedPipelinesReport report() const; + + bool recording() const { + return recording_.load(std::memory_order_acquire); + } + void start_recording(); + std::string stop_recording(const std::string& architecture); + void record_library( + const std::string& key, + const std::string& name, + const CompileOptions& options, + const std::string& source); + void record_pipeline( + const std::string& library, + const std::string& function, + const std::string& specialized_name, + const MTLFCList& constants, + size_t linked_function_count); + + private: + struct RecordedLibrary { + std::string name; + int math_mode; + std::string source; + }; + struct RecordedPipeline { + std::string library; + std::string function; + std::string specialized_name; + std::string constants_json; + size_t linked_function_count; + }; + + std::atomic mode_{SealedPipelines::off}; + NS::SharedPtr archives_; + std::vector> archive_refs_; + std::shared_ptr pack_bytes_; + std::unordered_map pack_; + + std::atomic archive_hits_{0}; + std::atomic archive_misses_{0}; + std::atomic library_hits_{0}; + std::atomic library_misses_{0}; + + mutable std::mutex mtx_; + std::vector misses_; + + std::atomic recording_{false}; + std::unordered_map recorded_libraries_; + std::vector recorded_library_order_; + std::unordered_map recorded_pipelines_; + std::vector recorded_pipeline_order_; +}; + +SealedPipelinesState& sealed_pipelines_state(); + +// The error text for code that sealed pipelines do not ship. +std::string sealed_miss_message(std::string_view what); + +} // namespace mlx::core::metal diff --git a/mlx/backend/no_cpu/compiled.cpp b/mlx/backend/no_cpu/compiled.cpp index 09987e7d58..fda9ea6fcd 100644 --- a/mlx/backend/no_cpu/compiled.cpp +++ b/mlx/backend/no_cpu/compiled.cpp @@ -1,5 +1,6 @@ // Copyright © 2023-2026 Apple Inc. +#include "mlx/backend/gpu/device_info.h" #include "mlx/compile_impl.h" #include "mlx/primitives.h" @@ -10,7 +11,7 @@ namespace mlx::core { // device. namespace detail { bool compile_available_for_device(const Device& device) { - return device == Device::gpu; + return device == Device::gpu && gpu::can_build_kernels(); } } // namespace detail diff --git a/mlx/backend/no_gpu/device_info.cpp b/mlx/backend/no_gpu/device_info.cpp index 65d1cfccf1..07f53100db 100644 --- a/mlx/backend/no_gpu/device_info.cpp +++ b/mlx/backend/no_gpu/device_info.cpp @@ -8,6 +8,10 @@ bool is_available() { return false; } +bool can_build_kernels() { + return true; +} + int device_count() { return 0; } diff --git a/mlx/compile.cpp b/mlx/compile.cpp index fbb04aa6ed..3fc6404710 100644 --- a/mlx/compile.cpp +++ b/mlx/compile.cpp @@ -1186,6 +1186,11 @@ ArrayFnWithExtra compile( return fun(inputs); } + // The backend can stop building kernels after compile() returned. + if (!compile_available_for_device(default_device())) { + return fun(inputs); + } + // Find a cache entry with the correct inputs auto [entry, entries_ptr] = compile_cache_unsafe()->find(fun_id, inputs, shapeless, constants); diff --git a/scripts/sealed_pipelines.py b/scripts/sealed_pipelines.py new file mode 100644 index 0000000000..29ff05ab89 --- /dev/null +++ b/scripts/sealed_pipelines.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +# Copyright © 2026 Apple Inc. +"""Build the GPU code for MLX sealed pipelines offline. + +Input: pipeline recordings (mlx_metal_stop_pipeline_recording, schema +"mlx-metal-pipelines/1") and the precompiled mlx.metallib. Output: + + kernels.mlxpack the generated kernel sources compiled to metallibs + pipelines.mtlp-json the Metal pipelines script for metal-tt + .mtlarchive one Metal binary archive for each GPU architecture + manifest.json sizes and SHA-256 of the files above + + python3 scripts/sealed_pipelines.py build --metallib mlx.metallib \\ + --arch applegpu_g17s --macos-version 27.0 --out out rec1.json rec2.json + +The archives hold a copy of the AIR of each function they use. The tool +gives metal-tt a copy of mlx.metallib that has only the recorded functions +(metal-objcopy --keep-symbol), so an archive does not hold all of mlx.metallib. +Metal finds a pipeline by the AIR of its function, so the archive also hits +when MLX loads the functions from the full mlx.metallib. + +The tool only uses xcrun metal, metallib, metal-objcopy and metal-tt. It runs +no GPU code. +""" + +import argparse +import hashlib +import json +import os +import struct +import subprocess +import sys +import tempfile + +SCHEMA = "mlx-metal-pipelines/1" +PACK_MAGIC = b"MLXKPACK" +PACK_VERSION = 1 +DEFAULT_LABEL = "mlx" +MATH_MODES = {0: "safe", 1: "relaxed", 2: "fast"} +CONSTANT_TYPES = { + "bool": "ConstantBool", + "int": "ConstantInt", + "uint": "ConstantUInt", + "short": "ConstantShort", + "ushort": "ConstantUShort", + "float": "ConstantFloat", +} + + +class ToolError(Exception): + pass + + +def source_key(source, math_mode): + header = f"mlx-sealed-source-v1\n{math_mode}\n".encode() + return hashlib.sha256(header + source.encode()).hexdigest() + + +def load_recordings(paths): + """Merge recordings. Libraries are keyed by source hash and pipelines by + (library, specialized name).""" + libraries = {} + pipelines = {} + for path in paths: + with open(path) as f: + rec = json.load(f) + if rec.get("schema") != SCHEMA: + raise ToolError(f"{path}: schema is not {SCHEMA}") + for lib in rec.get("libraries", []): + key = lib["key"] + if source_key(lib["source"], lib["math_mode"]) != key: + raise ToolError(f"{path}: library {lib['name']} key mismatch") + libraries.setdefault(key, lib) + for p in rec.get("pipelines", []): + if p.get("linked_functions"): + raise ToolError(f"{path}: pipeline {p['name']} has linked functions") + lib = p["library"] + if lib != DEFAULT_LABEL and lib not in libraries: + raise ToolError( + f"{path}: pipeline {p['name']} names unknown library {lib}" + ) + id = (lib, p["name"]) + old = pipelines.get(id) + if old is not None and ( + old["function"] != p["function"] or old["constants"] != p["constants"] + ): + raise ToolError(f"{path}: pipeline {p['name']} differs") + pipelines.setdefault(id, p) + return libraries, pipelines + + +def run(cmd, cwd=None): + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) + if proc.returncode != 0: + raise ToolError( + f"{' '.join(cmd)} failed ({proc.returncode}):\n{proc.stdout}{proc.stderr}" + ) + + +def compile_library(key, lib, workdir, deployment_target): + src = os.path.join(workdir, f"{key}.metal") + air = os.path.join(workdir, f"{key}.air") + out = os.path.join(workdir, f"{key}.metallib") + with open(src, "w") as f: + f.write(lib["source"]) + math = MATH_MODES.get(lib["math_mode"]) + if math is None: + raise ToolError(f"library {lib['name']}: unknown math mode") + cmd = ["xcrun", "-sdk", "macosx", "metal", "-x", "metal", "-c", src] + cmd += [f"-fmetal-math-mode={math}", "-Wno-everything", "-o", air] + if deployment_target: + cmd.append(f"-mmacosx-version-min={deployment_target}") + run(cmd) + cmd = ["xcrun", "-sdk", "macosx", "metallib", air, "-o", out] + run(cmd) + return out + + +def write_pack(entries, path): + """entries: list of (key hex, bytes), sorted by key.""" + header = PACK_MAGIC + struct.pack(" record the workload in report mode +// build build the pack and the archive (metal-tt) +// enforce run the workload sealed: no miss, same +// values, no compiler service; new code fails +// enforce-empty no shipped code: the first kernel fails +// report no shipped code: misses run and are counted +// late setting the mode after a kernel fails +// +// Exit 77 skips a case (no macOS 15, no metal-tt, an unsupported GPU). + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "mlx/backend/common/sealed_pipelines.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/metal.h" +#include "mlx/mlx.h" + +using namespace mlx::core; +namespace mm = mlx::core::metal; + +namespace { + +constexpr int kSkip = 77; + +void require(bool value, const std::string& what) { + if (!value) { + throw std::runtime_error(what); + } +} + +std::string read_text(const std::string& path) { + std::ifstream f(path); + require(f.good(), "cannot read " + path); + std::stringstream s; + s << f.rdbuf(); + return s.str(); +} + +bool contains(const std::string& text, const std::string& part) { + return text.find(part) != std::string::npos; +} + +std::string run_output(const std::string& cmd) { + std::string out; + if (FILE* p = popen(cmd.c_str(), "r")) { + char buf[4096]; + size_t n; + while ((n = fread(buf, 1, sizeof(buf), p)) > 0) { + out.append(buf, n); + } + pclose(p); + } + return out; +} + +std::string macos_major() { + char version[64] = {0}; + size_t size = sizeof(version); + sysctlbyname("kern.osproductversion", version, &size, nullptr, 0); + std::string v(version); + return v.substr(0, v.find('.')) + ".0"; +} + +std::vector workload(StreamOrDevice s) { + auto a = astype(reshape(arange(64 * 64, s), {64, 64}, s), float32, s); + a = divide(a, array(4096.0f), s); + auto m = matmul(a, transpose(a, s), s); + auto g = take(m, array({3, 1, 4, 1, 5}, int32), 0, s); + auto row = reshape(g, {-1}, s); + auto f = compile([](const std::vector& x) { + return std::vector{add(multiply(exp(x[0]), array(2.0f)), x[0])}; + }); + auto h = f({row})[0]; + return {m, g, h}; +} + +array add_one(const array& x, StreamOrDevice s) { + static auto kernel = fast::metal_kernel( + "sealed_test_add_one", + {"inp"}, + {"out"}, + "uint e = thread_position_in_grid.x; out[e] = inp[e] + 1.0f;"); + int n = static_cast(x.size()); + return kernel( + {x}, + {x.shape()}, + {x.dtype()}, + {n, 1, 1}, + {32, 1, 1}, + {}, + {}, + false, + s)[0]; +} + +void check_workload() { + auto gpu_out = workload(Device::gpu); + auto gpu_k = add_one(gpu_out[2], Device::gpu); + gpu_out.push_back(gpu_k); + eval(gpu_out); + auto cpu_out = workload(Device::cpu); + cpu_out.push_back(add(cpu_out[2], array(1.0f), Device::cpu)); + eval(cpu_out); + for (size_t i = 0; i < gpu_out.size(); ++i) { + require( + allclose(gpu_out[i], cpu_out[i], 2e-3, 2e-3).item(), + "GPU and CPU results differ at output " + std::to_string(i)); + } +} + +bool compiler_service_started() { + auto out = run_output( + "launchctl print pid/" + std::to_string(getpid()) + " 2>/dev/null"); + return contains(out, "com.apple.MTLCompilerService"); +} + +int case_record(const std::string& path) { + mm::set_sealed_pipelines(mm::SealedPipelines::report, {}); + mm::start_pipeline_recording(); + check_workload(); + auto json = mm::stop_pipeline_recording(); + require(contains(json, "\"schema\": \"mlx-metal-pipelines/1\""), "schema"); + // Matmul uses function constants; the custom kernel is a generated source. + require(contains(json, "\"constants\": [{\"index\""), "no constants"); + require(contains(json, "sealed_test_add_one"), "no custom kernel"); + auto report = mm::sealed_pipelines_report(); + require(report.archive_misses > 0, "report mode counted no miss"); + std::ofstream(path) << json; + return 0; +} + +int case_build(const std::string& recording, const std::string& dir) { + if (run_output("xcrun -sdk macosx -f metal-tt 2>/dev/null").empty()) { + std::cout << "metal-tt is not available\n"; + return kSkip; + } + auto arch = mm::device(Device::gpu).get_architecture(); + auto cmd = std::string("python3 '") + MLX_SOURCE_DIR + + "/scripts/sealed_pipelines.py' build --metallib '" + MLX_TEST_METALLIB + + "' --arch " + arch + " --macos-version " + macos_major() + " --out '" + + dir + "' '" + recording + "'"; + std::cout << cmd << "\n"; + int rc = std::system(cmd.c_str()); + if (rc != 0) { + // A virtual GPU can report an architecture that metal-tt does not know. + std::cout << "the build failed for " << arch << "\n"; + return kSkip; + } + return 0; +} + +int case_enforce(const std::string& dir) { + auto arch_file = dir + "/manifest.json"; + if (!std::ifstream(arch_file).good()) { + std::cout << "no build output\n"; + return kSkip; + } + auto arch = std::string(); + { + auto manifest = read_text(arch_file); + auto pos = manifest.find(".mtlarchive\""); + require(pos != std::string::npos, "manifest names no archive"); + auto start = manifest.rfind('"', pos - 1) + 1; + arch = manifest.substr(start, pos - start); + } + mm::set_sealed_pipelines( + mm::SealedPipelines::enforce, + {dir + "/" + arch + ".mtlarchive"}, + dir + "/kernels.mlxpack"); + require( + mm::sealed_pipelines() == mm::SealedPipelines::enforce, "mode not set"); + check_workload(); + auto report = mm::sealed_pipelines_report(); + require(report.archive_misses == 0, "a pipeline missed the archive"); + require(report.library_misses == 0, "a library missed the pack"); + require(report.archive_hits > 0, "no archive hit"); + require(!compiler_service_started(), "the compiler service started"); + + // Code that was not recorded fails closed. The inputs use only recorded + // pipelines (arange and the int32 to float32 copy). + auto recorded_input = [](int n) { + return astype(arange(n, Device::gpu), float32, Device::gpu); + }; + auto x = recorded_input(32); + eval(x); + bool refused = false; + try { + eval(erf(x, Device::gpu)); + } catch (const std::exception& e) { + refused = contains(e.what(), "Runtime Metal compilation is refused"); + } + require(refused, "an unrecorded pipeline did not fail closed"); + + refused = false; + try { + auto kernel = fast::metal_kernel( + "sealed_test_new_kernel", + {"inp"}, + {"out"}, + "uint e = thread_position_in_grid.x; out[e] = inp[e] * 3.0f;"); + eval(kernel( + {x}, + {x.shape()}, + {x.dtype()}, + {32, 1, 1}, + {32, 1, 1}, + {}, + {}, + false, + Device::gpu)[0]); + } catch (const std::exception& e) { + refused = contains(e.what(), "generated library") && + contains(e.what(), "Runtime Metal compilation is refused"); + } + require(refused, "a new custom kernel did not fail closed"); + require(!compiler_service_started(), "the compiler service started"); + return 0; +} + +int case_enforce_empty() { + mm::set_sealed_pipelines(mm::SealedPipelines::enforce, {}); + bool refused = false; + try { + eval(add(ones({8}, float32, Device::gpu), array(1.0f), Device::gpu)); + } catch (const std::exception& e) { + refused = contains(e.what(), "Sealed pipelines"); + } + require(refused, "the first kernel did not fail closed"); + auto report = mm::sealed_pipelines_report(); + require(report.archive_misses > 0, "the miss was not counted"); + return 0; +} + +int case_report() { + mm::set_sealed_pipelines(mm::SealedPipelines::report, {}); + check_workload(); + auto report = mm::sealed_pipelines_report(); + require(report.mode == mm::SealedPipelines::report, "mode"); + require(report.archive_misses > 0, "no archive miss counted"); + require(report.library_misses > 0, "no library miss counted"); + require(!report.misses.empty(), "no miss listed"); + mlx_metal_sealed_pipelines_counts counts; + mlx_metal_get_sealed_pipelines_counts(&counts); + require(counts.archive_misses == report.archive_misses, "C counts"); + return 0; +} + +int case_late() { + eval(add(ones({8}, float32, Device::gpu), array(1.0f), Device::gpu)); + char error[256]; + int rc = mlx_metal_set_sealed_pipelines( + MLX_METAL_SEALED_PIPELINES_ENFORCE, nullptr, 0, nullptr, error, 256); + require(rc == -1, "a late call succeeded"); + require(contains(error, "before the first GPU kernel"), error); + require(mm::sealed_pipelines() == mm::SealedPipelines::off, "mode changed"); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + if (!__builtin_available(macOS 15, *)) { + std::cout << "sealed pipelines need macOS 15\n"; + return kSkip; + } + std::string c = argc > 1 ? argv[1] : ""; + try { + if (c == "record" && argc == 3) { + return case_record(argv[2]); + } else if (c == "build" && argc == 4) { + return case_build(argv[2], argv[3]); + } else if (c == "enforce" && argc == 3) { + return case_enforce(argv[2]); + } else if (c == "enforce-empty") { + return case_enforce_empty(); + } else if (c == "report") { + return case_report(); + } else if (c == "late") { + return case_late(); + } + std::cerr << "unknown case\n"; + return 2; + } catch (const std::exception& e) { + std::cerr << "FAILED: " << e.what() << "\n"; + return 1; + } +} From 93527621ff1a2cecfb31b164bfe8d9bf9c31bd50 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 4 Dec 2026 09:51:07 -0800 Subject: [PATCH 2/2] fork.yaml: describe AGENTS.md The fork-diff gate fails on main since 56e12b00 because no section describes AGENTS.md. Same lines as in #73. Co-Authored-By: Claude Opus 5.5 --- fork.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/fork.yaml b/fork.yaml index 6f79dc1c9d..db927d28e1 100644 --- a/fork.yaml +++ b/fork.yaml @@ -827,6 +827,8 @@ def: under PRoot (`.github/scripts/fedora-proot/`); the Fedora x86_64 job and the protected Pages publisher stay on GitHub-hosted runners. `FORKDIFF.md` describes the qualification and watchdog time bounds. + `AGENTS.md` adds the "Working in our MLX forks" section permitting agent-assisted + contributions in Layr-Labs forks (`56e12b00` on `main`). `darkbloom-watchdog.yml` remains unchanged; a rerun keeps these static labels. On a Darkbloom Sandbox that has no Darkbloom cache, `fork-build-cache` sets `CI_ACTIONS_CACHE=off` and every @@ -880,6 +882,7 @@ def: - ".github/scripts/test-ci-resource-sampler.py" - ".github/scripts/test-runner-sizes.py" - "scripts/check_forkdiff.py" + - "AGENTS.md" - "FORKDIFF.md" - "docs/ci-codeql-native.md" - "README.md"