Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 /
Expand Down
98 changes: 73 additions & 25 deletions mlx/backend/common/metal_kernel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

#include <algorithm>
#include <iostream>
#include <memory>
#include <mutex>
#include <sstream>
#include <unordered_map>

#include "mlx/backend/common/compiled.h"
#include "mlx/backend/metal/metal.h"
Expand All @@ -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<std::string, std::shared_ptr<const Entry>> entries;
};

Stream resolve_metal_kernel_stream(StreamOrDevice s) {
if (metal::is_available()) {
// Default an unspecified stream to the GPU rather than the global default
Expand Down Expand Up @@ -313,9 +331,11 @@ CustomKernelFunction metal_kernel_with_mutable_inputs(
}
}

auto source_cache = std::make_shared<KernelSourceCache>();
return [=,
shape_infos = std::move(shape_infos),
attributes = std::move(attributes)](
attributes = std::move(attributes),
source_cache = std::move(source_cache)](
const std::vector<array>& inputs,
const std::vector<Shape>& output_shapes,
const std::vector<Dtype>& output_dtypes,
Expand Down Expand Up @@ -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<const KernelSourceCache::Entry> cached;
{
std::lock_guard<std::mutex> 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<std::string>{}(kernel_source);
auto entry = std::make_shared<const KernelSourceCache::Entry>(
KernelSourceCache::Entry{std::move(kernel_source), hash});
std::lock_guard<std::mutex> 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
Expand All @@ -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(
Expand All @@ -438,7 +484,9 @@ CustomKernelFunction metal_kernel_with_mutable_inputs(
std::vector<ScalarArg>{},
false,
0,
compile_options.serialize()),
compile_options.serialize(),
std::vector<int>{},
cached->hash),
std::move(inputs));
};
}
Expand Down
6 changes: 4 additions & 2 deletions mlx/backend/metal/custom_kernel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string>{}(source_), compile_options_);
const size_t source_hash =
source_hash_ != 0 ? source_hash_ : std::hash<std::string>{}(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);
Expand Down
7 changes: 6 additions & 1 deletion mlx/fast_primitives.h
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,8 @@ class CustomKernel : public Primitive {
bool is_precompiled,
int shared_memory,
CompileOptions::Data compile_options = {},
std::vector<int> mutable_inputs = {})
std::vector<int> mutable_inputs = {},
size_t source_hash = 0)
: Primitive(stream),
name_(std::move(name)),
source_(std::move(source)),
Expand All @@ -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<array>& inputs, std::vector<array>& outputs)
Expand Down Expand Up @@ -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<int> mutable_inputs_;
Expand Down
28 changes: 28 additions & 0 deletions python/tests/test_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(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
Expand Down
Loading