Repository navigation
Rebase the fork onto v0.32.4; qmv_quad ragged-tile scale/bias read (gemma4-qat#302) #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 28 commits
d084f85
aaa6558
f44c32a
f4eba18
939c71e
30e08d8
8d396ce
158d0ce
87e099a
cffb7f5
5d2510a
4783e7b
26aaef3
e6b7bbe
f54067d
438e420
329b79a
fc4c06a
44a6aa9
c28faeb
bee9e9d
ee0b1bc
33ef381
4c4d61c
1e1f993
cbbbe2f
c134ee2
560cd02
9482135
7b7e8d2
c52689c
7474d2c
713bf19
bb8fa5f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,9 @@ | ||
| // Copyright © 2024 Apple Inc. | ||
|
|
||
| #include <iostream> | ||
| #include <mutex> | ||
| #include <sstream> | ||
| #include <unordered_map> | ||
|
|
||
| #include "mlx/backend/common/compiled.h" | ||
| #include "mlx/backend/metal/metal.h" | ||
|
|
@@ -217,6 +219,59 @@ std::string make_template_hash(const std::string& template_def) { | |
| return template_hash; | ||
| } | ||
|
|
||
| // The name, source and source hash of one kernel variant. | ||
| struct KernelVariant { | ||
| std::string name; | ||
| std::shared_ptr<const std::string> source; | ||
| size_t source_hash; | ||
| }; | ||
|
|
||
| // Shared by all copies of one kernel function. Holds at most | ||
| // `metal_kernel_max_cached_variants` entries and is cleared when full. Callers | ||
| // keep an owning pointer to their entry, so clearing is safe at any time. | ||
| struct VariantCache { | ||
| std::mutex mutex; | ||
| std::unordered_map<std::string, std::shared_ptr<const KernelVariant>> | ||
| variants; | ||
| }; | ||
|
|
||
| // Encodes each call argument that the name and source depend on. Template | ||
| // arguments include their kind and name: `int` 1 and `bool` true give the same | ||
| // name but a different signature. | ||
| std::string variant_key( | ||
| const std::vector<array>& inputs, | ||
| const std::vector<Dtype>& output_dtypes, | ||
| const std::vector<std::pair<std::string, TemplateArg>>& template_args) { | ||
| std::string key; | ||
| auto append_bytes = [&key](auto v) { | ||
| key.append(reinterpret_cast<const char*>(&v), sizeof(v)); | ||
| }; | ||
| for (const auto& arr : inputs) { | ||
| key += static_cast<char>(arr.dtype().val()); | ||
| key += arr.ndim() == 0 ? 's' | ||
| : arr.size() < max_constant_array_size ? 'c' | ||
| : 'd'; | ||
| } | ||
| for (const auto& dtype : output_dtypes) { | ||
| key += static_cast<char>(dtype.val()); | ||
| } | ||
| for (const auto& [name, arg] : template_args) { | ||
| key += static_cast<char>(arg.index()); | ||
| append_bytes(name.size()); | ||
| key += name; | ||
| std::visit( | ||
| [&](auto v) { | ||
| if constexpr (std::is_same_v<decltype(v), Dtype>) { | ||
| key += static_cast<char>(v.val()); | ||
| } else { | ||
| append_bytes(v); | ||
| } | ||
| }, | ||
| arg); | ||
| } | ||
| return key; | ||
| } | ||
|
|
||
| } // namespace | ||
|
|
||
| CustomKernelFunction metal_kernel( | ||
|
|
@@ -270,7 +325,10 @@ CustomKernelFunction metal_kernel( | |
| } | ||
| } | ||
|
|
||
| auto cache = std::make_shared<VariantCache>(); | ||
|
|
||
| return [=, | ||
| cache = std::move(cache), | ||
| shape_infos = std::move(shape_infos), | ||
| attributes = std::move(attributes)]( | ||
| const std::vector<array>& inputs, | ||
|
|
@@ -298,60 +356,86 @@ 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; | ||
| auto key = variant_key(inputs, output_dtypes, template_args); | ||
| std::shared_ptr<const KernelVariant> variant; | ||
| { | ||
| std::lock_guard lock(cache->mutex); | ||
| if (auto it = cache->variants.find(key); it != cache->variants.end()) { | ||
| variant = it->second; | ||
| } | ||
| } | ||
| if (!variant) { | ||
| 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; | ||
| } | ||
|
|
||
| // The generated source depends on the dtypes of the inputs and outputs | ||
| // and on how each input is passed (see `write_signature`). Include them | ||
| // in the kernel name so that a given name always maps to the same source. | ||
| for (const auto& arr : inputs) { | ||
| kernel_name += "_"; | ||
| kernel_name += get_type_string(arr.dtype()); | ||
| if (arr.ndim() == 0) { | ||
| kernel_name += "s"; | ||
| } else if (arr.size() < max_constant_array_size) { | ||
| kernel_name += "c"; | ||
| // The generated source depends on the dtypes of the inputs and outputs | ||
| // and on how each input is passed (see `write_signature`). Include them | ||
| // in the kernel name so that a given name always maps to the same | ||
| // source. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Condense this four-line comment to one or two lines. The dtype and input-location suffix construction immediately below already shows what distinguishes generated sources, so the block repeats the implementation and exceeds the repository's concise-comment standard. AGENTS.md reference: AGENTS.md:L31-L33 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in bb8fa5f. The note is now two lines. The same commit condenses every other source comment in this PR that was longer than two lines. |
||
| for (const auto& arr : inputs) { | ||
| kernel_name += "_"; | ||
| kernel_name += get_type_string(arr.dtype()); | ||
| if (arr.ndim() == 0) { | ||
| kernel_name += "s"; | ||
| } else if (arr.size() < max_constant_array_size) { | ||
| kernel_name += "c"; | ||
| } | ||
| } | ||
| for (const auto& dtype : output_dtypes) { | ||
| kernel_name += "_"; | ||
| kernel_name += get_type_string(dtype); | ||
| } | ||
| } | ||
| for (const auto& dtype : output_dtypes) { | ||
| kernel_name += "_"; | ||
| 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); | ||
| 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()) { | ||
| 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 source_hash = std::hash<std::string>{}(kernel_source); | ||
| variant = std::make_shared<const KernelVariant>(KernelVariant{ | ||
| std::move(kernel_name), | ||
| std::make_shared<const std::string>(std::move(kernel_source)), | ||
| source_hash}); | ||
| std::lock_guard lock(cache->mutex); | ||
| if (auto it = cache->variants.find(key); it != cache->variants.end()) { | ||
| variant = it->second; | ||
| } else { | ||
| if (cache->variants.size() >= metal_kernel_max_cached_variants) { | ||
| cache->variants.clear(); | ||
| } | ||
| cache->variants.emplace(std::move(key), variant); | ||
| } | ||
| } | ||
|
|
||
| if (verbose) { | ||
| std::cout << "Generated source code for `" << name << "`:" << std::endl | ||
| << "```" << std::endl | ||
| << kernel_source << std::endl | ||
| << *variant->source << std::endl | ||
| << "```" << std::endl; | ||
| } | ||
|
|
||
|
|
@@ -360,8 +444,8 @@ CustomKernelFunction metal_kernel( | |
| std::move(output_dtypes), | ||
| std::make_shared<CustomKernel>( | ||
| s, | ||
| std::move(kernel_name), | ||
| std::move(kernel_source), | ||
| variant->name, | ||
| variant->source, | ||
| grid, | ||
| threadgroup, | ||
| shape_infos, | ||
|
|
@@ -370,7 +454,8 @@ CustomKernelFunction metal_kernel( | |
| std::vector<ScalarArg>{}, | ||
| false, | ||
| 0, | ||
| compile_options.serialize()), | ||
| compile_options.serialize(), | ||
| variant->source_hash), | ||
| std::move(inputs)); | ||
| }; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -943,8 +943,71 @@ void QuantizedMatmul::eval_cpu(const std::vector<array>& inputs, array& out) { | |
| encoder.set_input_array(scales); | ||
| encoder.set_output_array(out); | ||
| if (mode_ == QuantizationMode::Affine) { | ||
| if (inputs.size() < 4) { | ||
| throw std::runtime_error( | ||
| "[QuantizedMatmul::eval_cpu] Bias-free affine is Metal-only for " | ||
| "now; pass biases (e.g. derive_biases) on CPU."); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a 1/2-bit bias-free affine matmul is evaluated on CPU, this error directs users to Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 9482135. |
||
| } | ||
| auto biases = ensure_row_contiguous(inputs[3], encoder, stream()); | ||
| encoder.set_input_array(biases); | ||
| if (is_implied_bias(biases)) { | ||
| // Implied bias: expand the factor f into a temporary `scales * T(f)` | ||
| // for the per-group-bias kernels. | ||
| array full_biases(scales.shape(), scales.dtype(), nullptr, {}); | ||
| full_biases.set_data(allocator::malloc(full_biases.nbytes())); | ||
| encoder.add_temporary(full_biases); | ||
| encoder.set_output_array(full_biases); | ||
| encoder.dispatch([out = array::unsafe_weak_copy(out), | ||
| x = array::unsafe_weak_copy(x), | ||
| w = array::unsafe_weak_copy(w), | ||
| scales = array::unsafe_weak_copy(scales), | ||
| factor = array::unsafe_weak_copy(biases), | ||
| full_biases = array::unsafe_weak_copy(full_biases), | ||
| group_size_ = group_size_, | ||
| bits_ = bits_, | ||
| transpose_ = transpose_]() mutable { | ||
| float f; | ||
| switch (factor.dtype()) { | ||
| case float32: | ||
| f = factor.data<float>()[0]; | ||
| break; | ||
| case float16: | ||
| f = static_cast<float>(factor.data<float16_t>()[0]); | ||
| break; | ||
| case bfloat16: | ||
| f = static_cast<float>(factor.data<bfloat16_t>()[0]); | ||
| break; | ||
| default: | ||
| throw std::runtime_error( | ||
| "[QuantizedMatmul::eval_cpu] Implied-bias factor must be a " | ||
| "real floating type."); | ||
| } | ||
| auto fill = [&](auto* dst, const auto* src) { | ||
| using T = std::remove_pointer_t<decltype(dst)>; | ||
| for (size_t i = 0; i < scales.size(); ++i) { | ||
| dst[i] = static_cast<T>(f * static_cast<float>(src[i])); | ||
| } | ||
| }; | ||
| switch (scales.dtype()) { | ||
| case float32: | ||
| fill(full_biases.data<float>(), scales.data<float>()); | ||
| break; | ||
| case float16: | ||
| fill(full_biases.data<float16_t>(), scales.data<float16_t>()); | ||
| break; | ||
| case bfloat16: | ||
| fill(full_biases.data<bfloat16_t>(), scales.data<bfloat16_t>()); | ||
| break; | ||
| default: | ||
| throw std::runtime_error( | ||
| "[QuantizedMatmul::eval_cpu] Only real floating scales are " | ||
| "supported with an implied bias."); | ||
| } | ||
| _qmm_dispatch( | ||
| out, x, w, scales, full_biases, group_size_, bits_, transpose_); | ||
| }); | ||
| return; | ||
| } | ||
| encoder.dispatch([out = array::unsafe_weak_copy(out), | ||
| x = array::unsafe_weak_copy(x), | ||
| w = array::unsafe_weak_copy(w), | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When multiple threads request the same previously unseen variant concurrently, they can all miss the initial locked lookup and independently execute
write_template,write_signature, source allocation, and hashing before the second lock discards every result but one. This defeats the new build-once memoization precisely for concurrent first use, potentially multiplying large source-generation work by the number of racing callers; coordinate construction per key rather than doing it outside the protected section.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 713bf19. A missing variant is now built while
cache->mutexis held, so concurrent first callers build it once and the rest reuse it. The lock covers only source generation and hashing: the Metal library is compiled later, inCustomKernel::eval_gpu, so the extra serialization is small. Python suite: 965 passed, 57 skipped. C++: 311/311 on Metal, 311/311 on Metal JIT, 274/274 on CPU-only.