diff --git a/fork.yaml b/fork.yaml index 376a8bc9db..772efef0c0 100644 --- a/fork.yaml +++ b/fork.yaml @@ -162,6 +162,22 @@ def: - "mlx/backend/common/metal_kernel.cpp" - "mlx/backend/metal/custom_kernel.cpp" - "mlx/export.cpp" + - title: "Cached custom-kernel sources" + description: | + A custom Metal kernel function rebuilt its whole generated source (header, + signature, body, template instantiation) on every call and every dispatch hashed + that source to name its library. A one-token decode step of a large model calls + the same few kernels hundreds of times, so this was host time on the step's + critical path. Each kernel function now keeps its generated sources keyed by the + kernel name (template values, input dtypes and address spaces, output dtypes) and + the template parameter names, and hands the source's hash to the primitive, which + names the library from it instead of hashing again. Same sources, same libraries, + same dispatches. + globs: + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "python/tests/test_fast.py" - title: "Cross-thread compile-cache cleanup" description: | Compile caches became thread-local upstream; bindings built before that (the mlx-c / diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index f253f599aa..31065d73a9 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -2,7 +2,10 @@ #include #include +#include +#include #include +#include #include "mlx/backend/common/compiled.h" #include "mlx/backend/metal/metal.h" @@ -18,6 +21,21 @@ namespace { // Inputs with fewer elements are passed in the constant address space constexpr int max_constant_array_size = 8; +// Generated sources of one kernel function, keyed by everything they depend +// on beyond the function's fixed name, header, body and argument names: the +// kernel name (template values, input dtypes and address spaces, output +// dtypes) and the template parameter names. A decode step calls the same few +// kernels hundreds of times; each call otherwise rebuilt the full source and +// each dispatch hashed it. Bounded: a function sees a handful of keys. +struct KernelSourceCache { + struct Entry { + std::string source; + size_t hash; + }; + std::mutex mutex; + std::unordered_map> entries; +}; + Stream resolve_metal_kernel_stream(StreamOrDevice s) { if (metal::is_available()) { // Default an unspecified stream to the GPU rather than the global default @@ -313,9 +331,11 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( } } + auto source_cache = std::make_shared(); return [=, shape_infos = std::move(shape_infos), - attributes = std::move(attributes)]( + attributes = std::move(attributes), + source_cache = std::move(source_cache)]( const std::vector& inputs, const std::vector& output_shapes, const std::vector& output_dtypes, @@ -371,30 +391,55 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( kernel_name += get_type_string(dtype); } - std::string kernel_source = write_signature( - kernel_name, - header, - source, - input_names, - inputs, - output_names, - output_dtypes, - template_args, - attributes, - shape_infos, - atomic_outputs, - mutable_inputs); + std::string cache_key = kernel_name; + for (const auto& [arg_name, arg] : template_args) { + cache_key += '|'; + cache_key += arg_name; + } + std::shared_ptr cached; + { + std::lock_guard lock(source_cache->mutex); + auto it = source_cache->entries.find(cache_key); + if (it != source_cache->entries.end()) { + cached = it->second; + } + } + if (!cached) { + std::string kernel_source = write_signature( + kernel_name, + header, + source, + input_names, + inputs, + output_names, + output_dtypes, + template_args, + attributes, + shape_infos, + atomic_outputs, + mutable_inputs); - if (!template_args.empty()) { - template_def = kernel_name + template_def; - kernel_source += "\ntemplate [[host_name(\""; - kernel_source += kernel_name; - kernel_source += "\")]] [[kernel]] decltype("; - kernel_source += template_def; - kernel_source += ") "; - kernel_source += template_def; - kernel_source += ";\n"; + if (!template_args.empty()) { + template_def = kernel_name + template_def; + kernel_source += "\ntemplate [[host_name(\""; + kernel_source += kernel_name; + kernel_source += "\")]] [[kernel]] decltype("; + kernel_source += template_def; + kernel_source += ") "; + kernel_source += template_def; + kernel_source += ";\n"; + } + auto hash = std::hash{}(kernel_source); + auto entry = std::make_shared( + KernelSourceCache::Entry{std::move(kernel_source), hash}); + std::lock_guard lock(source_cache->mutex); + if (source_cache->entries.size() >= 256) { + source_cache->entries.clear(); + } + cached = source_cache->entries.emplace(cache_key, std::move(entry)) + .first->second; } + std::string kernel_source = cached->source; if (verbose) { std::cout << "Generated source code for `" << name << "`:" << std::endl @@ -420,7 +465,8 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( false, 0, compile_options.serialize(), - mutable_inputs), + mutable_inputs, + cached->hash), inputs); } return array::make_arrays( @@ -438,7 +484,9 @@ CustomKernelFunction metal_kernel_with_mutable_inputs( std::vector{}, false, 0, - compile_options.serialize()), + compile_options.serialize(), + std::vector{}, + cached->hash), std::move(inputs)); }; } diff --git a/mlx/backend/metal/custom_kernel.cpp b/mlx/backend/metal/custom_kernel.cpp index 3ee8f3d029..14ddd1f80b 100644 --- a/mlx/backend/metal/custom_kernel.cpp +++ b/mlx/backend/metal/custom_kernel.cpp @@ -81,8 +81,10 @@ void CustomKernel::eval_gpu( checked_inputs.push_back(check_input(in)); } - std::string lib_name = fmt::format( - "{}_{:x}_{}", name_, std::hash{}(source_), compile_options_); + const size_t source_hash = + source_hash_ != 0 ? source_hash_ : std::hash{}(source_); + std::string lib_name = + fmt::format("{}_{:x}_{}", name_, source_hash, compile_options_); auto lib = d.get_library( lib_name, compile_options_, [this] { return metal::utils() + source_; }); auto kernel = d.get_kernel(name_, lib); diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index bbe7d5b0c9..0967123484 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -520,7 +520,8 @@ class CustomKernel : public Primitive { bool is_precompiled, int shared_memory, CompileOptions::Data compile_options = {}, - std::vector mutable_inputs = {}) + std::vector mutable_inputs = {}, + size_t source_hash = 0) : Primitive(stream), name_(std::move(name)), source_(std::move(source)), @@ -533,6 +534,7 @@ class CustomKernel : public Primitive { is_precompiled_(is_precompiled), shared_memory_(shared_memory), compile_options_(compile_options), + source_hash_(source_hash), mutable_inputs_(std::move(mutable_inputs)) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) @@ -571,6 +573,9 @@ class CustomKernel : public Primitive { bool is_precompiled_; int shared_memory_; CompileOptions::Data compile_options_; + // std::hash of source_ computed once by the kernel function's source cache + // (0: compute it here). Only names the compiled library. + size_t source_hash_; protected: std::vector mutable_inputs_; diff --git a/python/tests/test_fast.py b/python/tests/test_fast.py index dfdcc18242..c1efec1913 100644 --- a/python/tests/test_fast.py +++ b/python/tests/test_fast.py @@ -1281,6 +1281,34 @@ def call_kernel(a: mx.array): out = call_kernel(a).astype(mx.float32) + call_kernel(b) self.assertTrue(mx.allclose(out, mx.full((32,), 8.0))) + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_custom_kernel_reuses_sources_per_specialization(self): + # One kernel function caches its generated sources: repeated and + # interleaved calls with other template values and input dtypes must + # each still run their own specialization. + kernel = mx.fast.metal_kernel( + name="cached_specializations", + input_names=["inp"], + output_names=["out"], + source=""" + uint e = thread_position_in_grid.x; + out[e] = inp[e] * static_cast(V); + """, + ) + for _ in range(3): + for v in (2, 3): + for dtype in (mx.float16, mx.float32, mx.int32): + a = mx.arange(8, dtype=dtype) + (out,) = kernel( + inputs=[a], + template=[("T", dtype), ("V", v)], + grid=(8, 1, 1), + threadgroup=(8, 1, 1), + output_shapes=[(8,)], + output_dtypes=[dtype], + ) + self.assertTrue(mx.array_equal(out, a * v)) + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") def test_custom_metal_kernel_negative_template_int(self): # Negative int template values used to produce a '-' in the generated