Skip to content
Merged
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
2 changes: 1 addition & 1 deletion mlx/backend/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ target_sources(
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/broadcasting.cpp
${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp
${CMAKE_CURRENT_SOURCE_DIR}/common.cpp
${CMAKE_CURRENT_SOURCE_DIR}/custom_kernel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/load.cpp
${CMAKE_CURRENT_SOURCE_DIR}/metal_kernel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/reduce.cpp
${CMAKE_CURRENT_SOURCE_DIR}/slicing.cpp
${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp)
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright © 2024 Apple Inc.

#include <fmt/format.h>
#include <iostream>
#include <sstream>

Expand Down Expand Up @@ -198,26 +199,37 @@ std::string write_template(
return template_def.str();
}

std::string make_template_hash(const std::string& template_def) {
std::string template_hash;
template_hash.reserve(template_def.size());
for (size_t i = 0; i < template_def.size(); ++i) {
auto c = template_def[i];
if (c == '<' || c == '>' || c == '-') {
template_hash += '_';
} else if (
c == ',' && i + 1 < template_def.size() && template_def[i + 1] == ' ') {
template_hash += '_';
++i;
} else {
template_hash += c;
} // namespace

std::string template_arguments_hash(
const std::vector<std::pair<std::string, TemplateArg>>& template_args) {
if (template_args.empty()) {
return "";
}

std::string hash;
hash.reserve(512);

for (const auto& [name, arg] : template_args) {
if (std::holds_alternative<int>(arg)) {
std::string number = std::to_string(std::get<int>(arg));
for (char& c : number) {
if (c == '-') {
c = '_';
}
}
hash += "_";
hash += number;
} else if (std::holds_alternative<bool>(arg)) {
hash += (std::get<bool>(arg)) ? "_t" : "_f";
} else if (std::holds_alternative<Dtype>(arg)) {
hash += "_";
hash += get_type_string(std::get<Dtype>(arg));
}
}
template_hash.pop_back();
return template_hash;
}

} // namespace
return hash;
}

CustomKernelFunction metal_kernel(
const std::string& name,
Expand Down Expand Up @@ -271,6 +283,7 @@ CustomKernelFunction metal_kernel(
}

return [=,
cache = std::make_shared<GeneratedSourceCache>(),
shape_infos = std::move(shape_infos),
attributes = std::move(attributes)](
const std::vector<array>& inputs,
Expand Down Expand Up @@ -298,14 +311,8 @@ CustomKernelFunction metal_kernel(

auto s = resolve_metal_kernel_stream(s_);

std::string kernel_name = "custom_kernel_" + name;
std::string template_def = "";
if (!template_args.empty()) {
template_def = write_template(template_args);
auto template_hash = make_template_hash(template_def);
kernel_name += "_";
kernel_name += template_hash;
}
std::string kernel_name =
"custom_kernel_" + name + template_arguments_hash(template_args);

// The generated source depends on the dtypes of the inputs and outputs
// and on how each input is passed (see `write_signature`). Include them
Expand All @@ -324,29 +331,32 @@ CustomKernelFunction metal_kernel(
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);
const auto& [kernel_source, source_hash] = cache->get(kernel_name, [&] {
std::string kernel_source = write_signature(
kernel_name,
header,
source,
input_names,
inputs,
output_names,
output_dtypes,
template_args,
attributes,
shape_infos,
atomic_outputs);

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()) {
std::string template_def = kernel_name + write_template(template_args);
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";
}
return kernel_source;
});

if (verbose) {
std::cout << "Generated source code for `" << name << "`:" << std::endl
Expand All @@ -361,7 +371,8 @@ CustomKernelFunction metal_kernel(
std::make_shared<CustomKernel>(
s,
std::move(kernel_name),
std::move(kernel_source),
kernel_source,
source_hash,
grid,
threadgroup,
shape_infos,
Expand Down
59 changes: 59 additions & 0 deletions mlx/backend/common/custom_kernel.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2026 Apple Inc.

#pragma once

#include <mutex>
#include <unordered_map>
#include <variant>

#include "mlx/dtype.h"

namespace mlx::core::fast {

using TemplateArg = std::variant<int, bool, Dtype>;
using ScalarArg = std::variant<bool, int, float>;

enum class MathMode {
Safe = 0,
Relaxed = 1,
Fast = 2,
};

struct CompileOptions {
MathMode math_mode = MathMode::Safe;

CompileOptions() = default;
bool operator==(const CompileOptions&) const = default;

// A simple way to make export work, needs more work when adding new options.
using Data = int;
CompileOptions(Data data) : math_mode(static_cast<MathMode>(data)) {}
Data serialize() const {
return static_cast<int>(math_mode);
}
};

std::string template_arguments_hash(
const std::vector<std::pair<std::string, TemplateArg>>& template_args);

class GeneratedSourceCache {
public:
template <typename F>
const auto& get(const std::string& name, F&& make) {
std::lock_guard<std::mutex> lock(mutex_);
auto it = cache_.find(name);
if (it != cache_.end()) {
return it->second;
}
auto source = make();
auto hash = std::hash<std::string>{}(source);
return cache_.emplace(name, std::make_pair(std::move(source), hash))
.first->second;
}

private:
std::mutex mutex_;
std::unordered_map<std::string, std::pair<std::string, size_t>> cache_;
};

} // namespace mlx::core::fast
27 changes: 0 additions & 27 deletions mlx/backend/common/metal_kernel.h

This file was deleted.

57 changes: 20 additions & 37 deletions mlx/backend/cuda/custom_kernel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,6 @@ constexpr const char* default_header = R"(

)";

std::string template_arguments_hash(
const std::vector<std::pair<std::string, TemplateArg>>& template_args) {
if (template_args.empty()) {
return "";
}

std::string hash;
hash.reserve(512);

for (const auto& [name, arg] : template_args) {
if (std::holds_alternative<int>(arg)) {
hash += fmt::format("_{}", std::get<int>(arg));
} else if (std::holds_alternative<bool>(arg)) {
hash += (std::get<bool>(arg)) ? "_t" : "_f";
} else if (std::holds_alternative<Dtype>(arg)) {
hash += "_";
hash += get_type_string(std::get<Dtype>(arg));
}
}

return hash;
}

std::string build_kernel(
const std::string& func_name,
const std::string& header,
Expand Down Expand Up @@ -161,7 +138,9 @@ CustomKernelFunction cuda_kernel(
shape_infos.push_back(shape_info);
}

return [=, shape_infos = std::move(shape_infos)](
return [=,
cache = std::make_shared<GeneratedSourceCache>(),
shape_infos = std::move(shape_infos)](
const std::vector<array>& inputs,
const std::vector<Shape>& output_shapes,
const std::vector<Dtype>& output_dtypes,
Expand Down Expand Up @@ -201,16 +180,19 @@ CustomKernelFunction cuda_kernel(

std::string kernel_name =
"custom_kernel_" + name + template_arguments_hash(template_args);
std::string kernel_source = build_kernel(
kernel_name,
header,
source,
input_names,
inputs,
output_names,
output_dtypes,
template_args,
shape_infos);

const auto& [kernel_source, source_hash] = cache->get(kernel_name, [&] {
return build_kernel(
kernel_name,
header,
source,
input_names,
inputs,
output_names,
output_dtypes,
template_args,
shape_infos);
});

if (verbose) {
std::cout << "Generated source code for `" << kernel_name
Expand All @@ -226,7 +208,8 @@ CustomKernelFunction cuda_kernel(
std::make_shared<CustomKernel>(
s,
std::move(kernel_name),
std::move(kernel_source),
kernel_source,
source_hash,
grid,
threadgroup,
shape_infos,
Expand Down Expand Up @@ -261,6 +244,7 @@ std::vector<array> precompiled_cuda_kernel(
to_stream(s),
name,
compiled_source,
std::hash<std::string>{}(compiled_source),
grid,
threadgroup,
shape_infos,
Expand Down Expand Up @@ -310,8 +294,7 @@ void CustomKernel::eval_gpu(
// Compile the custom kernel
std::string kernel_name =
(is_precompiled_) ? name_ : "mlx::core::cu::" + name_;
std::string module_name =
fmt::format("{}_{:x}", name_, std::hash<std::string>{}(source_));
std::string module_name = fmt::format("{}_{:x}", name_, source_hash_);
cu::JitModule& mod = cu::get_jit_module(
encoder.device(),
module_name,
Expand Down
6 changes: 3 additions & 3 deletions mlx/backend/metal/custom_kernel.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright © 2024 Apple Inc.

#include "mlx/backend/common/metal_kernel.h"
#include "mlx/backend/common/custom_kernel.h"
#include "mlx/backend/gpu/copy.h"
#include "mlx/backend/metal/jit/includes.h"
#include "mlx/backend/metal/utils.h"
Expand Down Expand Up @@ -47,8 +47,8 @@ void CustomKernel::eval_gpu(

auto& d = metal::device(s.device);

std::string lib_name = fmt::format(
"{}_{:x}_{}", name_, std::hash<std::string>{}(source_), compile_options_);
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
Loading
Loading