From ac9051afa3d4ba320f4f81c835927ea82aa6045f Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Fri, 16 Oct 2026 00:51:18 -0700 Subject: [PATCH 1/3] Update MLX to v0.32.4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - mlx submodule v0.32.3 (plus Pico's floor_divide fix) → v0.32.4, back on ml-explore/mlx. v0.32.4 replaces that floor_divide code with a FloorDivide primitive (ml-explore/mlx#4642), and it fixes the Metal fence deadlock (#4689), more missing streams (#4663, #4687), cached failed distributed initializations (#4558) and the cooperative-tensor build on macOS 27 (#4594). - mlx-c stays at PicoMLX/mlx-c d7fbf0a. It compiles against v0.32.4 unchanged. - Regenerated mlx-generated and include-framework with tools/update-mlx.sh. - tools/fix-metal-includes.sh gains v0.32.4's two new always-built kernels, gated_delta_update_vjp and scaled_dot_product_attention_vjp. - The Xcode project's exception lists follow MLX's added, renamed and removed files: the new Metal kernels and headers, floor_divide.cu, the examples/extensions → cmake_extension rename, examples/metal_extension, the new Python test files, and CLAUDE.md gone. - CMake fetches ml-explore/mlx v0.32.4. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 2 +- CMakeLists.txt | 6 +- Source/Cmlx/include-framework/Metal.hpp | 2 +- Source/Cmlx/include-framework/mlx-allocator.h | 56 +- Source/Cmlx/include-framework/mlx-array.h | 52 +- .../mlx-backend-metal-device.h | 11 +- .../mlx-backend-metal-resident.h | 10 +- Source/Cmlx/include-framework/mlx-fft.h | 28 + Source/Cmlx/include-framework/mlx-ops.h | 38 + .../Cmlx/include-framework/mlx-primitives.h | 28 +- .../include-framework/mlx-types-complex.h | 5 + Source/Cmlx/include-framework/mlx-version.h | 2 +- Source/Cmlx/mlx | 2 +- .../Cmlx/mlx-generated/compiled_preamble.cpp | 25 + Source/Cmlx/mlx-generated/conv.cpp | 35 +- .../mlx-generated/cuda/cuda_jit_sources.h | 840 ++-- Source/Cmlx/mlx-generated/fft.cpp | 24 +- Source/Cmlx/mlx-generated/fp_quantized.cpp | 72 +- .../mlx-generated/gated_delta_update_nax.cpp | 402 +- .../gated_delta_update_nax_vjp.cpp | 3816 +++++++++++++++++ Source/Cmlx/mlx-generated/gemv.cpp | 24 +- Source/Cmlx/mlx-generated/gemv_masked.cpp | 2 +- Source/Cmlx/mlx-generated/masked_scatter.cpp | 2 +- Source/Cmlx/mlx-generated/metal/complex.h | 24 +- Source/Cmlx/mlx-generated/metal/conv.metal | 4 +- .../Cmlx/mlx-generated/metal/fp_quantized.h | 72 +- .../mlx-generated/metal/gated_delta_nax_ops.h | 588 +++ .../mlx-generated/metal/gated_delta_update.h | 27 +- .../metal/gated_delta_update.metal | 48 +- .../metal/gated_delta_update_nax.h | 390 +- .../metal/gated_delta_update_nax_vjp.h | 1737 ++++++++ .../metal/gated_delta_update_vjp.h | 184 + .../metal/gated_delta_update_vjp.metal | 35 + Source/Cmlx/mlx-generated/metal/gemv_masked.h | 2 +- .../metal/indexing/masked_scatter.h | 2 +- .../mlx-generated/metal/indexing/scatter.h | 6 +- Source/Cmlx/mlx-generated/metal/quantized.h | 283 +- .../Cmlx/mlx-generated/metal/quantized_nax.h | 190 +- .../metal/reduction/reduce_col.h | 14 +- .../metal/reduction/reduce_init.h | 5 +- .../metal/scaled_dot_product_attention.metal | 33 +- .../scaled_dot_product_attention_vjp.metal | 154 + .../Cmlx/mlx-generated/metal/sdpa_blocked.h | 45 + Source/Cmlx/mlx-generated/metal/sdpa_vector.h | 90 +- .../steel/attn/kernels/steel_attention.h | 24 +- .../steel/attn/kernels/steel_attention_nax.h | 35 + .../metal/steel/conv/kernels/steel_conv.h | 4 +- .../steel/conv/kernels/steel_conv_general.h | 2 +- .../steel/conv/loaders/loader_channel_l.h | 28 +- .../steel/conv/loaders/loader_channel_n.h | 7 +- .../metal/steel/conv/loaders/loader_general.h | 8 +- .../steel/gemm/kernels/steel_gemm_segmented.h | 4 +- .../gemm/kernels/steel_gemm_segmented_nax.h | 4 +- .../steel/gemm/kernels/steel_gemm_thin_nax.h | 223 + Source/Cmlx/mlx-generated/quantized.cpp | 283 +- Source/Cmlx/mlx-generated/quantized_nax.cpp | 190 +- Source/Cmlx/mlx-generated/reduce.cpp | 19 +- Source/Cmlx/mlx-generated/scatter.cpp | 6 +- Source/Cmlx/mlx-generated/steel_attention.cpp | 22 + .../mlx-generated/steel_attention_nax.cpp | 35 + Source/Cmlx/mlx-generated/steel_conv.cpp | 4 +- .../Cmlx/mlx-generated/steel_conv_general.cpp | 10 +- .../mlx-generated/steel_gemm_segmented.cpp | 4 +- .../steel_gemm_segmented_nax.cpp | 4 +- .../mlx-generated/steel_gemm_thin_nax.cpp | 242 ++ Source/Cmlx/mlx-generated/utils.cpp | 24 +- tools/fix-metal-includes.sh | 2 + xcode/MLX.xcodeproj/project.pbxproj | 49 +- 68 files changed, 9544 insertions(+), 1106 deletions(-) create mode 100644 Source/Cmlx/mlx-generated/gated_delta_update_nax_vjp.cpp create mode 100644 Source/Cmlx/mlx-generated/metal/gated_delta_nax_ops.h create mode 100644 Source/Cmlx/mlx-generated/metal/gated_delta_update_nax_vjp.h create mode 100644 Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.h create mode 100644 Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.metal create mode 100644 Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention_vjp.metal create mode 100644 Source/Cmlx/mlx-generated/metal/sdpa_blocked.h create mode 100644 Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_thin_nax.h create mode 100644 Source/Cmlx/mlx-generated/steel_gemm_thin_nax.cpp diff --git a/.gitmodules b/.gitmodules index ce4a5445e..8407808e2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "submodules/mlx"] path = Source/Cmlx/mlx - url = https://github.com/PicoMLX/mlx + url = https://github.com/ml-explore/mlx [submodule "submodules/mlx-c"] path = Source/Cmlx/mlx-c url = https://github.com/PicoMLX/mlx-c diff --git a/CMakeLists.txt b/CMakeLists.txt index 902f3dd68..7c0ed8cfd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,12 +46,10 @@ set(MLX_BUILD_EXAMPLES OFF) set(MLX_BUILD_BENCHMARKS OFF) set(MLX_BUILD_PYTHON_BINDINGS OFF) -# mlx: v0.32.3 plus the stream fix for integer floor_divide, the same commit as -# the Source/Cmlx/mlx submodule FetchContent_Declare( mlx - GIT_REPOSITORY "https://github.com/PicoMLX/mlx.git" - GIT_TAG "712dbd34939e902f7dbb844bf3ddaf3cf4c77f20") + GIT_REPOSITORY "https://github.com/ml-explore/mlx.git" + GIT_TAG "v0.32.4") FetchContent_MakeAvailable(mlx) # mlx-c: 0.7.0 plus ml-explore/mlx-c#137 (gather_qmm for MLX v0.32.3), the same diff --git a/Source/Cmlx/include-framework/Metal.hpp b/Source/Cmlx/include-framework/Metal.hpp index a44ec5666..f350c0ba3 100644 --- a/Source/Cmlx/include-framework/Metal.hpp +++ b/Source/Cmlx/include-framework/Metal.hpp @@ -2,7 +2,7 @@ // // Metal.hpp.in // -// Autogenerated from commit 8f784840de21cacd0c5c237ea860179e47dcec91. +// Autogenerated from commit d1288278beee1a212c03abac2bd364b5bec19f28. // // Copyright 2020-2024 Apple Inc. // diff --git a/Source/Cmlx/include-framework/mlx-allocator.h b/Source/Cmlx/include-framework/mlx-allocator.h index b014aee0d..9823a63fb 100644 --- a/Source/Cmlx/include-framework/mlx-allocator.h +++ b/Source/Cmlx/include-framework/mlx-allocator.h @@ -4,9 +4,20 @@ #pragma once #include +#include +#include #include +namespace mlx::core::allocator { +class Data; +} // namespace mlx::core::allocator + +namespace mlx::core::cu { +class CommandEncoder; +allocator::Data malloc_async(size_t size, CommandEncoder& encoder); +} // namespace mlx::core::cu + namespace mlx::core::allocator { // Simple wrapper around buffer pointers @@ -52,12 +63,47 @@ class MLX_API Allocator { MLX_API Allocator& allocator(); -inline Buffer malloc(size_t size) { - return allocator().malloc(size); -} +using Deleter = std::function; + +// The allocator owns data from malloc +class Data { + public: + Data(Buffer buffer, Deleter d) : buffer_(buffer), deleter_(std::move(d)) {} + Data(const Data& other) = delete; + Data& operator=(const Data& other) = delete; + Data(Data&& other) noexcept + : buffer_(std::exchange(other.buffer_, Buffer(nullptr))), + deleter_(std::exchange(other.deleter_, nullptr)), + owned_(std::exchange(other.owned_, false)) {} + ~Data() { + if (owned_) { + allocator().free(buffer_); + } else if (deleter_) { + deleter_(buffer_); + } + } + + Buffer buffer() const& { + return buffer_; + } + Buffer buffer() const&& = delete; + + bool is_owned() const { + return owned_; + } + + private: + Buffer buffer_; + Deleter deleter_; + bool owned_{false}; + + explicit Data(Buffer buffer) : buffer_(buffer), owned_(true) {} + friend Data malloc(size_t size); + friend Data cu::malloc_async(size_t size, cu::CommandEncoder& encoder); +}; -inline void free(Buffer buffer) { - allocator().free(buffer); +inline Data malloc(size_t size) { + return Data(allocator().malloc(size)); } // Make a Buffer from a raw pointer of the given size without a copy. If a diff --git a/Source/Cmlx/include-framework/mlx-array.h b/Source/Cmlx/include-framework/mlx-array.h index 4af752e76..5fde4ee6e 100644 --- a/Source/Cmlx/include-framework/mlx-array.h +++ b/Source/Cmlx/include-framework/mlx-array.h @@ -20,7 +20,6 @@ namespace mlx::core { // Forward declaration class Primitive; -using Deleter = std::function; using ShapeElem = int32_t; using Shape = SmallVector; using Strides = SmallVector; @@ -70,12 +69,8 @@ class MLX_API array { Dtype dtype, const std::function& deleter); - /* Build an array from a buffer */ - explicit array( - allocator::Buffer data, - Shape shape, - Dtype dtype, - Deleter deleter = allocator::free); + /* Build an array from data */ + explicit array(allocator::Data data, Shape shape, Dtype dtype); /** Assignment to rvalue does not compile. */ array& operator=(const array& other) && = delete; @@ -239,22 +234,7 @@ class MLX_API array { return reinterpret_cast(array_desc_->primitive.get()); } - struct Data { - allocator::Buffer buffer; - Deleter d; - Data(allocator::Buffer buffer, Deleter d = allocator::free) - : buffer(buffer), d(d) {} - // Not copyable - Data(const Data& d) = delete; - Data& operator=(const Data& d) = delete; - Data(Data&& o) : buffer(o.buffer), d(o.d) { - o.buffer = allocator::Buffer(nullptr); - o.d = [](allocator::Buffer) {}; - } - ~Data() { - d(buffer); - } - }; + using Data = allocator::Data; struct Flags { // True iff there are no gaps in the underlying data. Each item @@ -303,7 +283,8 @@ class MLX_API array { /** True indicates the arrays buffer is safe to reuse */ bool is_donatable() const { - return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1); + return array_desc_.use_count() == 1 && + (array_desc_->data.use_count() == 1) && array_desc_->data->is_owned(); } /** The array's siblings. */ @@ -360,11 +341,8 @@ class MLX_API array { return array_desc_->data_size; } - allocator::Buffer& buffer() { - return array_desc_->data->buffer; - } - const allocator::Buffer& buffer() const { - return array_desc_->data->buffer; + allocator::Buffer buffer() const { + return array_desc_->data->buffer(); } size_t buffer_size() const { @@ -448,24 +426,14 @@ class MLX_API array { // Check if the array is a tracer array bool is_tracer() const; - void set_data(allocator::Buffer buffer, Deleter d = allocator::free); + void set_data(allocator::Data data); void set_data( - allocator::Buffer buffer, + allocator::Data data, size_t data_size, Strides strides, Flags flags, - Deleter d) { - set_data(buffer, data_size, std::move(strides), flags, 0, std::move(d)); - } - - void set_data( - allocator::Buffer buffer, - size_t data_size, - Strides strides, - Flags flags, - int64_t offset = 0, - Deleter d = allocator::free); + int64_t offset = 0); void copy_shared_buffer( const array& other, diff --git a/Source/Cmlx/include-framework/mlx-backend-metal-device.h b/Source/Cmlx/include-framework/mlx-backend-metal-device.h index b7c06c1a4..3521bbee0 100644 --- a/Source/Cmlx/include-framework/mlx-backend-metal-device.h +++ b/Source/Cmlx/include-framework/mlx-backend-metal-device.h @@ -63,8 +63,13 @@ class MLX_API CommandEncoder { template >> void set_vector_bytes(const Vec& vec, size_t nelems, int idx) { - get_command_encoder()->setBytes( - vec.data(), nelems * sizeof(typename Vec::value_type), idx); + using T = typename Vec::value_type; + if (nelems > 0) { + get_command_encoder()->setBytes(vec.data(), nelems * sizeof(T), idx); + } else { + T val{}; + get_command_encoder()->setBytes(&val, sizeof(T), idx); + } } template >> void set_vector_bytes(const Vec& vec, int idx) { @@ -90,7 +95,7 @@ class MLX_API CommandEncoder { } void barrier(); - void end_encoding(); + void end_encoding(bool wait_in_flight = false); void wait_event(Event event, uint64_t value); void signal_event(Event event, uint64_t value); bool needs_commit() const; diff --git a/Source/Cmlx/include-framework/mlx-backend-metal-resident.h b/Source/Cmlx/include-framework/mlx-backend-metal-resident.h index a5c6b58f4..a72a1cfe2 100644 --- a/Source/Cmlx/include-framework/mlx-backend-metal-resident.h +++ b/Source/Cmlx/include-framework/mlx-backend-metal-resident.h @@ -1,11 +1,14 @@ #ifdef __cplusplus -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #pragma once #include +#include #include #include +#include +#include #include #include @@ -97,7 +100,7 @@ class ResidencySets { // gave us a set; the new set is the last one. add_to_set_locked returns the // set it used. Neither it nor remove_from_set_locked commits, so a bulk // resize costs one commit per set instead of one per allocation. - bool add_set_locked(NS::Error** error = nullptr); + bool add_set_locked(std::string* error = nullptr); uint32_t choose_set_locked(size_t bytes); uint32_t add_to_set_locked(const MTL::Allocation* buf, Placement& at); void remove_from_set_locked(const MTL::Allocation* buf, Placement& at); @@ -119,6 +122,9 @@ class ResidencySets { // taking the lock. std::atomic num_sets_{0}; mutable std::mutex mtx_; + std::condition_variable refresh_cv_; + bool stop_refresh_{false}; + std::thread refresh_thread_; }; } // namespace mlx::core::metal diff --git a/Source/Cmlx/include-framework/mlx-fft.h b/Source/Cmlx/include-framework/mlx-fft.h index 628113909..5b7cc2fe4 100644 --- a/Source/Cmlx/include-framework/mlx-fft.h +++ b/Source/Cmlx/include-framework/mlx-fft.h @@ -4,6 +4,7 @@ #pragma once #include +#include #include #include @@ -213,6 +214,7 @@ inline array irfft2( StreamOrDevice s = {}) { return irfftn(a, axes, norm, s); } + /** Compute the discrete Fourier Transform sample frequencies. */ MLX_API array fftfreq(int n, double d = 1.0, StreamOrDevice s = {}); @@ -235,5 +237,31 @@ MLX_API array ifftshift(const array& a, StreamOrDevice s = {}); MLX_API array ifftshift(const array& a, const std::vector& axes, StreamOrDevice s = {}); +/** Compute the Short-Time Fourier Transform of the last axis of `x`. */ +MLX_API array stft( + const array& x, + int n_fft = 2048, + const std::optional& hop_length = std::nullopt, + const std::optional& win_length = std::nullopt, + const std::optional& window = std::nullopt, + bool center = true, + const std::string& pad_mode = "reflect", + FFTNorm norm = FFTNorm::Backward, + const std::optional& onesided = std::nullopt, + StreamOrDevice s = {}); + +/** Compute the inverse Short-Time Fourier Transform. */ +MLX_API array istft( + const array& stft_matrix, + const std::optional& n_fft = std::nullopt, + const std::optional& hop_length = std::nullopt, + const std::optional& win_length = std::nullopt, + const std::optional& window = std::nullopt, + bool center = true, + FFTNorm norm = FFTNorm::Backward, + const std::optional& onesided = std::nullopt, + const std::optional& length = std::nullopt, + StreamOrDevice s = {}); + } // namespace mlx::core::fft #endif diff --git a/Source/Cmlx/include-framework/mlx-ops.h b/Source/Cmlx/include-framework/mlx-ops.h index d3ff5a0d5..5e3d6cc1e 100644 --- a/Source/Cmlx/include-framework/mlx-ops.h +++ b/Source/Cmlx/include-framework/mlx-ops.h @@ -787,6 +787,23 @@ min(const array& a, MLX_API array min(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {}); +MLX_API std::tuple +minmax(const array& a, bool keepdims, StreamOrDevice s = {}); +inline std::tuple minmax(const array& a, StreamOrDevice s = {}) { + return minmax(a, false, to_stream(s)); +} + +/** The minimum and maximum of the elements of an array along the given axes. */ +MLX_API std::tuple minmax( + const array& a, + const std::vector& axes, + bool keepdims = false, + StreamOrDevice s = {}); + +/** The minimum and maximum of the elements of an array along the given axis. */ +MLX_API std::tuple +minmax(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {}); + /** Returns the Hanning window of size M. */ MLX_API array hanning(int M, StreamOrDevice s = {}); @@ -882,6 +899,27 @@ MLX_API array topk(const array& a, int k, StreamOrDevice s = {}); /** Returns topk elements of the array along a given axis. */ MLX_API array topk(const array& a, int k, int axis, StreamOrDevice s = {}); +/** + * Returns the sorted unique elements of the flattened array, and optionally + * the index of the first occurrence of each, the inverse indices and the + * counts. The output has the given size, and + * is truncated if ``size`` is smaller than the number of unique values. + * If ``size`` is larger, the result is padded with ``fill_value``, or the + * first of the sorted unique values if no fill value is provided. An empty + * input has none, so it throws unless ``size`` is zero or a fill value is + * given. + * A truncated output loses the counts of the values it drops, and its inverse + * indices are clamped to the last entry. + */ +MLX_API std::vector unique( + const array& a, + int size, + bool return_index = false, + bool return_inverse = false, + bool return_counts = false, + const std::optional& fill_value = std::nullopt, + StreamOrDevice s = {}); + /** Cumulative logsumexp of an array. */ MLX_API array logcumsumexp( const array& a, diff --git a/Source/Cmlx/include-framework/mlx-primitives.h b/Source/Cmlx/include-framework/mlx-primitives.h index 692f821ab..549b40961 100644 --- a/Source/Cmlx/include-framework/mlx-primitives.h +++ b/Source/Cmlx/include-framework/mlx-primitives.h @@ -1080,8 +1080,13 @@ class FFT : public UnaryPrimitive { Stream stream, const std::vector& axes, bool inverse, - bool real) - : UnaryPrimitive(stream), axes_(axes), inverse_(inverse), real_(real) {} + bool real, + bool odd_out = false) + : UnaryPrimitive(stream), + axes_(axes), + inverse_(inverse), + real_(real), + odd_out_(odd_out) {} void eval_cpu(const std::vector& inputs, array& out) override; void eval_gpu(const std::vector& inputs, array& out) override; @@ -1092,13 +1097,16 @@ class FFT : public UnaryPrimitive { bool is_equivalent(const Primitive& other) const override; auto state() const { - return std::make_tuple(axes_, inverse_, real_); + return std::make_tuple(axes_, inverse_, real_, odd_out_); } private: std::vector axes_; bool inverse_; bool real_; + // The output length of an inverse real transform is not recoverable from + // the input shape. + bool odd_out_; }; class Flatten : public UnaryPrimitive { @@ -1140,6 +1148,20 @@ class Floor : public UnaryPrimitive { DEFINE_INPUT_OUTPUT_SHAPE() }; +class FloorDivide : public UnaryPrimitive { + public: + explicit FloorDivide(Stream stream) : UnaryPrimitive(stream) {} + + void eval_cpu(const std::vector& inputs, array& out) override; + void eval_gpu(const std::vector& inputs, array& out) override; + + DEFINE_VMAP() + DEFINE_GRADS() + DEFINE_NAME(FloorDivide) + DEFINE_DEFAULT_IS_EQUIVALENT() + DEFINE_INPUT_OUTPUT_SHAPE() +}; + class Full : public UnaryPrimitive { public: explicit Full(Stream stream) : UnaryPrimitive(stream) {} diff --git a/Source/Cmlx/include-framework/mlx-types-complex.h b/Source/Cmlx/include-framework/mlx-types-complex.h index f9dda2b71..764667911 100644 --- a/Source/Cmlx/include-framework/mlx-types-complex.h +++ b/Source/Cmlx/include-framework/mlx-types-complex.h @@ -46,6 +46,11 @@ struct complex64_t : public std::complex { operator float() const { return real(); }; + + // Explicit, so int casts still go through operator float + explicit operator bool() const { + return real() != 0 || imag() != 0; + }; }; inline bool operator>=(const complex64_t& a, const complex64_t& b) { diff --git a/Source/Cmlx/include-framework/mlx-version.h b/Source/Cmlx/include-framework/mlx-version.h index f672cd22f..f02758282 100644 --- a/Source/Cmlx/include-framework/mlx-version.h +++ b/Source/Cmlx/include-framework/mlx-version.h @@ -7,7 +7,7 @@ #define MLX_VERSION_MAJOR 0 #define MLX_VERSION_MINOR 32 -#define MLX_VERSION_PATCH 3 +#define MLX_VERSION_PATCH 4 #define MLX_VERSION_NUMERIC \ (100000 * MLX_VERSION_MAJOR + 1000 * MLX_VERSION_MINOR + MLX_VERSION_PATCH) diff --git a/Source/Cmlx/mlx b/Source/Cmlx/mlx index 712dbd349..36969c094 160000 --- a/Source/Cmlx/mlx +++ b/Source/Cmlx/mlx @@ -1 +1 @@ -Subproject commit 712dbd34939e902f7dbb844bf3ddaf3cf4c77f20 +Subproject commit 36969c094354086e15d2a327a9c50feb20b9cf11 diff --git a/Source/Cmlx/mlx-generated/compiled_preamble.cpp b/Source/Cmlx/mlx-generated/compiled_preamble.cpp index c23168e74..48006a428 100644 --- a/Source/Cmlx/mlx-generated/compiled_preamble.cpp +++ b/Source/Cmlx/mlx-generated/compiled_preamble.cpp @@ -115,6 +115,9 @@ struct complex64_t : public std::complex { operator float() const { return real(); }; + explicit operator bool() const { + return real() != 0 || imag() != 0; + }; }; inline bool operator>=(const complex64_t& a, const complex64_t& b) { return (a.real() > b.real()) || @@ -305,6 +308,27 @@ Simd divide(Simd a_, Simd b_) { return a / b; } template +Simd floor_divide(Simd a_, Simd b_) { + T a = a_.value; + T b = b_.value; + if constexpr (std::is_integral_v) { + if (b == 0) { + return T(0); + } + T q = a / b; + if constexpr (is_signed_v) { + if (a % b != 0 && (a < 0 != b < 0)) { + q -= 1; + } + } + return q; + } else if constexpr (is_complex) { + return a / b; + } else { + return floor(divide(a_, b_)); + } +} +template Simd remainder(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; @@ -686,6 +710,7 @@ using namespace mlx::core::simd; struct Add { template Simd operator()(Simd x, Simd y) { return operator+(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; struct ArcTan2 { template Simd operator()(Simd x, Simd y) { return atan2(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; struct Divide { template Simd operator()(Simd x, Simd y) { return divide(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; +struct FloorDivide { template Simd operator()(Simd x, Simd y) { return floor_divide(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; struct Multiply { template Simd operator()(Simd x, Simd y) { return operator*(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; struct Subtract { template Simd operator()(Simd x, Simd y) { return operator-(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; struct LogicalAnd { template Simd operator()(Simd x, Simd y) { return operator&&(x, y); } template T operator()(T x, T y) { return (*this)(Simd(x), Simd(y)).value; } }; diff --git a/Source/Cmlx/mlx-generated/conv.cpp b/Source/Cmlx/mlx-generated/conv.cpp index 25c6d5433..3cdec8672 100644 --- a/Source/Cmlx/mlx-generated/conv.cpp +++ b/Source/Cmlx/mlx-generated/conv.cpp @@ -224,8 +224,8 @@ struct Conv2DInputBlockLoaderLargeFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -374,8 +374,8 @@ struct Conv2DInputBlockLoaderSmallFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -561,6 +561,7 @@ struct Conv2DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -582,6 +583,7 @@ struct Conv2DWeightBlockLoader { weight_hw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -596,7 +598,7 @@ struct Conv2DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; @@ -658,9 +660,9 @@ struct Conv3DInputBlockLoaderLargeFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; short kdil_d; short kdil_h; @@ -842,9 +844,9 @@ struct Conv3DInputBlockLoaderSmallFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -1064,6 +1066,7 @@ struct Conv3DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -1085,6 +1088,7 @@ struct Conv3DWeightBlockLoader { weight_dhw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -1099,7 +1103,7 @@ struct Conv3DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; @@ -1206,6 +1210,7 @@ struct Conv2DInputBlockLoaderSmallChannels { // Rows / strided reads within the block STEEL_CONST short n_rows = BROWS / TROWS; + static_assert(n_rows > 0, "BM must be at least tgp_size * vec_size / BK"); // Thread location indices const short thread_idx; @@ -1368,6 +1373,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { int weight_hw; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -1388,6 +1394,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { params(params_), weight_hw(thread_idx % TCOLS), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + BN <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -1395,7 +1402,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { if (bi >= BROWS || bj >= BCOLS) return; - if (read_n >= params->O || weight_hw >= params->wS[1] * params->wS[0]) { + if (read_n >= N || weight_hw >= params->wS[1] * params->wS[0]) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BROWS; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -1424,7 +1431,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { } } else { for (short i = 0; i < BROWS; i += TROWS) { - if (((read_n + i) < params->O)) { + if (((read_n + i) < N)) { STEEL_PRAGMA_UNROLL for (short j = 0; j < n_channels; j++) { dst[i * dst_ld + j] = curr_src[i * src_ld + j]; diff --git a/Source/Cmlx/mlx-generated/cuda/cuda_jit_sources.h b/Source/Cmlx/mlx-generated/cuda/cuda_jit_sources.h index 88af64a0f..0dab87176 100644 --- a/Source/Cmlx/mlx-generated/cuda/cuda_jit_sources.h +++ b/Source/Cmlx/mlx-generated/cuda/cuda_jit_sources.h @@ -755,7 +755,7 @@ constexpr char jit_source_cast_op[] = { 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x5f, 0x74, 0x3c, 0x54, 0x3e, 0x20, 0x78, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x78, 0x2e, 0x72, 0x65, 0x61, 0x6c, 0x28, 0x29, - 0x20, 0x21, 0x3d, 0x20, 0x30, 0x20, 0x26, 0x26, 0x20, 0x78, 0x2e, 0x69, + 0x20, 0x21, 0x3d, 0x20, 0x30, 0x20, 0x7c, 0x7c, 0x20, 0x78, 0x2e, 0x69, 0x6d, 0x61, 0x67, 0x28, 0x29, 0x20, 0x21, 0x3d, 0x20, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, 0x3c, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, @@ -772,7 +772,7 @@ constexpr char jit_source_cast_op[] = { 0x72, 0x28, 0x29, 0x28, 0x62, 0x6f, 0x6f, 0x6c, 0x20, 0x78, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x78, 0x20, 0x3f, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, - 0x5f, 0x74, 0x3c, 0x54, 0x3e, 0x7b, 0x31, 0x2c, 0x20, 0x31, 0x7d, 0x20, + 0x5f, 0x74, 0x3c, 0x54, 0x3e, 0x7b, 0x31, 0x2c, 0x20, 0x30, 0x7d, 0x20, 0x3a, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x5f, 0x74, 0x3c, 0x54, 0x3e, 0x7b, 0x30, 0x2c, 0x20, 0x30, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x2f, 0x2f, 0x20, 0x43, 0x6f, 0x6e, @@ -5494,47 +5494,288 @@ constexpr char jit_source_qmm_sm80[] = { 0x20, 0x20, 0x20, 0x20, 0x74, 0x43, 0x72, 0x43, 0x28, 0x69, 0x29, 0x20, 0x3d, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x28, 0x74, 0x43, 0x72, 0x43, 0x5f, 0x61, 0x63, 0x63, 0x75, 0x28, 0x69, 0x29, 0x29, 0x3b, - 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x28, - 0x72, 0x32, 0x73, 0x5f, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x63, 0x2c, 0x20, - 0x72, 0x32, 0x73, 0x5f, 0x74, 0x43, 0x72, 0x43, 0x2c, 0x20, 0x72, 0x32, - 0x73, 0x5f, 0x74, 0x43, 0x73, 0x43, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x5f, - 0x5f, 0x73, 0x79, 0x6e, 0x63, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, - 0x28, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x69, - 0x66, 0x28, 0x73, 0x32, 0x67, 0x5f, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x63, - 0x2c, 0x20, 0x74, 0x43, 0x70, 0x43, 0x2c, 0x20, 0x73, 0x32, 0x67, 0x5f, - 0x74, 0x43, 0x73, 0x43, 0x2c, 0x20, 0x73, 0x32, 0x67, 0x5f, 0x74, 0x43, - 0x67, 0x43, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x74, 0x65, 0x6d, 0x70, - 0x6c, 0x61, 0x74, 0x65, 0x20, 0x3c, 0x69, 0x6e, 0x74, 0x20, 0x47, 0x72, - 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, 0x3e, 0x0a, 0x69, 0x6e, 0x6c, - 0x69, 0x6e, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x65, 0x78, 0x70, - 0x72, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, - 0x73, 0x63, 0x61, 0x6c, 0x65, 0x73, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, - 0x74, 0x28, 0x69, 0x6e, 0x74, 0x20, 0x6e, 0x2c, 0x20, 0x69, 0x6e, 0x74, - 0x20, 0x6b, 0x2c, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6c, 0x29, 0x20, 0x7b, - 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x67, 0x72, 0x6f, 0x75, - 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x20, 0x3d, 0x20, 0x49, 0x6e, 0x74, - 0x3c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, 0x3e, 0x7b, - 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, - 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x28, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, - 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6e, 0x2c, 0x20, 0x6d, 0x61, 0x6b, - 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x67, 0x72, 0x6f, 0x75, - 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x20, 0x6b, 0x20, 0x2f, 0x20, - 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x2c, - 0x20, 0x6c, 0x29, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, - 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6b, - 0x20, 0x2f, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, - 0x65, 0x2c, 0x20, 0x53, 0x74, 0x72, 0x69, 0x64, 0x65, 0x3c, 0x5f, 0x30, - 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6e, 0x20, 0x2a, 0x20, + 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x54, 0x68, + 0x65, 0x20, 0x6c, 0x61, 0x73, 0x74, 0x20, 0x70, 0x72, 0x65, 0x66, 0x65, + 0x74, 0x63, 0x68, 0x65, 0x73, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x73, 0x74, + 0x69, 0x6c, 0x6c, 0x20, 0x62, 0x65, 0x20, 0x6c, 0x61, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62, 0x75, + 0x66, 0x66, 0x65, 0x72, 0x73, 0x20, 0x43, 0x20, 0x72, 0x65, 0x75, 0x73, + 0x65, 0x73, 0x2e, 0x0a, 0x20, 0x20, 0x63, 0x70, 0x5f, 0x61, 0x73, 0x79, + 0x6e, 0x63, 0x5f, 0x77, 0x61, 0x69, 0x74, 0x3c, 0x30, 0x3e, 0x28, 0x29, + 0x3b, 0x0a, 0x20, 0x20, 0x5f, 0x5f, 0x73, 0x79, 0x6e, 0x63, 0x74, 0x68, + 0x72, 0x65, 0x61, 0x64, 0x73, 0x28, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x63, + 0x6f, 0x70, 0x79, 0x28, 0x72, 0x32, 0x73, 0x5f, 0x63, 0x6f, 0x70, 0x79, + 0x5f, 0x63, 0x2c, 0x20, 0x72, 0x32, 0x73, 0x5f, 0x74, 0x43, 0x72, 0x43, + 0x2c, 0x20, 0x72, 0x32, 0x73, 0x5f, 0x74, 0x43, 0x73, 0x43, 0x29, 0x3b, + 0x0a, 0x20, 0x20, 0x5f, 0x5f, 0x73, 0x79, 0x6e, 0x63, 0x74, 0x68, 0x72, + 0x65, 0x61, 0x64, 0x73, 0x28, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x63, 0x6f, + 0x70, 0x79, 0x5f, 0x69, 0x66, 0x28, 0x73, 0x32, 0x67, 0x5f, 0x63, 0x6f, + 0x70, 0x79, 0x5f, 0x63, 0x2c, 0x20, 0x74, 0x43, 0x70, 0x43, 0x2c, 0x20, + 0x73, 0x32, 0x67, 0x5f, 0x74, 0x43, 0x73, 0x43, 0x2c, 0x20, 0x73, 0x32, + 0x67, 0x5f, 0x74, 0x43, 0x67, 0x43, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, + 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, 0x3c, 0x69, 0x6e, + 0x74, 0x20, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, 0x3e, + 0x0a, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x73, + 0x74, 0x65, 0x78, 0x70, 0x72, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x63, 0x61, 0x6c, 0x65, 0x73, 0x5f, 0x6c, + 0x61, 0x79, 0x6f, 0x75, 0x74, 0x28, 0x69, 0x6e, 0x74, 0x20, 0x6e, 0x2c, + 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6b, 0x2c, 0x20, 0x69, 0x6e, 0x74, 0x20, + 0x6c, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, + 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x20, 0x3d, + 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, + 0x7a, 0x65, 0x3e, 0x7b, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x72, 0x65, 0x74, + 0x75, 0x72, 0x6e, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x6c, 0x61, 0x79, + 0x6f, 0x75, 0x74, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6e, 0x2c, + 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, + 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x20, 0x6b, 0x20, 0x2f, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, - 0x7a, 0x65, 0x29, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x74, 0x65, 0x6d, - 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, 0x3c, 0x69, 0x6e, 0x74, 0x20, 0x47, - 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, 0x2c, 0x0a, 0x20, 0x20, + 0x7a, 0x65, 0x29, 0x2c, 0x20, 0x6c, 0x29, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, + 0x64, 0x65, 0x28, 0x6b, 0x20, 0x2f, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, + 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x20, 0x53, 0x74, 0x72, 0x69, 0x64, + 0x65, 0x3c, 0x5f, 0x30, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, + 0x6e, 0x20, 0x2a, 0x20, 0x6b, 0x20, 0x2f, 0x20, 0x67, 0x72, 0x6f, 0x75, + 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, + 0x0a, 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, 0x3c, 0x69, + 0x6e, 0x74, 0x20, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x45, 0x6c, 0x65, + 0x6d, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, + 0x6d, 0x65, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x2c, 0x20, 0x74, 0x79, + 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x53, 0x63, 0x61, 0x6c, 0x65, + 0x2c, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x43, + 0x74, 0x61, 0x54, 0x69, 0x6c, 0x65, 0x72, 0x3e, 0x0a, 0x5f, 0x5f, 0x67, + 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x5f, 0x5f, 0x0a, 0x5f, 0x5f, 0x6c, 0x61, + 0x75, 0x6e, 0x63, 0x68, 0x5f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x5f, + 0x5f, 0x28, 0x64, 0x65, 0x63, 0x6c, 0x74, 0x79, 0x70, 0x65, 0x28, 0x73, + 0x69, 0x7a, 0x65, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x64, 0x5f, 0x6d, 0x6d, 0x61, 0x28, 0x29, 0x29, 0x29, 0x3a, 0x3a, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x29, 0x0a, 0x76, 0x6f, 0x69, 0x64, 0x20, + 0x71, 0x6d, 0x6d, 0x5f, 0x73, 0x6d, 0x38, 0x30, 0x5f, 0x6b, 0x65, 0x72, + 0x6e, 0x65, 0x6c, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, + 0x73, 0x74, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, + 0x41, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, + 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x2a, 0x20, 0x42, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x53, 0x63, 0x61, + 0x6c, 0x65, 0x2a, 0x20, 0x53, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, + 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, + 0x2a, 0x20, 0x5a, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, + 0x73, 0x74, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x2a, + 0x20, 0x6c, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, + 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x2a, 0x20, 0x72, 0x68, + 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, + 0x43, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6d, + 0x2c, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6e, 0x2c, 0x20, 0x69, 0x6e, 0x74, + 0x20, 0x6b, 0x2c, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6c, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x62, 0x6f, 0x6f, 0x6c, 0x20, 0x62, 0x72, 0x6f, 0x61, + 0x64, 0x63, 0x61, 0x73, 0x74, 0x5f, 0x62, 0x29, 0x20, 0x7b, 0x0a, 0x20, + 0x20, 0x69, 0x6e, 0x74, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x5f, + 0x69, 0x64, 0x78, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x74, 0x68, + 0x72, 0x65, 0x61, 0x64, 0x49, 0x64, 0x78, 0x2e, 0x78, 0x29, 0x3b, 0x0a, + 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6d, 0x5f, 0x63, 0x6f, 0x6f, 0x72, + 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x78, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, + 0x6e, 0x74, 0x20, 0x6e, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, + 0x20, 0x69, 0x6e, 0x74, 0x28, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, + 0x78, 0x2e, 0x79, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, + 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, + 0x74, 0x28, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x7a, + 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x44, 0x65, 0x66, + 0x69, 0x6e, 0x65, 0x20, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x73, 0x20, + 0x28, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x29, 0x2e, 0x0a, 0x20, 0x20, 0x61, + 0x75, 0x74, 0x6f, 0x20, 0x64, 0x41, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6b, 0x2c, 0x20, + 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6d, 0x20, + 0x2a, 0x20, 0x6b, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4d, + 0x2c, 0x64, 0x4b, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, + 0x74, 0x6f, 0x20, 0x64, 0x42, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, + 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6b, 0x2c, 0x20, 0x49, + 0x6e, 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6e, 0x20, 0x2a, + 0x20, 0x6b, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4e, 0x2c, + 0x64, 0x4b, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, + 0x6f, 0x20, 0x64, 0x43, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, + 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6e, 0x2c, 0x20, 0x49, 0x6e, + 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6d, 0x20, 0x2a, 0x20, + 0x6e, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4d, 0x2c, 0x64, + 0x4e, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, + 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, + 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x63, 0x61, 0x6c, 0x65, 0x73, 0x5f, + 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x3c, 0x47, 0x72, 0x6f, 0x75, 0x70, + 0x53, 0x69, 0x7a, 0x65, 0x3e, 0x28, 0x6e, 0x2c, 0x20, 0x6b, 0x2c, 0x20, + 0x6c, 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x48, 0x61, + 0x6e, 0x64, 0x6c, 0x65, 0x20, 0x62, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, + 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x0a, 0x20, 0x20, 0x69, 0x66, 0x20, + 0x28, 0x62, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x5f, 0x62, + 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x67, 0x65, 0x74, 0x3c, + 0x32, 0x3e, 0x28, 0x64, 0x42, 0x29, 0x20, 0x3d, 0x20, 0x30, 0x3b, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x67, 0x65, 0x74, 0x3c, 0x32, 0x3e, 0x28, 0x73, + 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, + 0x75, 0x74, 0x29, 0x29, 0x20, 0x3d, 0x20, 0x30, 0x3b, 0x0a, 0x20, 0x20, + 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x52, 0x65, 0x70, 0x72, + 0x65, 0x73, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, + 0x6c, 0x6c, 0x20, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x2e, 0x0a, + 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x41, 0x5f, + 0x6d, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, + 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, + 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, 0x41, 0x29, 0x2c, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, + 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6d, 0x2c, 0x20, 0x6b, 0x2c, 0x20, + 0x6c, 0x29, 0x2c, 0x20, 0x64, 0x41, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x4d, 0x2c, 0x4b, 0x2c, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, + 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x42, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, + 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, + 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, + 0x70, 0x74, 0x72, 0x3c, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x3e, 0x28, 0x42, + 0x29, 0x2c, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, + 0x65, 0x28, 0x6e, 0x2c, 0x20, 0x6b, 0x2c, 0x20, 0x6c, 0x29, 0x2c, 0x20, + 0x64, 0x42, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x4b, + 0x2c, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, + 0x20, 0x6d, 0x43, 0x5f, 0x6d, 0x6e, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, + 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, + 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, + 0x43, 0x29, 0x2c, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6d, 0x2c, + 0x20, 0x6e, 0x2c, 0x20, 0x6c, 0x29, 0x2c, 0x20, 0x64, 0x43, 0x29, 0x3b, + 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4e, 0x2c, 0x4c, 0x29, 0x0a, + 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x53, + 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, + 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, + 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, 0x53, 0x29, 0x2c, + 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x29, 0x3b, 0x20, + 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, + 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, + 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x2c, 0x4c, 0x29, 0x0a, 0x20, + 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x5a, 0x5f, 0x6e, + 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, + 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, + 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, 0x5a, 0x29, 0x2c, 0x20, 0x53, + 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x29, 0x3b, 0x20, 0x2f, 0x2f, + 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, + 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, + 0x73, 0x69, 0x7a, 0x65, 0x29, 0x2c, 0x4c, 0x29, 0x0a, 0x0a, 0x20, 0x20, + 0x2f, 0x2f, 0x20, 0x46, 0x6f, 0x72, 0x20, 0x67, 0x61, 0x74, 0x68, 0x65, + 0x72, 0x2c, 0x20, 0x75, 0x73, 0x65, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, + 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x75, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, + 0x69, 0x6e, 0x70, 0x75, 0x74, 0x20, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, + 0x73, 0x6c, 0x69, 0x63, 0x69, 0x6e, 0x67, 0x2e, 0x0a, 0x20, 0x20, 0x75, + 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x20, 0x61, 0x5f, 0x62, 0x61, + 0x74, 0x63, 0x68, 0x20, 0x3d, 0x20, 0x6c, 0x68, 0x73, 0x5f, 0x69, 0x6e, + 0x64, 0x69, 0x63, 0x65, 0x73, 0x20, 0x3f, 0x20, 0x6c, 0x68, 0x73, 0x5f, + 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x5b, 0x6c, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x5d, 0x20, 0x3a, 0x20, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, + 0x72, 0x64, 0x3b, 0x0a, 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, + 0x5f, 0x74, 0x20, 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, 0x3d, + 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, + 0x20, 0x3f, 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, + 0x65, 0x73, 0x5b, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x5d, 0x20, + 0x3a, 0x20, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x3b, 0x0a, 0x0a, + 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x47, 0x65, 0x74, 0x20, 0x62, 0x61, 0x74, + 0x63, 0x68, 0x20, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x2e, 0x0a, 0x20, 0x20, + 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x41, 0x20, 0x3d, 0x20, + 0x6d, 0x41, 0x5f, 0x6d, 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x61, + 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x4d, 0x2c, 0x4b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, + 0x6f, 0x72, 0x20, 0x6d, 0x42, 0x20, 0x3d, 0x20, 0x6d, 0x42, 0x5f, 0x6e, + 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, 0x74, + 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x4b, + 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, + 0x43, 0x20, 0x3d, 0x20, 0x6d, 0x43, 0x5f, 0x6d, 0x6e, 0x6c, 0x28, 0x5f, + 0x2c, 0x5f, 0x2c, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x29, 0x3b, + 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4e, 0x29, 0x0a, 0x0a, 0x20, + 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x53, 0x20, 0x3d, + 0x20, 0x6d, 0x53, 0x5f, 0x6e, 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, + 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, + 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, + 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, + 0x73, 0x69, 0x7a, 0x65, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, + 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x5a, 0x20, 0x3d, 0x20, 0x6d, 0x5a, 0x5f, + 0x6e, 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, + 0x74, 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, + 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, + 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, + 0x29, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x47, 0x65, 0x74, + 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x70, 0x72, + 0x69, 0x61, 0x74, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x20, + 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x74, 0x68, 0x72, + 0x65, 0x61, 0x64, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x0a, 0x20, + 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, + 0x6c, 0x65, 0x72, 0x20, 0x3d, 0x20, 0x43, 0x74, 0x61, 0x54, 0x69, 0x6c, + 0x65, 0x72, 0x7b, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, + 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, + 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x28, + 0x6d, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x6e, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x3b, 0x20, 0x2f, 0x2f, + 0x20, 0x28, 0x6d, 0x2c, 0x6e, 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x54, + 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x41, 0x20, 0x3d, 0x20, 0x6c, + 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x41, + 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, + 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, + 0x53, 0x74, 0x65, 0x70, 0x3c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x2c, 0x5f, + 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, + 0x4c, 0x4b, 0x5f, 0x4d, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, + 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, + 0x42, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, + 0x6c, 0x65, 0x28, 0x6d, 0x42, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, + 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, 0x20, 0x58, + 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, + 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x2c, 0x42, 0x4c, + 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, + 0x73, 0x6f, 0x72, 0x20, 0x67, 0x43, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, + 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x43, 0x2c, 0x20, + 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, + 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, + 0x65, 0x70, 0x3c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x3e, + 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, + 0x5f, 0x4d, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x29, 0x0a, 0x0a, 0x20, + 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x53, 0x20, 0x3d, + 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, + 0x6d, 0x53, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, + 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, + 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, 0x20, 0x58, 0x2c, 0x5f, 0x31, + 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, + 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, + 0x20, 0x67, 0x5a, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, + 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x5a, 0x2c, 0x20, 0x63, 0x74, 0x61, + 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, + 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, + 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x29, + 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x2c, + 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x0a, 0x20, 0x20, + 0x2f, 0x2f, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x75, 0x74, 0x65, 0x20, 0x74, + 0x69, 0x6c, 0x65, 0x20, 0x72, 0x65, 0x73, 0x69, 0x64, 0x75, 0x65, 0x73, + 0x20, 0x66, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x65, 0x64, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, + 0x20, 0x6d, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, + 0x20, 0x3d, 0x20, 0x6d, 0x20, 0x2d, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x3c, + 0x30, 0x3e, 0x28, 0x67, 0x41, 0x29, 0x20, 0x2a, 0x20, 0x6d, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x4d, 0x20, 0x2d, + 0x20, 0x42, 0x4c, 0x4b, 0x5f, 0x4d, 0x20, 0x2a, 0x20, 0x6d, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x0a, 0x0a, 0x20, 0x20, 0x71, 0x6d, 0x6d, 0x5f, + 0x73, 0x6d, 0x38, 0x30, 0x5f, 0x6d, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x6f, + 0x70, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x74, 0x61, + 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x67, 0x41, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x67, 0x42, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x53, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x5a, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x43, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x6d, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, + 0x68, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x78, 0x29, 0x3b, 0x0a, + 0x7d, 0x0a, 0x0a, 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, + 0x3c, 0x69, 0x6e, 0x74, 0x20, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, + 0x7a, 0x65, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x45, + 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, + 0x6d, 0x65, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, - 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, - 0x2c, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x51, - 0x75, 0x61, 0x6e, 0x74, 0x2c, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, - 0x6d, 0x65, 0x20, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2c, 0x20, 0x74, 0x79, + 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x43, 0x74, 0x61, 0x54, 0x69, 0x6c, 0x65, 0x72, 0x3e, 0x0a, 0x5f, 0x5f, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x5f, 0x5f, 0x0a, 0x5f, 0x5f, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, @@ -5543,223 +5784,324 @@ constexpr char jit_source_qmm_sm80[] = { 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x64, 0x5f, 0x6d, 0x6d, 0x61, 0x28, 0x29, 0x29, 0x29, 0x3a, 0x3a, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x29, 0x0a, 0x76, 0x6f, 0x69, 0x64, 0x20, 0x71, 0x6d, 0x6d, 0x5f, - 0x73, 0x6d, 0x38, 0x30, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x28, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x45, - 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, 0x41, 0x2c, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x51, 0x75, 0x61, - 0x6e, 0x74, 0x2a, 0x20, 0x42, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, - 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2a, 0x20, - 0x53, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, - 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, 0x5a, 0x2c, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x75, - 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x2a, 0x20, 0x6c, 0x68, 0x73, - 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x2c, 0x0a, 0x20, 0x20, - 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x75, 0x69, 0x6e, 0x74, - 0x33, 0x32, 0x5f, 0x74, 0x2a, 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, - 0x64, 0x69, 0x63, 0x65, 0x73, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x45, - 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, 0x43, 0x2c, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6d, 0x2c, 0x20, 0x69, 0x6e, - 0x74, 0x20, 0x6e, 0x2c, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6b, 0x2c, 0x20, - 0x69, 0x6e, 0x74, 0x20, 0x6c, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, - 0x6f, 0x6f, 0x6c, 0x20, 0x62, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, - 0x74, 0x5f, 0x62, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, - 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x78, 0x20, - 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, - 0x49, 0x64, 0x78, 0x2e, 0x78, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, - 0x74, 0x20, 0x6d, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, - 0x69, 0x6e, 0x74, 0x28, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x78, - 0x2e, 0x78, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6e, - 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, - 0x28, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x79, 0x29, - 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6c, 0x5f, 0x63, 0x6f, - 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x62, 0x6c, - 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x7a, 0x29, 0x3b, 0x0a, 0x0a, - 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x20, - 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x73, 0x20, 0x28, 0x6d, 0x69, 0x78, - 0x65, 0x64, 0x29, 0x2e, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, - 0x64, 0x41, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, - 0x72, 0x69, 0x64, 0x65, 0x28, 0x6b, 0x2c, 0x20, 0x49, 0x6e, 0x74, 0x3c, - 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6d, 0x20, 0x2a, 0x20, 0x6b, 0x29, - 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4d, 0x2c, 0x64, 0x4b, 0x2c, - 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x64, - 0x42, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, - 0x69, 0x64, 0x65, 0x28, 0x6b, 0x2c, 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, - 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6e, 0x20, 0x2a, 0x20, 0x6b, 0x29, 0x3b, - 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4e, 0x2c, 0x64, 0x4b, 0x2c, 0x64, - 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x64, 0x43, - 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, - 0x64, 0x65, 0x28, 0x6e, 0x2c, 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x3e, - 0x7b, 0x7d, 0x2c, 0x20, 0x6d, 0x20, 0x2a, 0x20, 0x6e, 0x29, 0x3b, 0x20, - 0x2f, 0x2f, 0x20, 0x28, 0x64, 0x4d, 0x2c, 0x64, 0x4e, 0x2c, 0x64, 0x4c, - 0x29, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x53, 0x5f, 0x6c, - 0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, - 0x5f, 0x73, 0x63, 0x61, 0x6c, 0x65, 0x73, 0x5f, 0x6c, 0x61, 0x79, 0x6f, - 0x75, 0x74, 0x3c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, - 0x3e, 0x28, 0x6e, 0x2c, 0x20, 0x6b, 0x2c, 0x20, 0x6c, 0x29, 0x3b, 0x0a, - 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, - 0x20, 0x62, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x69, 0x6e, - 0x67, 0x2e, 0x0a, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x62, 0x72, 0x6f, - 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x5f, 0x62, 0x29, 0x20, 0x7b, 0x0a, - 0x20, 0x20, 0x20, 0x20, 0x67, 0x65, 0x74, 0x3c, 0x32, 0x3e, 0x28, 0x64, - 0x42, 0x29, 0x20, 0x3d, 0x20, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, - 0x67, 0x65, 0x74, 0x3c, 0x32, 0x3e, 0x28, 0x73, 0x74, 0x72, 0x69, 0x64, - 0x65, 0x28, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x29, 0x29, - 0x20, 0x3d, 0x20, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, - 0x20, 0x2f, 0x2f, 0x20, 0x52, 0x65, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, - 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x6c, 0x6c, 0x20, 0x74, - 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x2e, 0x0a, 0x20, 0x20, 0x54, 0x65, - 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x41, 0x5f, 0x6d, 0x6b, 0x6c, 0x20, + 0x73, 0x6d, 0x38, 0x30, 0x5f, 0x72, 0x68, 0x73, 0x5f, 0x6b, 0x65, 0x72, + 0x6e, 0x65, 0x6c, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, + 0x73, 0x74, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2a, 0x20, + 0x41, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, + 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x2a, 0x20, 0x42, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x53, 0x63, 0x61, + 0x6c, 0x65, 0x2a, 0x20, 0x53, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, + 0x6f, 0x6e, 0x73, 0x74, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, + 0x2a, 0x20, 0x5a, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, + 0x73, 0x74, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x2a, + 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, + 0x74, 0x2a, 0x20, 0x43, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, + 0x74, 0x20, 0x6d, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x74, + 0x20, 0x6e, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, + 0x6b, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x67, + 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x29, 0x20, + 0x7b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x74, 0x68, 0x72, 0x65, + 0x61, 0x64, 0x5f, 0x69, 0x64, 0x78, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, + 0x28, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x49, 0x64, 0x78, 0x2e, 0x78, + 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6d, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x78, 0x29, 0x3b, 0x0a, + 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6e, 0x5f, 0x63, 0x6f, 0x6f, 0x72, + 0x64, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x49, 0x64, 0x78, 0x2e, 0x79, 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, + 0x61, 0x75, 0x74, 0x6f, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x72, 0x20, 0x3d, 0x20, 0x43, 0x74, 0x61, 0x54, 0x69, 0x6c, 0x65, + 0x72, 0x7b, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x74, + 0x69, 0x6c, 0x65, 0x5f, 0x6d, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, + 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x30, 0x3e, 0x28, 0x63, 0x74, 0x61, 0x5f, + 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, + 0x6e, 0x74, 0x20, 0x79, 0x5f, 0x72, 0x6f, 0x77, 0x20, 0x3d, 0x20, 0x6d, + 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x2a, 0x20, 0x74, 0x69, 0x6c, + 0x65, 0x5f, 0x6d, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6d, + 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, + 0x20, 0x6d, 0x20, 0x2d, 0x20, 0x79, 0x5f, 0x72, 0x6f, 0x77, 0x3b, 0x0a, + 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x74, 0x67, 0x70, 0x5f, 0x62, 0x6d, + 0x20, 0x3d, 0x20, 0x6d, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, + 0x72, 0x64, 0x20, 0x3c, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x5f, 0x6d, 0x20, + 0x3f, 0x20, 0x6d, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, 0x72, + 0x64, 0x20, 0x3a, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x5f, 0x6d, 0x3b, 0x0a, + 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x65, + 0x20, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x73, 0x20, 0x28, 0x6d, 0x69, + 0x78, 0x65, 0x64, 0x29, 0x2e, 0x20, 0x41, 0x6c, 0x6c, 0x20, 0x67, 0x61, + 0x74, 0x68, 0x65, 0x72, 0x65, 0x64, 0x20, 0x72, 0x6f, 0x77, 0x73, 0x20, + 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x6d, 0x61, 0x74, + 0x72, 0x69, 0x78, 0x3b, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20, 0x72, 0x75, + 0x6e, 0x20, 0x6f, 0x66, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x65, 0x71, + 0x75, 0x61, 0x6c, 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, + 0x63, 0x65, 0x73, 0x20, 0x69, 0x6e, 0x73, 0x69, 0x64, 0x65, 0x20, 0x74, + 0x68, 0x65, 0x20, 0x72, 0x6f, 0x77, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x20, + 0x72, 0x65, 0x75, 0x73, 0x65, 0x73, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x65, + 0x78, 0x70, 0x65, 0x72, 0x74, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x2e, 0x0a, + 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x64, 0x41, 0x20, 0x3d, 0x20, + 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, + 0x6b, 0x2c, 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, + 0x20, 0x6d, 0x20, 0x2a, 0x20, 0x6b, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x64, 0x4d, 0x2c, 0x64, 0x4b, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, + 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x64, 0x42, 0x20, 0x3d, 0x20, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6b, + 0x2c, 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, + 0x6e, 0x20, 0x2a, 0x20, 0x6b, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, + 0x64, 0x4e, 0x2c, 0x64, 0x4b, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, + 0x61, 0x75, 0x74, 0x6f, 0x20, 0x64, 0x43, 0x20, 0x3d, 0x20, 0x6d, 0x61, + 0x6b, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x64, 0x65, 0x28, 0x6e, 0x2c, + 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x6d, + 0x20, 0x2a, 0x20, 0x6e, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x64, + 0x4d, 0x2c, 0x64, 0x4e, 0x2c, 0x64, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x61, + 0x75, 0x74, 0x6f, 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, + 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x63, 0x61, 0x6c, + 0x65, 0x73, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x3c, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x53, 0x69, 0x7a, 0x65, 0x3e, 0x28, 0x6e, 0x2c, 0x20, + 0x6b, 0x2c, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x63, 0x6f, 0x75, + 0x6e, 0x74, 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, + 0x6f, 0x72, 0x20, 0x6d, 0x41, 0x5f, 0x6d, 0x6b, 0x6c, 0x20, 0x3d, 0x20, + 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, + 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, + 0x72, 0x28, 0x41, 0x29, 0x2c, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, + 0x6d, 0x2c, 0x20, 0x6b, 0x2c, 0x20, 0x31, 0x29, 0x2c, 0x20, 0x64, 0x41, + 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4b, 0x2c, 0x4c, + 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, + 0x42, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, + 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, + 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x3c, 0x51, 0x75, + 0x61, 0x6e, 0x74, 0x3e, 0x28, 0x42, 0x29, 0x2c, 0x20, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6e, 0x2c, 0x20, 0x6b, + 0x2c, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x29, 0x2c, 0x20, 0x64, 0x42, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x4e, 0x2c, 0x4b, 0x2c, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, + 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x43, 0x5f, 0x6d, 0x6e, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, - 0x70, 0x74, 0x72, 0x28, 0x41, 0x29, 0x2c, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x70, 0x74, 0x72, 0x28, 0x43, 0x29, 0x2c, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, - 0x65, 0x28, 0x6d, 0x2c, 0x20, 0x6b, 0x2c, 0x20, 0x6c, 0x29, 0x2c, 0x20, - 0x64, 0x41, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4b, - 0x2c, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, - 0x20, 0x6d, 0x42, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, - 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, - 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x3c, - 0x51, 0x75, 0x61, 0x6e, 0x74, 0x3e, 0x28, 0x42, 0x29, 0x2c, 0x20, 0x6d, - 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6e, 0x2c, - 0x20, 0x6b, 0x2c, 0x20, 0x6c, 0x29, 0x2c, 0x20, 0x64, 0x42, 0x29, 0x3b, - 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x4b, 0x2c, 0x4c, 0x29, 0x0a, - 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x43, 0x5f, - 0x6d, 0x6e, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, - 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, - 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, 0x43, 0x29, 0x2c, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, - 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x6d, 0x2c, 0x20, 0x6e, 0x2c, 0x20, - 0x6c, 0x29, 0x2c, 0x20, 0x64, 0x43, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, - 0x28, 0x4d, 0x2c, 0x4e, 0x2c, 0x4c, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x54, - 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x53, 0x5f, 0x6e, 0x6b, 0x6c, - 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, - 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, - 0x5f, 0x70, 0x74, 0x72, 0x28, 0x53, 0x29, 0x2c, 0x20, 0x53, 0x5f, 0x6c, - 0x61, 0x79, 0x6f, 0x75, 0x74, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, - 0x4e, 0x2c, 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, - 0x65, 0x2c, 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, - 0x7a, 0x65, 0x29, 0x2c, 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, - 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x5a, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, - 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, - 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, - 0x74, 0x72, 0x28, 0x5a, 0x29, 0x2c, 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, - 0x6f, 0x75, 0x74, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, - 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, - 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, - 0x29, 0x2c, 0x4c, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x46, - 0x6f, 0x72, 0x20, 0x67, 0x61, 0x74, 0x68, 0x65, 0x72, 0x2c, 0x20, 0x75, - 0x73, 0x65, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x20, 0x6c, 0x6f, 0x6f, - 0x6b, 0x75, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x70, 0x75, - 0x74, 0x20, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, 0x73, 0x6c, 0x69, 0x63, - 0x69, 0x6e, 0x67, 0x2e, 0x0a, 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, - 0x32, 0x5f, 0x74, 0x20, 0x61, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, - 0x3d, 0x20, 0x6c, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, - 0x73, 0x20, 0x3f, 0x20, 0x6c, 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, - 0x63, 0x65, 0x73, 0x5b, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x5d, - 0x20, 0x3a, 0x20, 0x6c, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x3b, 0x0a, - 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, 0x74, 0x20, 0x62, - 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, 0x3d, 0x20, 0x72, 0x68, 0x73, - 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x20, 0x3f, 0x20, 0x72, - 0x68, 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x5b, 0x6c, - 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x5d, 0x20, 0x3a, 0x20, 0x6c, 0x5f, - 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, - 0x20, 0x47, 0x65, 0x74, 0x20, 0x62, 0x61, 0x74, 0x63, 0x68, 0x20, 0x73, - 0x6c, 0x69, 0x63, 0x65, 0x2e, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, - 0x6f, 0x72, 0x20, 0x6d, 0x41, 0x20, 0x3d, 0x20, 0x6d, 0x41, 0x5f, 0x6d, - 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x61, 0x5f, 0x62, 0x61, 0x74, - 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4b, - 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, - 0x42, 0x20, 0x3d, 0x20, 0x6d, 0x42, 0x5f, 0x6e, 0x6b, 0x6c, 0x28, 0x5f, - 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x29, 0x3b, - 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x4b, 0x29, 0x0a, 0x20, 0x20, - 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x43, 0x20, 0x3d, 0x20, - 0x6d, 0x43, 0x5f, 0x6d, 0x6e, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x6c, - 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, - 0x28, 0x4d, 0x2c, 0x4e, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, - 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x53, 0x20, 0x3d, 0x20, 0x6d, 0x53, 0x5f, - 0x6e, 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, - 0x74, 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, - 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, - 0x4b, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, - 0x29, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, - 0x6d, 0x5a, 0x20, 0x3d, 0x20, 0x6d, 0x5a, 0x5f, 0x6e, 0x6b, 0x6c, 0x28, - 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x29, + 0x65, 0x28, 0x6d, 0x2c, 0x20, 0x6e, 0x2c, 0x20, 0x31, 0x29, 0x2c, 0x20, + 0x64, 0x43, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, 0x2c, 0x4e, + 0x2c, 0x4c, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, + 0x72, 0x20, 0x6d, 0x53, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, + 0x61, 0x6b, 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, + 0x28, 0x53, 0x29, 0x2c, 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, + 0x74, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, + 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, + 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x2c, + 0x4c, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, + 0x6d, 0x5a, 0x5f, 0x6e, 0x6b, 0x6c, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x28, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x67, 0x6d, 0x65, 0x6d, 0x5f, 0x70, 0x74, 0x72, 0x28, 0x5a, + 0x29, 0x2c, 0x20, 0x53, 0x5f, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, 0x67, 0x72, - 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x29, 0x0a, 0x0a, - 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x47, 0x65, 0x74, 0x20, 0x74, 0x68, 0x65, - 0x20, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x70, 0x72, 0x69, 0x61, 0x74, 0x65, - 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, - 0x74, 0x68, 0x69, 0x73, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x20, - 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, - 0x6f, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x20, - 0x3d, 0x20, 0x43, 0x74, 0x61, 0x54, 0x69, 0x6c, 0x65, 0x72, 0x7b, 0x7d, - 0x3b, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x63, 0x74, 0x61, - 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x6b, - 0x65, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x6d, 0x5f, 0x63, 0x6f, - 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x6e, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, - 0x2c, 0x20, 0x5f, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x6d, 0x2c, - 0x6e, 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, - 0x72, 0x20, 0x67, 0x41, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, - 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x41, 0x2c, 0x20, 0x63, 0x74, - 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, - 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, - 0x3c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, - 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4d, - 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, - 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x42, 0x20, 0x3d, 0x20, + 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x2c, 0x4c, 0x29, + 0x0a, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, + 0x41, 0x20, 0x3d, 0x20, 0x6d, 0x41, 0x5f, 0x6d, 0x6b, 0x6c, 0x28, 0x5f, + 0x2c, 0x5f, 0x2c, 0x30, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4d, + 0x2c, 0x4b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, + 0x20, 0x6d, 0x43, 0x20, 0x3d, 0x20, 0x6d, 0x43, 0x5f, 0x6d, 0x6e, 0x6c, + 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x30, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, + 0x28, 0x4d, 0x2c, 0x4e, 0x29, 0x0a, 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, + 0x33, 0x32, 0x5f, 0x74, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x5f, 0x6e, + 0x65, 0x78, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x68, 0x73, 0x5f, 0x69, 0x6e, + 0x64, 0x69, 0x63, 0x65, 0x73, 0x5b, 0x79, 0x5f, 0x72, 0x6f, 0x77, 0x5d, + 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x20, 0x3d, 0x20, 0x30, 0x3b, + 0x0a, 0x20, 0x20, 0x77, 0x68, 0x69, 0x6c, 0x65, 0x20, 0x28, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x20, 0x3c, 0x20, + 0x74, 0x67, 0x70, 0x5f, 0x62, 0x6d, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x69, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x20, 0x3d, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, + 0x78, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, + 0x33, 0x32, 0x5f, 0x74, 0x20, 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, + 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x5f, 0x6e, 0x65, 0x78, + 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x20, 0x3d, 0x20, 0x74, 0x67, 0x70, + 0x5f, 0x62, 0x6d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, + 0x20, 0x28, 0x69, 0x6e, 0x74, 0x20, 0x72, 0x6f, 0x77, 0x20, 0x3d, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x20, 0x2b, 0x20, 0x31, 0x3b, 0x20, + 0x72, 0x6f, 0x77, 0x20, 0x3c, 0x20, 0x74, 0x67, 0x70, 0x5f, 0x62, 0x6d, + 0x3b, 0x20, 0x2b, 0x2b, 0x72, 0x6f, 0x77, 0x29, 0x20, 0x7b, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x5f, + 0x74, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x20, 0x3d, 0x20, 0x72, 0x68, + 0x73, 0x5f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x65, 0x73, 0x5b, 0x79, 0x5f, + 0x72, 0x6f, 0x77, 0x20, 0x2b, 0x20, 0x72, 0x6f, 0x77, 0x5d, 0x3b, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x69, 0x6e, + 0x64, 0x65, 0x78, 0x20, 0x21, 0x3d, 0x20, 0x62, 0x5f, 0x62, 0x61, 0x74, + 0x63, 0x68, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x78, + 0x74, 0x20, 0x3d, 0x20, 0x72, 0x6f, 0x77, 0x3b, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x5f, 0x6e, + 0x65, 0x78, 0x74, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x3b, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x72, 0x65, + 0x61, 0x6b, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, + 0x6e, 0x74, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x72, 0x6f, 0x77, 0x73, 0x20, + 0x3d, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x78, + 0x74, 0x20, 0x2d, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3b, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, + 0x41, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x20, 0x3d, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, + 0x6e, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x28, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x79, 0x5f, 0x72, 0x6f, + 0x77, 0x20, 0x2b, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x2c, 0x20, + 0x30, 0x29, 0x2c, 0x20, 0x6d, 0x41, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x43, 0x5f, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x20, 0x3d, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x79, 0x5f, 0x72, 0x6f, 0x77, 0x20, 0x2b, + 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x2c, 0x20, 0x30, 0x29, 0x2c, + 0x20, 0x6d, 0x43, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, + 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6d, 0x42, 0x20, 0x3d, 0x20, 0x6d, 0x42, + 0x5f, 0x6e, 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, + 0x61, 0x74, 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, + 0x2c, 0x4b, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, + 0x6f, 0x72, 0x20, 0x6d, 0x53, 0x20, 0x3d, 0x20, 0x6d, 0x53, 0x5f, 0x6e, + 0x6b, 0x6c, 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, 0x74, + 0x63, 0x68, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x28, + 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x4b, + 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, + 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, + 0x20, 0x6d, 0x5a, 0x20, 0x3d, 0x20, 0x6d, 0x5a, 0x5f, 0x6e, 0x6b, 0x6c, + 0x28, 0x5f, 0x2c, 0x5f, 0x2c, 0x62, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, + 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x4e, 0x2c, 0x28, 0x67, 0x72, + 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x2c, 0x4b, 0x2f, 0x67, + 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x29, 0x29, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x72, 0x75, + 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x20, 0x3d, 0x20, 0x5b, 0x26, 0x5d, 0x28, + 0x61, 0x75, 0x74, 0x6f, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x72, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x41, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, - 0x42, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, - 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, + 0x41, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x2c, 0x20, 0x72, 0x75, + 0x6e, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x30, 0x2c, 0x20, 0x6e, + 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x2c, 0x20, + 0x53, 0x74, 0x65, 0x70, 0x3c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x2c, 0x5f, + 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, + 0x4c, 0x4b, 0x5f, 0x4d, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, + 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, + 0x6f, 0x72, 0x20, 0x67, 0x42, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, + 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x42, 0x2c, 0x20, 0x72, + 0x75, 0x6e, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x6d, 0x61, + 0x6b, 0x65, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x30, 0x2c, 0x20, + 0x6e, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, - 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, - 0x67, 0x43, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, - 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x43, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, - 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, - 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, 0x5f, - 0x31, 0x2c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, - 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4d, 0x2c, 0x42, - 0x4c, 0x4b, 0x5f, 0x4e, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x54, 0x65, 0x6e, - 0x73, 0x6f, 0x72, 0x20, 0x67, 0x53, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, - 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x53, 0x2c, 0x20, - 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x63, - 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x53, 0x74, - 0x65, 0x70, 0x3c, 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, - 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, - 0x5f, 0x4e, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, - 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x5a, 0x20, - 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, - 0x28, 0x6d, 0x5a, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, - 0x65, 0x72, 0x2c, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x63, 0x6f, 0x6f, 0x72, - 0x64, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, 0x3c, 0x20, 0x58, 0x2c, 0x5f, - 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, - 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, - 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x43, - 0x6f, 0x6d, 0x70, 0x75, 0x74, 0x65, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x20, - 0x72, 0x65, 0x73, 0x69, 0x64, 0x75, 0x65, 0x73, 0x20, 0x66, 0x6f, 0x72, - 0x20, 0x70, 0x72, 0x65, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x2e, 0x0a, 0x20, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x6d, 0x5f, 0x6d, - 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x20, 0x3d, 0x20, 0x6d, - 0x20, 0x2d, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x30, 0x3e, 0x28, 0x67, - 0x41, 0x29, 0x20, 0x2a, 0x20, 0x6d, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, - 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x4d, 0x20, 0x2d, 0x20, 0x42, 0x4c, 0x4b, - 0x5f, 0x4d, 0x20, 0x2a, 0x20, 0x6d, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, - 0x0a, 0x0a, 0x20, 0x20, 0x71, 0x6d, 0x6d, 0x5f, 0x73, 0x6d, 0x38, 0x30, - 0x5f, 0x6d, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x6f, 0x70, 0x28, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, - 0x65, 0x72, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x41, - 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x42, 0x2c, 0x0a, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x53, 0x2c, 0x0a, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x67, 0x5a, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x67, 0x43, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x6d, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x2c, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, - 0x64, 0x5f, 0x69, 0x64, 0x78, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x7d, - 0x20, 0x2f, 0x2f, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, - 0x65, 0x20, 0x6d, 0x6c, 0x78, 0x3a, 0x3a, 0x63, 0x6f, 0x72, 0x65, 0x3a, - 0x3a, 0x63, 0x75, 0x0a, 0x00, + 0x6b, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, + 0x73, 0x6f, 0x72, 0x20, 0x67, 0x43, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, + 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x28, 0x6d, 0x43, 0x5f, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x2c, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x74, + 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x30, 0x2c, 0x20, 0x6e, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x2c, 0x20, 0x53, 0x74, 0x65, + 0x70, 0x3c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x2c, 0x20, 0x58, 0x3e, 0x7b, + 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, + 0x4d, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, 0x53, + 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x28, 0x6d, 0x53, 0x2c, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x74, 0x69, + 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x28, 0x30, 0x2c, 0x20, 0x6e, 0x5f, 0x63, 0x6f, 0x6f, + 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x2c, 0x20, 0x53, 0x74, 0x65, 0x70, + 0x3c, 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, 0x7d, + 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, 0x4e, + 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x67, + 0x5a, 0x20, 0x3d, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x74, 0x69, + 0x6c, 0x65, 0x28, 0x6d, 0x5a, 0x2c, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x74, + 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x63, + 0x6f, 0x6f, 0x72, 0x64, 0x28, 0x30, 0x2c, 0x20, 0x6e, 0x5f, 0x63, 0x6f, + 0x6f, 0x72, 0x64, 0x2c, 0x20, 0x5f, 0x29, 0x2c, 0x20, 0x53, 0x74, 0x65, + 0x70, 0x3c, 0x20, 0x58, 0x2c, 0x5f, 0x31, 0x2c, 0x5f, 0x31, 0x3e, 0x7b, + 0x7d, 0x29, 0x3b, 0x20, 0x2f, 0x2f, 0x20, 0x28, 0x42, 0x4c, 0x4b, 0x5f, + 0x4e, 0x2c, 0x42, 0x4c, 0x4b, 0x5f, 0x4b, 0x2c, 0x6b, 0x29, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x71, 0x6d, 0x6d, 0x5f, 0x73, 0x6d, + 0x38, 0x30, 0x5f, 0x6d, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x6f, 0x70, 0x28, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, + 0x75, 0x6e, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x41, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x42, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x67, 0x53, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x67, 0x5a, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x67, 0x43, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x72, 0x6f, + 0x77, 0x73, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x78, + 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x65, 0x78, 0x70, 0x72, + 0x20, 0x69, 0x6e, 0x74, 0x20, 0x74, 0x69, 0x6c, 0x65, 0x5f, 0x72, 0x6f, + 0x77, 0x73, 0x20, 0x3d, 0x20, 0x64, 0x65, 0x63, 0x6c, 0x74, 0x79, 0x70, + 0x65, 0x28, 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x30, 0x3e, 0x28, 0x63, 0x74, + 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x29, 0x3a, 0x3a, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, + 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x65, 0x78, 0x70, 0x72, 0x20, 0x28, + 0x74, 0x69, 0x6c, 0x65, 0x5f, 0x72, 0x6f, 0x77, 0x73, 0x20, 0x3e, 0x20, + 0x33, 0x32, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x69, 0x66, 0x20, 0x28, 0x72, 0x75, 0x6e, 0x5f, 0x72, 0x6f, 0x77, 0x73, + 0x20, 0x3c, 0x3d, 0x20, 0x31, 0x36, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, + 0x6d, 0x28, 0x6d, 0x61, 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, + 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x49, 0x6e, 0x74, 0x3c, 0x31, 0x36, 0x3e, 0x7b, 0x7d, 0x2c, + 0x20, 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x31, 0x3e, 0x28, 0x63, 0x74, 0x61, + 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x2c, 0x20, 0x73, 0x69, 0x7a, + 0x65, 0x3c, 0x32, 0x3e, 0x28, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x72, 0x29, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x7d, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x69, 0x66, 0x20, 0x28, + 0x72, 0x75, 0x6e, 0x5f, 0x72, 0x6f, 0x77, 0x73, 0x20, 0x3c, 0x3d, 0x20, + 0x33, 0x32, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x28, 0x6d, 0x61, + 0x6b, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x6e, + 0x74, 0x3c, 0x33, 0x32, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x73, 0x69, 0x7a, + 0x65, 0x3c, 0x31, 0x3e, 0x28, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, + 0x65, 0x72, 0x29, 0x2c, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x32, 0x3e, + 0x28, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x29, + 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x20, 0x65, + 0x6c, 0x73, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x28, 0x63, 0x74, + 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x3b, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x20, + 0x65, 0x6c, 0x73, 0x65, 0x20, 0x69, 0x66, 0x20, 0x63, 0x6f, 0x6e, 0x73, + 0x74, 0x65, 0x78, 0x70, 0x72, 0x20, 0x28, 0x74, 0x69, 0x6c, 0x65, 0x5f, + 0x72, 0x6f, 0x77, 0x73, 0x20, 0x3e, 0x20, 0x31, 0x36, 0x29, 0x20, 0x7b, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x72, + 0x75, 0x6e, 0x5f, 0x72, 0x6f, 0x77, 0x73, 0x20, 0x3c, 0x3d, 0x20, 0x31, + 0x36, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x28, 0x6d, 0x61, 0x6b, + 0x65, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x28, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x6e, 0x74, + 0x3c, 0x31, 0x36, 0x3e, 0x7b, 0x7d, 0x2c, 0x20, 0x73, 0x69, 0x7a, 0x65, + 0x3c, 0x31, 0x3e, 0x28, 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, + 0x72, 0x29, 0x2c, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x3c, 0x32, 0x3e, 0x28, + 0x63, 0x74, 0x61, 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x29, 0x29, + 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x20, 0x65, 0x6c, + 0x73, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x28, 0x63, 0x74, 0x61, + 0x5f, 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x20, 0x65, + 0x6c, 0x73, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x72, 0x75, 0x6e, 0x5f, 0x71, 0x6d, 0x6d, 0x28, 0x63, 0x74, 0x61, 0x5f, + 0x74, 0x69, 0x6c, 0x65, 0x72, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x54, 0x68, 0x65, + 0x20, 0x6e, 0x65, 0x78, 0x74, 0x20, 0x72, 0x75, 0x6e, 0x27, 0x73, 0x20, + 0x6c, 0x6f, 0x61, 0x64, 0x73, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x6e, + 0x6f, 0x74, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x77, 0x72, 0x69, 0x74, 0x65, + 0x20, 0x43, 0x20, 0x77, 0x68, 0x69, 0x6c, 0x65, 0x20, 0x69, 0x74, 0x20, + 0x69, 0x73, 0x20, 0x73, 0x74, 0x69, 0x6c, 0x6c, 0x20, 0x62, 0x65, 0x69, + 0x6e, 0x67, 0x20, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x64, 0x2e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x5f, 0x5f, 0x73, 0x79, 0x6e, 0x63, 0x74, 0x68, 0x72, + 0x65, 0x61, 0x64, 0x73, 0x28, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, + 0x7d, 0x0a, 0x0a, 0x7d, 0x20, 0x2f, 0x2f, 0x20, 0x6e, 0x61, 0x6d, 0x65, + 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x6d, 0x6c, 0x78, 0x3a, 0x3a, 0x63, + 0x6f, 0x72, 0x65, 0x3a, 0x3a, 0x63, 0x75, 0x0a, 0x00, }; constexpr char jit_source_qmm_sm90[] = { diff --git a/Source/Cmlx/mlx-generated/fft.cpp b/Source/Cmlx/mlx-generated/fft.cpp index d60d565b8..36c59094c 100644 --- a/Source/Cmlx/mlx-generated/fft.cpp +++ b/Source/Cmlx/mlx-generated/fft.cpp @@ -664,10 +664,20 @@ constexpr complex_t operator*(complex_t a, complex_t b) { template constexpr complex_t operator/(complex_t a, complex_t b) { - auto denom = b.real * b.real + b.imag * b.imag; - auto x = a.real * b.real + a.imag * b.imag; - auto y = a.imag * b.real - a.real * b.imag; - return {x / denom, y / denom}; + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; } template < @@ -675,11 +685,7 @@ template < typename U, enable_if_t && is_lane_convertible_v, bool> = true> constexpr complex_t operator/(U a, complex_t b) { - auto scalar = static_cast(a); - auto denom = b.real * b.real + b.imag * b.imag; - auto x = scalar * b.real; - auto y = -scalar * b.imag; - return {x / denom, y / denom}; + return complex_t(a) / b; } template diff --git a/Source/Cmlx/mlx-generated/fp_quantized.cpp b/Source/Cmlx/mlx-generated/fp_quantized.cpp index c9fade97e..ad0c884be 100644 --- a/Source/Cmlx/mlx-generated/fp_quantized.cpp +++ b/Source/Cmlx/mlx-generated/fp_quantized.cpp @@ -497,6 +497,7 @@ template < typename T, int group_size, int bits, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> METAL_FUNC void fp_qmv_fast_impl( @@ -530,6 +531,15 @@ METAL_FUNC void fp_qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // Reuse the last valid row for reads beyond the output tile. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; @@ -539,8 +549,12 @@ METAL_FUNC void fp_qmv_fast_impl( load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device auto* sl = scales + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device auto* sl = scales + src * in_vec_size_g; U s = dequantize_scale(sl[0]); result[row] += qdot(wl, x_thread, s); @@ -558,7 +572,7 @@ METAL_FUNC void fp_qmv_fast_impl( for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { if constexpr (has_global_scale) { y[row] = static_cast(result[row] * inv_scale_enc); } else { @@ -959,6 +973,7 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, const bool has_global_scale = false, const int BM = 32, const int BK = 32, @@ -968,7 +983,7 @@ METAL_FUNC void fp_qmm_t_impl( const device uint8_t* scales, const device float* global_scale, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, threadgroup T* Ws, const constant int& K, @@ -993,7 +1008,7 @@ METAL_FUNC void fp_qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; using loader_w_t = QuantizedBlockLoader< @@ -1406,6 +1421,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv_fast( @@ -1447,6 +1463,7 @@ template < T, group_size, bits, + partial_rows, has_global_scale, results_per_simdgroup>( w, @@ -1466,6 +1483,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv( @@ -1674,14 +1692,14 @@ template template < typename T, - const int group_size, - const int bits, - const bool aligned_N, - const bool batched, - const bool has_global_scale = false, - const int BM = 32, - const int BK = 32, - const int BN = 32> + int group_size, + int bits, + bool aligned_N, + bool batched, + bool has_global_scale = false, + int BM = 32, + int BK = 32, + int BN = 32> [[kernel]] void fp_qmm_t( const device uint32_t* w, const device uint8_t* scales, @@ -1725,7 +1743,16 @@ template < s_strides, tid); } - fp_qmm_t_impl( + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( w, scales, global_scale, @@ -1847,7 +1874,7 @@ template w_strides, s_strides, tid); - fp_qmv_fast_impl( + fp_qmv_fast_impl( w, scales, global_scale, @@ -2044,7 +2071,16 @@ template < w_strides, s_strides, tid); - fp_qmm_t_impl( + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( w, scales, global_scale, @@ -2074,7 +2110,7 @@ template < const device uint32_t* w [[buffer(0)]], const device uint8_t* scales [[buffer(1)]], const device T* x [[buffer(2)]], - device T* y [[buffer(3)]], + device float* y [[buffer(3)]], const constant int& K [[buffer(4)]], const constant int& N [[buffer(5)]], const constant int& M [[buffer(6)]], @@ -2099,7 +2135,7 @@ template < scales += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - fp_qmm_t_impl( + fp_qmm_t_impl( (const device uint32_t*)wl, scales, nullptr, diff --git a/Source/Cmlx/mlx-generated/gated_delta_update_nax.cpp b/Source/Cmlx/mlx-generated/gated_delta_update_nax.cpp index 56afceba5..94a90fe8d 100644 --- a/Source/Cmlx/mlx-generated/gated_delta_update_nax.cpp +++ b/Source/Cmlx/mlx-generated/gated_delta_update_nax.cpp @@ -1115,10 +1115,11 @@ METAL_FUNC void tile_matmad_nax( } // namespace mlx /////////////////////////////////////////////////////////////////////////////// -// Contents from "mlx/backend/metal/kernels/gated_delta_update_nax.h" +// Contents from "mlx/backend/metal/kernels/gated_delta_nax_ops.h" /////////////////////////////////////////////////////////////////////////////// -#line 1 "mlx/backend/metal/kernels/gated_delta_update_nax.h" +#line 1 "mlx/backend/metal/kernels/gated_delta_nax_ops.h" +// Copyright © 2026 Apple Inc. #include @@ -1130,15 +1131,146 @@ using namespace metal; using namespace mpp; using namespace mpp::tensor_ops; -// NAX MACROS I can probably do a nice template instead of doing this -// fm = base_fm + (idx >> 2) * 8; // idx>>2 = idx/4 -> 0 for idx 0-3, 1 for -// idx 4-7 fn = base_fn + (idx % 4); // 4 consecutive columns +typedef mlx::steel::NAXTile _M16x16; +typedef mlx::steel::NAXTile _M16x32; + +// NAX MACROS #define AT_NAX(TILE, IDX) TILE.elems()[IDX] +// out = a - b +template +METAL_FUNC T operator-(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) - b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator-(const thread T& a) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = -a.frag_at(0, f); + } + return out; +} + +// out = a + b +template +METAL_FUNC T operator+(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator+(const thread T& a, float addend) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + addend; + } + return out; +} + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +// out = a * b, elementwise. Not a matmul. +template +METAL_FUNC T operator*(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator*(const thread T& a, float s) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * s; + } + return out; +} + +template +METAL_FUNC T fmadd(const thread T& a, const thread T& b, const thread T& c) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f) + c.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC _M16x16 reduce(const thread T& a) { + _M16x16 out; + out.frag_at(0, 0) = a.frag_at(0, 0); + STEEL_PRAGMA_UNROLL + for (short f = 1; f < T::kNumFrags; f++) { + out.frag_at(0, 0) += a.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T scale_rows(const thread T& tile, const thread float* s) { + typename T::frag_type sv; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + sv[i] = s[i >> 2]; + } + + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = tile.frag_at(0, f) * sv; + } + return out; +} + +template +METAL_FUNC void row_sum(thread float* dst, const thread T& tile) { + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + dst[i >> 2] += tile.frag_at(0, f)[i]; + } + } +} + +// Scales row i by DEC2[group(i)] == exp(gamma_{C-1} - gamma_i). +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + #define SUB_NAX(TILE0, TILE1, TILE2) \ { \ STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) - AT_NAX(TILE2, _i); \ } \ } @@ -1146,7 +1278,7 @@ using namespace mpp::tensor_ops; #define ADD_NAX(TILE0, TILE1, TILE2) \ { \ STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) + AT_NAX(TILE2, _i); \ } \ } @@ -1177,6 +1309,15 @@ using namespace mpp::tensor_ops; } \ } +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + #define SCALE_BETA_NAX(TILE0, BETA2) \ { \ STEEL_PRAGMA_UNROLL \ @@ -1240,15 +1381,23 @@ METAL_FUNC static constexpr void mma( mpp::tensor_ops::matmul2d gemm_op; + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + auto ct_a = gemm_op.template get_left_input_cooperative_tensor(); auto ct_b = gemm_op .template get_right_input_cooperative_tensor(); - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); STEEL_PRAGMA_UNROLL for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { @@ -1286,15 +1435,23 @@ METAL_FUNC static constexpr void mma( mpp::tensor_ops::matmul2d gemm_op; + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + auto ct_a = gemm_op.template get_left_input_cooperative_tensor(); auto ct_b = gemm_op .template get_right_input_cooperative_tensor(); - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); STEEL_PRAGMA_UNROLL for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { @@ -1336,6 +1493,15 @@ METAL_FUNC static constexpr void mman( // Create matmul op mpp::tensor_ops::matmul2d gemm_op; + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + // Create matmul operands in registers auto ct_a = gemm_op.template get_left_input_cooperative_tensor(); @@ -1344,10 +1510,9 @@ METAL_FUNC static constexpr void mman( .template get_right_input_cooperative_tensor(); // Create matmul output in register - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); // Load A in to left operand registers STEEL_PRAGMA_UNROLL @@ -1375,9 +1540,9 @@ METAL_FUNC static constexpr void mman( #define MM16x16x16(C, CO, A, TA, AO, B, TB, BO) \ mlx::steel::mma< \ - float, \ - float, \ - float, \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ TA, \ TB, \ mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ @@ -1389,9 +1554,9 @@ METAL_FUNC static constexpr void mman( #define MMA16x16x16(C, CO, A, TA, AO, B, TB, BO) \ mlx::steel::mma< \ - float, \ - float, \ - float, \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ TA, \ TB, \ mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ @@ -1403,9 +1568,9 @@ METAL_FUNC static constexpr void mman( #define MMA16x16x32(C, CO, A, TA, AO, B, TB, BO) \ mlx::steel::mma< \ - float, \ - float, \ - float, \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ TA, \ TB, \ mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ @@ -1419,9 +1584,9 @@ METAL_FUNC static constexpr void mman( #define MM16x32x16(C, CO, A, TA, AO, B, TB, BO) \ mlx::steel::mman< \ - float, \ - float, \ - float, \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ TA, \ TB, \ mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ @@ -1435,9 +1600,9 @@ METAL_FUNC static constexpr void mman( #define MMA16x32x16(C, CO, A, TA, AO, B, TB, BO) \ mlx::steel::mman< \ - float, \ - float, \ - float, \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ TA, \ TB, \ mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ @@ -1449,7 +1614,117 @@ METAL_FUNC static constexpr void mman( B.frag_at(0, (BO) + 1), \ metal::bool_constant{}); -template +// Row sum of an elementwise product, reduced over the fragment's column axis. +// DST[0] is the fm row group, DST[1] the fm + kElemRowsJump group. +#define ROWSUM_NAX(DST, TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i) * AT_NAX(TILE1, _i); \ + } \ + } + +// already generic +#define SCALE_BETA_NAX_O(DST, TILE, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(DST, _i) = AT_NAX(TILE, _i) * (BETA2)[_w >> 2]; \ + } \ + } + +#define ROWSUM1_NAX(DST, TILE0) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i); \ + } \ + } + +#define MUL_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULA_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) += AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULS_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) -= AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define NSCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define SCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (ROW2)[_w >> 2]; \ + } \ + } + +// As SCALE_ROW_P but also negates, in one pass. +#define NSCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * (ROW2)[_w >> 2]; \ + } \ + } + +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/gated_delta_update_nax.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/gated_delta_update_nax.h" +// Copyright © 2026 Apple Inc. + + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +/////////////////////////////////////////////////////////////////////////////// +// Function constants +/////////////////////////////////////////////////////////////////////////////// + +constant bool save_state_cache [[function_constant(200)]]; + +template [[kernel]] void gated_delta_fused_nax( const device InT* q [[buffer(0)]], const device InT* k [[buffer(1)]], @@ -1460,6 +1735,9 @@ template device InT* y [[buffer(6)]], device float* state_out [[buffer(7)]], constant int& T [[buffer(8)]], + device float* state_cache [[buffer(9)]], // [B, Hv, n_ckpt, Dv, Dk] + device float* chunk_mats [[buffer(10)]], // [B, Hv, n_chunks, 3, 16, 16] + device float* chunk_delta [[buffer(11)]], // [B, Hv, n_chunks, C, Dv] uint3 thread_position_in_grid [[thread_position_in_grid]], uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { @@ -1492,6 +1770,13 @@ template auto i_state = state_in + (n * Dv + dv_idx) * Dk; auto o_state = state_out + (n * Dv + dv_idx) * Dk; + const int n_chunks = (T + C - 1) / C; + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + auto c_state = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + + auto o_chunk_mats = chunk_mats + n * n_chunks * 3 * 256; + auto o_chunk_delta = chunk_delta + n * n_chunks * C * Dv + dv_idx; + threadgroup float gamma_all[C * 4]; threadgroup float* gamma = gamma_all + sg_id * C; @@ -1524,6 +1809,10 @@ template } mlx::steel::NAXTile TMP_tile; + // Which chunk process_chunk is on, so it knows whether this is a segment + // boundary. + int chunk_idx = 0; + auto process_chunk = [&](const short valid_rows, auto bounded_tag) __attribute__((always_inline)) { constexpr bool B = decltype(bounded_tag)::value; @@ -1536,19 +1825,23 @@ template } }; + // Checkpoint the state entering this chunk before anything mutates it, on + // segment boundaries only. + if (save_state_cache && (chunk_idx % Ckpt) == 0) { + S_tile.store(c_state, Dk); + c_state += Dv * Dk; + } + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) ? metal::fast::log( metal::max( - static_cast( - g_[thread_index_in_simdgroup * Hv + hv_idx]), - 1e-6f)) + float(g_[thread_index_in_simdgroup * Hv + hv_idx]), 1e-6)) : 0.0f; auto gamma_val = simd_prefix_inclusive_sum(g_val); if (thread_index_in_simdgroup < C) { gamma[thread_index_in_simdgroup] = static_cast(gamma_val); } - simdgroup_barrier(mem_flags::mem_threadgroup); beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; @@ -1560,6 +1853,12 @@ template MMA16x16x32(KKt_tile, 0, K_tile, false, 0, K_tile, true, 0); } + // KKt_raw is identical for every Dv tile of this chunk; only the first + // tile needs to write it out for the vjp kernel to reuse. + if (save_state_cache && dv_idx == 0) { + KKt_tile.store(o_chunk_mats, 16); + } + KKtK_tile = KKt_tile; SCALE_TRIEQ_NAX1(KKtK_tile, beta_fm); @@ -1570,6 +1869,12 @@ template SUB_NAX(Tinv_tile, I_tile, TMP_tile); } + // Same as KKt_raw: cache the pre-decay inverse before it is overwritten + // below by the gamma-scaled (TUinv) version. + if (save_state_cache && dv_idx == 0) { + Tinv_tile.store(o_chunk_mats + 256, 16); + } + STEEL_PRAGMA_UNROLL for (short nn = 0; nn < Dk / 16; nn += 2) { load_seq(K_tile, k_ + nn * 16, Dk * Hk); @@ -1591,20 +1896,29 @@ template SUB_NAX(delta_tile, U_tile, WS_tile) - tmp_tile.clear(); QKt_tile.clear(); + tmp_tile.clear(); for (int kk = 0; kk < Dk; kk += 32) { load_seq(Q_tile, q_ + kk, Hk * Dk); load_seq(K_tile, k_ + kk, Hk * Dk); - MMA16x16x32(QKt_tile, 0, Q_tile, false, 0, K_tile, true, 0); - SCALE_ROW_NAX(Q_tile, gamma); MMA16x16x32(tmp_tile, 0, Q_tile, false, 0, S_tile, true, kk / 16); } - SCALE_TRI_NAX(QKt_tile, gamma) + if (save_state_cache) { + if (dv_idx == 0) { + QKt_tile.store(o_chunk_mats + 512, 16); + } + // Every Dv tile stores its own slice. + delta_tile.store(o_chunk_delta, Dv); + o_chunk_mats += 3 * 256; + o_chunk_delta += C * Dv; + } + // Output path runs unconditionally: the forward serves both inference and + // the training save, so y and state_out are always needed. + SCALE_TRI_NAX(QKt_tile, gamma) out_tile = tmp_tile; MMA16x16x16(out_tile, 0, QKt_tile, false, 0, delta_tile, false, 0); @@ -1626,6 +1940,8 @@ template SCALE2_NAX(K_tile, gamma); MMA16x32x16(S_tile, kk / 16, delta_tile, true, 0, K_tile, false, 0); } + + chunk_idx++; }; int t = 0; diff --git a/Source/Cmlx/mlx-generated/gated_delta_update_nax_vjp.cpp b/Source/Cmlx/mlx-generated/gated_delta_update_nax_vjp.cpp new file mode 100644 index 000000000..bf46ed675 --- /dev/null +++ b/Source/Cmlx/mlx-generated/gated_delta_update_nax_vjp.cpp @@ -0,0 +1,3816 @@ +namespace mlx::core::metal { + +const char* gated_delta_update_nax_vjp() { + return R"preamble( +// Copyright © 2025 Apple Inc. + +// Auto generated source for mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/steel/defines.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/steel/defines.h" +// Copyright © 2024 Apple Inc. + + +#define STEEL_CONST static constant constexpr const +#define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)") +#define STEEL_PRAGMA_NO_UNROLL _Pragma("clang loop unroll(disable)") + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/steel/utils/type_traits.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/steel/utils/type_traits.h" +// Copyright © 2024 Apple Inc. + + +#include + +#pragma METAL internals : enable + +namespace metal { + +template +struct is_empty : metal::bool_constant<__is_empty(T)> {}; + +#ifdef __cpp_variable_templates +template +constexpr constant bool is_empty_v = is_empty::value; +#endif + +template +struct make_void { + typedef void type; +}; + +template +using void_t = typename make_void::type; + +template +struct is_static : metal::bool_constant>::value> {}; + +template +struct pointer_element {}; + +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; + +template +using pointer_element_t = typename pointer_element>::type; + +} // namespace metal + +#pragma METAL internals : disable + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/steel/utils/integral_constant.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/steel/utils/integral_constant.h" +// Copyright © 2024 Apple Inc. + + +#include + +#pragma METAL internals : enable + +namespace mlx { +namespace steel { + +/////////////////////////////////////////////////////////////////////////////// +// Integral constant with casting +/////////////////////////////////////////////////////////////////////////////// + +template +struct integral_constant { + static constexpr constant T value = v; + using value_type = T; + using type = integral_constant; + + METAL_FUNC constexpr operator value_type() const thread noexcept { + return value; + } +}; + +template +using bool_constant = integral_constant; +using true_type = bool_constant; +using false_type = bool_constant; + +template +struct is_integral : bool_constant::value> {}; + +template +struct is_integral> + : bool_constant::value> {}; + +template +constexpr constant bool is_integral_v = is_integral::value; + +template +using Int = integral_constant; + +/////////////////////////////////////////////////////////////////////////////// +// Binary Operators on Integral constants +/////////////////////////////////////////////////////////////////////////////// + +#define integral_const_binop(__op__, __operator__) \ + template \ + METAL_FUNC constexpr auto __operator__( \ + integral_constant, integral_constant) { \ + constexpr auto res = tv __op__ uv; \ + using res_t = metal::remove_addrspace_t; \ + return integral_constant{}; \ + } + +integral_const_binop(+, operator+); +integral_const_binop(-, operator-); +integral_const_binop(*, operator*); +integral_const_binop(/, operator/); + +integral_const_binop(==, operator==); +integral_const_binop(!=, operator!=); +integral_const_binop(<, operator<); +integral_const_binop(>, operator>); +integral_const_binop(<=, operator<=); +integral_const_binop(>=, operator>=); + +integral_const_binop(&&, operator&&); +integral_const_binop(||, operator||); + +template >> +METAL_FUNC constexpr auto operator||(true_type, T) { + return true_type{}; +} +template >> +METAL_FUNC constexpr auto operator||(T, true_type) { + return true_type{}; +} + +template >> +METAL_FUNC constexpr auto operator&&(false_type, T) { + return false_type{}; +} + +template >> +METAL_FUNC constexpr auto operator&&(T, false_type) { + return false_type{}; +} + +// Dispatch utilities +template +void dispatch_bool(bool v, F f) { + if (v) { + f(true_type{}); + } else { + f(false_type{}); + } +} + +template +constexpr void const_for_loop(F f) { + if constexpr (start < stop) { + constexpr auto idx = Int{}; + f(idx); + const_for_loop(f); + } +} + +#undef integral_const_binop + +/////////////////////////////////////////////////////////////////////////////// +// Reduction operators +/////////////////////////////////////////////////////////////////////////////// + +template +METAL_FUNC constexpr T sum(T x) { + return x; +} + +template +METAL_FUNC constexpr auto sum(T x, Us... us) { + return x + sum(us...); +} + +} // namespace steel +} // namespace mlx + +#pragma METAL internals : disable + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/steel/gemm/nax.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/steel/gemm/nax.h" +// Copyright © 2025 Apple Inc. + + +#include +#include +#include + + +#include + +using namespace metal; + +/////////////////////////////////////////////////////////////////////////////// +// MMA helper +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +/////////////////////////////////////////////////////////////////////////////// +// NAX Steel with new tiles +/////////////////////////////////////////////////////////////////////////////// + +struct BaseNAXFrag { + STEEL_CONST short kFragRows = 16; + STEEL_CONST short kFragCols = 16; + + STEEL_CONST short kElemsPerFrag = (kFragRows * kFragCols) / 32; + + STEEL_CONST short kElemRows = 2; + STEEL_CONST short kElemCols = 4; + + STEEL_CONST short kElemRowsJump = 8; + + static_assert( + kElemRows * kElemCols == kElemsPerFrag, + "MMAFrag shape is not consistent with MMAFrag size"); + + template + using dtype_frag_t = typename metal::vec; + + METAL_FUNC static short2 get_coord() { + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4; + return short2{fn, fm}; + } + + METAL_FUNC static short2 get_coord(short idx) { + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)) + (idx >> 2) * 8; + const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4 + idx % 4; + return short2{fn, fm}; + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = static_cast(src[r * str_x + c + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } + } + } + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename LimX, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load_rows( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + LimX lim_x, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if (r < lx) { + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = static_cast(src[r * str_x + (c + j)]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } + } + + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = T(0); + } + } + } + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load_safe( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + auto ly = lim_y - sc.x; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if ((r < lx) && ((c + j) < ly)) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } else { + dst[i * kElemCols + j] = T(0); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + c + j] = static_cast(src[i * kElemCols + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename LimX, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_rows( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + LimX lim_x, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if (r < lx) { + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + c + j] = static_cast(src[i * kElemCols + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_safe( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + auto ly = lim_y - sc.x; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if (r < lx && (c + j) < ly) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename StartX, + typename StopX, + typename StartY, + typename StopY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_slice( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + StartX start_x, + StopX stop_x, + StartY start_y, + StopY stop_y, + OffX off_x = Int<0>{}, + OffY off_y = Int<0>{}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + + const_for_loop<0, kElemRows, 1>([&](auto idx_row) { + const auto r = off_x + idx_row * Int{}; + if (r >= stop_x - sc.y || r < start_x - sc.y) { + return; + } + + const_for_loop<0, kElemCols, 1>([&](auto idx_col) { + const auto c = off_y + idx_col; + if (c >= stop_y - sc.x || c < start_y - sc.x) { + return; + } + + const auto src_idx = idx_row * Int{} + idx_col; + dst[(r + sc.y) * str_x + (c + sc.x) * str_y] = + static_cast(src[src_idx]); + }); + }); + } + + template + METAL_FUNC static constexpr void row_reduce( + thread const dtype_frag_t& inp_vals, + thread T* reduced_vals) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + T thr_reduce = Op::apply( + Op::apply(inp_vals[i * kElemCols + 0], inp_vals[i * kElemCols + 1]), + Op::apply(inp_vals[i * kElemCols + 2], inp_vals[i * kElemCols + 3])); + + T qgr_reduce = simd_shuffle_xor(thr_reduce, ushort(1)); + qgr_reduce = Op::apply(thr_reduce, qgr_reduce); + + T sgr_reduce = simd_shuffle_xor(qgr_reduce, ushort(8)); + sgr_reduce = Op::apply(qgr_reduce, sgr_reduce); + + reduced_vals[i] = Op::apply(reduced_vals[i], sgr_reduce); + } + } + + template + METAL_FUNC static constexpr void row_bin_op( + thread dtype_frag_t& inp_vals, + thread T* row_vals) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + inp_vals[i * kElemCols + j] = + Op::apply(inp_vals[i * kElemCols + j], row_vals[i]); + } + } + } + + template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false> + METAL_FUNC static constexpr void mma( + thread dtype_frag_t& Cn0, + thread dtype_frag_t& Cn1, + const thread dtype_frag_t& A, + metal::bool_constant, + const thread dtype_frag_t& Bn0, + const thread dtype_frag_t& Bn1, + metal::bool_constant) { + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, + 32, + 16, + transpose_a, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + // Create matmul operands in registers + auto ct_a = + gemm_op + .template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = gemm_op.template get_destination_cooperative_tensor< + metal::remove_addrspace_t, + metal::remove_addrspace_t, + CType>(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_a[i] = A[i]; + } + + // Load B into right operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_b[i] = Bn0[i]; + ct_b[kElemsPerFrag + i] = Bn1[i]; + } + + // Load C into output registers (op handles accumulation) + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_c[i] = Cn0[i]; + ct_c[kElemsPerFrag + i] = Cn1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + Cn0[i] = ct_c[i]; + Cn1[i] = ct_c[kElemsPerFrag + i]; + } + } + + template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false> + METAL_FUNC static constexpr void mma( + thread dtype_frag_t& Cm0, + thread dtype_frag_t& Cm1, + const thread dtype_frag_t& Am0, + const thread dtype_frag_t& Am1, + metal::bool_constant, + const thread dtype_frag_t& B, + metal::bool_constant) { + // Create Matmul descriptor + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, + 32, + 16, + transpose_a, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + // Create matmul operands in registers + auto ct_a = + gemm_op + .template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = gemm_op.template get_destination_cooperative_tensor< + metal::remove_addrspace_t, + metal::remove_addrspace_t, + CType>(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_a[i] = Am0[i]; + ct_a[kElemsPerFrag + i] = Am1[i]; + } + + // Load B into right operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_b[i] = B[i]; + } + + // Load C into output registers (op handles accumulation) + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_c[i] = Cm0[i]; + ct_c[kElemsPerFrag + i] = Cm1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + Cm0[i] = ct_c[i]; + Cm1[i] = ct_c[kElemsPerFrag + i]; + } + } +}; + +template < + typename T, + short kTileRows_, + short kTileCols_, + class NAXFrag_ = BaseNAXFrag> +struct NAXTile { + using NAXFrag_t = NAXFrag_; + using elem_type = T; + + STEEL_CONST short kFragRows = NAXFrag_t::kFragRows; + STEEL_CONST short kFragCols = NAXFrag_t::kFragCols; + STEEL_CONST short kElemsPerFrag = NAXFrag_t::kElemsPerFrag; + + STEEL_CONST short kTileRows = kTileRows_; + STEEL_CONST short kTileCols = kTileCols_; + + STEEL_CONST short kRows = kTileRows * kFragRows; + STEEL_CONST short kCols = kTileCols * kFragCols; + + STEEL_CONST short kNumFrags = kTileRows * kTileCols; + STEEL_CONST short kElemsPerTile = kNumFrags * kElemsPerFrag; + + STEEL_CONST short kFragThrRows = NAXFrag_t::kElemRows; + STEEL_CONST short kFragThrCols = NAXFrag_t::kElemCols; + STEEL_CONST short kFragRowsJump = NAXFrag_t::kElemRowsJump; + + STEEL_CONST short kRowsPerThread = kTileRows * NAXFrag_t::kElemRows; + STEEL_CONST short kColsPerThread = kTileCols * NAXFrag_t::kElemCols; + + typedef typename NAXFrag_t::template dtype_frag_t frag_type; + + frag_type val_frags[kNumFrags]; // = {frag_type(0)}; + + METAL_FUNC NAXTile() thread {} + + METAL_FUNC constexpr void clear() thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kNumFrags; ++i) { + val_frags[i] = frag_type(0); + } + } + + METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) + thread { + return val_frags[i * kTileCols + j]; + } + + METAL_FUNC constexpr const thread frag_type& frag_at( + const short i, + const short j) const thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr thread frag_type& frag_at() thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at() const thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr thread frag_type& frag_at( + const short i, + const short j, + metal::bool_constant) thread { + if constexpr (transpose) { + return frag_at(j, i); + } else { + return frag_at(i, j); + } + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at( + const short i, + const short j, + metal::bool_constant) const thread { + if constexpr (transpose) { + return frag_at(j, i); + } else { + return frag_at(i, j); + } + } + + template + METAL_FUNC constexpr thread frag_type& frag_at() thread { + if constexpr (transpose) { + return frag_at(); + } else { + return frag_at(); + } + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at() const thread { + if constexpr (transpose) { + return frag_at(); + } else { + return frag_at(); + } + } + + METAL_FUNC thread elem_type* elems() thread { + return reinterpret_cast(val_frags); + } + + METAL_FUNC const thread elem_type* elems() const thread { + return reinterpret_cast(val_frags); + } + + template + METAL_FUNC void row_reduce( + thread metal::vec& vals) const thread { + auto vptr = (thread T*)(&vals); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + NAXFrag_t::template row_reduce( + frag_at(i, j), &vptr[i * kFragThrRows]); + } + } + } + + template + METAL_FUNC void row_bin_op( + thread metal::vec& vals) thread { + auto vptr = (thread T*)(&vals); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + NAXFrag_t::template row_bin_op( + frag_at(i, j), &vptr[i * kFragThrRows]); + } + } + } + + template + METAL_FUNC void load(const threadgroup U* src) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load( + frag_at(), + src, + Int{}, + Int{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store(threadgroup U* dst) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store( + frag_at(), + dst, + Int{}, + Int{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void load(const device U* src, const int ld) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load( + frag_at(), + src, + ld, + Int<1>{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store(device U* dst, const int ld) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store( + frag_at(), + dst, + ld, + Int<1>{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void + load_rows(const device U* src, const int ld, const short n_rows) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load_rows( + frag_at(), + src, + ld, + Int<1>{}, + n_rows, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void load_safe( + const device U* src, + const int ld, + const short2 src_tile_dims) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load_safe( + frag_at(), + src, + ld, + Int<1>{}, + src_tile_dims.y, + src_tile_dims.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_rows(device U* dst, const int ld, const short n_rows) + const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_rows( + frag_at(), + dst, + ld, + Int<1>{}, + n_rows, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_safe( + device U* dst, + const int ld, + const short2 dst_tile_dims) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_safe( + frag_at(), + dst, + ld, + Int<1>{}, + dst_tile_dims.y, + dst_tile_dims.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_slice( + device U* dst, + const int ld, + const short2 start, + const short2 stop) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_slice( + frag_at(), + dst, + ld, + Int<1>{}, + start.y, + stop.y, + start.x, + stop.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } +}; + +template < + class CTile, + class ATile, + class BTile, + bool transpose_a, + bool transpose_b> +METAL_FUNC void tile_matmad_nax( + thread CTile& C, + thread ATile& A, + metal::bool_constant, + thread BTile& B, + metal::bool_constant) { + // Static checks + constexpr short TMa = transpose_a ? ATile::kTileCols : ATile::kTileRows; + constexpr short TM = CTile::kTileRows; + static_assert(TMa == TM, "MXU tile matmul: M dimensions do not match"); + + constexpr short TNb = transpose_b ? BTile::kTileRows : BTile::kTileCols; + constexpr short TN = CTile::kTileCols; + static_assert(TNb == TN, "MXU tile matmul: N dimensions do not match"); + + constexpr short TKa = transpose_a ? ATile::kTileRows : ATile::kTileCols; + constexpr short TK = transpose_b ? BTile::kTileCols : BTile::kTileRows; + static_assert(TKa == TK, "MXU tile matmul: K dimensions do not match"); + + constexpr auto ta = metal::bool_constant{}; + constexpr auto tb = metal::bool_constant{}; + + if constexpr (TN == 1 && TM % 2 == 0) { + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < TM; mm += 2) { + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < TN; ++nn) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < TK; ++kk) { + CTile::NAXFrag_t::mma( + C.frag_at(mm, nn), + C.frag_at(mm + 1, nn), + A.frag_at(mm, kk, ta), + A.frag_at(mm + 1, kk, ta), + metal::bool_constant{}, + B.frag_at(kk, nn, tb), + metal::bool_constant{}); + } + } + } + } else if constexpr (TN % 2 == 0) { + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < TM; ++mm) { + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < TN; nn += 2) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < TK; ++kk) { + CTile::NAXFrag_t::mma( + C.frag_at(mm, nn), + C.frag_at(mm, nn + 1), + A.frag_at(mm, kk, ta), + metal::bool_constant{}, + B.frag_at(kk, nn, tb), + B.frag_at(kk, nn + 1, tb), + metal::bool_constant{}); + } + } + } + } +} + +} // namespace steel +} // namespace mlx + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/gated_delta_nax_ops.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/gated_delta_nax_ops.h" +// Copyright © 2026 Apple Inc. + +#include + +#include +#include + + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +typedef mlx::steel::NAXTile _M16x16; +typedef mlx::steel::NAXTile _M16x32; + +// NAX MACROS +#define AT_NAX(TILE, IDX) TILE.elems()[IDX] + +// out = a - b +template +METAL_FUNC T operator-(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) - b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator-(const thread T& a) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = -a.frag_at(0, f); + } + return out; +} + +// out = a + b +template +METAL_FUNC T operator+(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator+(const thread T& a, float addend) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + addend; + } + return out; +} + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +// out = a * b, elementwise. Not a matmul. +template +METAL_FUNC T operator*(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator*(const thread T& a, float s) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * s; + } + return out; +} + +template +METAL_FUNC T fmadd(const thread T& a, const thread T& b, const thread T& c) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f) + c.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC _M16x16 reduce(const thread T& a) { + _M16x16 out; + out.frag_at(0, 0) = a.frag_at(0, 0); + STEEL_PRAGMA_UNROLL + for (short f = 1; f < T::kNumFrags; f++) { + out.frag_at(0, 0) += a.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T scale_rows(const thread T& tile, const thread float* s) { + typename T::frag_type sv; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + sv[i] = s[i >> 2]; + } + + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = tile.frag_at(0, f) * sv; + } + return out; +} + +template +METAL_FUNC void row_sum(thread float* dst, const thread T& tile) { + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + dst[i >> 2] += tile.frag_at(0, f)[i]; + } + } +} + +// Scales row i by DEC2[group(i)] == exp(gamma_{C-1} - gamma_i). +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + +#define SUB_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) - AT_NAX(TILE2, _i); \ + } \ + } + +#define ADD_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) + AT_NAX(TILE2, _i); \ + } \ + } + +#define FMA_NAX(TILE0, S, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { \ + (TILE0)[_i] = (S) * (TILE1)[_i] + (TILE2)[_i]; \ + } \ + } + +#define SCALE_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) *= (S); \ + } \ + } + +#define SCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +#define SCALE_BETA_NAX(TILE0, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (BETA2)[_w >> 2]; \ + } \ + } + +#define SCALE2_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + const short _fm = mlx::steel::BaseNAXFrag::get_coord(_w).y; \ + AT_NAX(TILE0, _i) *= metal::fast::exp((GAMMA)[(C) - 1] - (GAMMA)[_fm]); \ + } \ + } + +#define SCALE_TRI_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x > _c.y) \ + ? 0.f \ + : metal::fast::exp((GAMMA)[_c.y] - (GAMMA)[_c.x]); \ + } \ + } + +#define SCALE_TRIEQ_NAX1(TILE0, BETA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x >= _c.y) ? 0.f : (BETA)[_i >> 2]; \ + } \ + } + +namespace mlx { +namespace steel { +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A0, + const thread BaseNAXFrag::dtype_frag_t& A1, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B0, + const thread BaseNAXFrag::dtype_frag_t& B1, + metal::bool_constant) { + // M=16, N=16, K=32: A and B each two K-fragments, single 16x16 C. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 16, 32, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A0[i]; + ct_a[BaseNAXFrag::kElemsPerFrag + i] = A1[i]; + ct_b[i] = B0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = B1[i]; + ct_c[i] = C[i]; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a, + bool transpose_b, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B, + metal::bool_constant) { + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = B[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + ct_c[i] = C[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mman( + thread BaseNAXFrag::dtype_frag_t& Cn0, + thread BaseNAXFrag::dtype_frag_t& Cn1, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& Bn0, + const thread BaseNAXFrag::dtype_frag_t& Bn1, + metal::bool_constant) { + // M=16, N=32, K=16: single A (K=16), B and C two N-fragments each. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + // Create matmul operands in registers + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = Bn0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = Bn1[i]; + ct_c[i] = Cn0[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = Cn1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + Cn0[i] = ct_c[i]; + Cn1[i] = ct_c[BaseNAXFrag::kElemsPerFrag + i]; + } +} + +} // namespace steel +} // namespace mlx + +#define MM16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x32(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + A.frag_at(0, (AO) + 1), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MM16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MMA16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +// Row sum of an elementwise product, reduced over the fragment's column axis. +// DST[0] is the fm row group, DST[1] the fm + kElemRowsJump group. +#define ROWSUM_NAX(DST, TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i) * AT_NAX(TILE1, _i); \ + } \ + } + +// already generic +#define SCALE_BETA_NAX_O(DST, TILE, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(DST, _i) = AT_NAX(TILE, _i) * (BETA2)[_w >> 2]; \ + } \ + } + +#define ROWSUM1_NAX(DST, TILE0) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i); \ + } \ + } + +#define MUL_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULA_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) += AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULS_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) -= AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define NSCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define SCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (ROW2)[_w >> 2]; \ + } \ + } + +// As SCALE_ROW_P but also negates, in one pass. +#define NSCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * (ROW2)[_w >> 2]; \ + } \ + } + +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/atomic.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/atomic.h" +// Copyright © 2023 Apple Inc. + + +#include +#include + +using namespace metal; + +/////////////////////////////////////////////////////////////////////////////// +// Atomic utils +/////////////////////////////////////////////////////////////////////////////// + +#pragma METAL internals : enable +template +constexpr constant bool is_metal_atomic = _disjunction< + is_same, + is_same, + is_same, + is_same>::value; + +#pragma METAL internals : disable + +template +struct mlx_atomic { + atomic val; +}; + +template +struct mlx_atomic>> { + atomic val; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Native metal atomics +/////////////////////////////////////////////////////////////////////////////// + +template , bool> = true> +METAL_FUNC T +mlx_atomic_load_explicit(device mlx_atomic* object, size_t offset) { + return atomic_load_explicit(&(object[offset].val), memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void +mlx_atomic_store_explicit(device mlx_atomic* object, T val, size_t offset) { + atomic_store_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_and_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + atomic_fetch_and_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_or_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + atomic_fetch_or_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_min_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + atomic_fetch_min_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_max_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + atomic_fetch_max_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_add_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + atomic_fetch_add_explicit(&(object[offset].val), val, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_mul_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + T expected = mlx_atomic_load_explicit(object, offset); + while (!mlx_atomic_compare_exchange_weak_explicit( + object, &expected, val * expected, offset)) { + // Workaround: Metal's atomic_compare_exchange_weak_explicit does + // not perform bitwise comparison as required by the C++ atomics spec. + // The compiler lowers the success check to `fcmp fast ueq` under + // no-nans-fp-math, which evaluates to false when either operand is NaN - + // even when the bit patterns are identical. With NaN in memory the CAS + // can never succeed, so the loop spins. Bail out instead: memory is + // already NaN and that is the correct reduction result regardless of + // this thread's update. + if constexpr (metal::is_floating_point_v) { + if (isnan(expected)) { + break; + } + } + } +} + +template , bool> = true> +METAL_FUNC bool mlx_atomic_compare_exchange_weak_explicit( + device mlx_atomic* object, + thread T* expected, + T val, + size_t offset) { + return atomic_compare_exchange_weak_explicit( + &(object[offset].val), + expected, + val, + memory_order_relaxed, + memory_order_relaxed); +} + +// Specialization for float since it does not atomic_fetch_min_explicit +template <> +METAL_FUNC void mlx_atomic_fetch_min_explicit( + device mlx_atomic* object, + float val, + size_t offset) { + float expected = mlx_atomic_load_explicit(object, offset); + while (val < expected) { + if (mlx_atomic_compare_exchange_weak_explicit( + object, &expected, val, offset)) { + return; + } + } +} + +// Specialization for float since it does not atomic_fetch_max_explicit +template <> +METAL_FUNC void mlx_atomic_fetch_max_explicit( + device mlx_atomic* object, + float val, + size_t offset) { + float expected = mlx_atomic_load_explicit(object, offset); + while (val > expected) { + if (mlx_atomic_compare_exchange_weak_explicit( + object, &expected, val, offset)) { + return; + } + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Custom atomics +/////////////////////////////////////////////////////////////////////////////// + +namespace { + +template +constexpr constant uint packing_size = sizeof(uint) / sizeof(T); + +template +union uint_or_packed { + T val[packing_size]; + uint bits; +}; + +template +struct mlx_atomic_update_helper { + uint operator()(uint_or_packed init, T update, size_t elem_offset) thread { + Op op; + init.val[elem_offset] = op(update, init.val[elem_offset]); + return init.bits; + } +}; + +template +METAL_FUNC void mlx_atomic_update_and_store( + device mlx_atomic* object, + T update, + size_t offset) { + size_t pack_offset = offset / packing_size; + size_t elem_offset = offset % packing_size; + + mlx_atomic_update_helper helper; + uint_or_packed expected; + expected.bits = + atomic_load_explicit(&(object[pack_offset].val), memory_order_relaxed); + + while (Op::condition(update, expected.val[elem_offset]) && + !mlx_atomic_compare_exchange_weak_explicit( + object, + &(expected.bits), + helper(expected, update, elem_offset), + pack_offset)) { + } +} + +template +struct __None { + static bool condition(T a, T b) { +#pragma unused(a) +#pragma unused(b) + return true; + } + + T operator()(T a, T b) thread { +#pragma unused(b) + return a; + } +}; + +template +struct __Add { + static bool condition(T a, T b) { +#pragma unused(a) +#pragma unused(b) + return true; + } + + T operator()(T a, T b) thread { + return a + b; + } +}; + +template +struct __Mul { + static bool condition(T a, T b) { +#pragma unused(a) + return b != 0; + } + + T operator()(T a, T b) thread { + return a * b; + } +}; + +template +struct __Max { + static bool condition(T a, T b) { + return a > b; + } + + T operator()(T a, T b) thread { + return max(a, b); + } +}; + +template +struct __Min { + static bool condition(T a, T b) { + return a < b; + } + + T operator()(T a, T b) thread { + return min(a, b); + } +}; + +} // namespace + +template , bool> = true> +METAL_FUNC T +mlx_atomic_load_explicit(device mlx_atomic* object, size_t offset) { + size_t pack_offset = offset / sizeof(T); + size_t elem_offset = offset % sizeof(T); + uint_or_packed packed_val; + packed_val.bits = + atomic_load_explicit(&(object[pack_offset].val), memory_order_relaxed); + return packed_val.val[elem_offset]; +} + +template , bool> = true> +METAL_FUNC void +mlx_atomic_store_explicit(device mlx_atomic* object, T val, size_t offset) { + mlx_atomic_update_and_store>(object, val, offset); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_and_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + size_t pack_offset = offset / packing_size; + size_t elem_offset = offset % packing_size; + uint_or_packed identity; + identity.bits = __UINT32_MAX__; + identity.val[elem_offset] = val; + + atomic_fetch_and_explicit( + &(object[pack_offset].val), identity.bits, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_or_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + size_t pack_offset = offset / packing_size; + size_t elem_offset = offset % packing_size; + uint_or_packed identity; + identity.bits = 0; + identity.val[elem_offset] = val; + + atomic_fetch_or_explicit( + &(object[pack_offset].val), identity.bits, memory_order_relaxed); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_min_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + mlx_atomic_update_and_store>(object, val, offset); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_max_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + mlx_atomic_update_and_store>(object, val, offset); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_add_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + mlx_atomic_update_and_store>(object, val, offset); +} + +template , bool> = true> +METAL_FUNC void mlx_atomic_fetch_mul_explicit( + device mlx_atomic* object, + T val, + size_t offset) { + mlx_atomic_update_and_store>(object, val, offset); +} + +template , bool> = true> +METAL_FUNC bool mlx_atomic_compare_exchange_weak_explicit( + device mlx_atomic* object, + thread uint* expected, + uint val, + size_t offset) { + return atomic_compare_exchange_weak_explicit( + &(object[offset].val), + expected, + val, + memory_order_relaxed, + memory_order_relaxed); +} + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h" +// Copyright © 2026 Apple Inc. + + +#include + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +template +METAL_FUNC void reduce_tile_tg( + thread TileT& acc, + threadgroup float* scratch, + device mlx_atomic* out, + int row_stride, + int col_off, + short valid_rows, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(sg_id * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _s = 1; _s < kNSG; _s++) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(_s * 32 + simd_lane_id) * kE + _i]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Simdgroup 0 alone holds the total. + if (sg_id != 0) { + return; + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * row_stride + col_off + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(out, AT_NAX(acc, _i), idx); + } else { + mlx_atomic_store_explicit(out, AT_NAX(acc, _i), idx); + } + } + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_ckpt, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + device float* seg_states [[buffer(17)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + const int n_chunks = (T + C - 1) / C; + // Ceiling: the floor form gives 0 when n_chunks < Ckpt, which would leave the + // allocation empty and fault on the first read. + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + const short tail = short(T - (n_chunks - 1) * C); + + // Bases, indexed by chunk rather than walked. With two nested loops the + // incremental decrements are no longer expressible. + auto q_base = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_base = k + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dq_base = dq + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dk_base = dk + b_idx * T * Hk * Dk + hk_idx * Dk; + + auto v_base = v + b_idx * T * Hv * Dv + hv_idx * Dv; + auto dv_base = dv + b_idx * T * Hv * Dv + hv_idx * Dv; + auto co_base = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv; + + auto g_base = g + b_idx * T * Hv; + auto beta_base = beta + b_idx * T * Hv; + auto dg_base = dg + b_idx * T * Hv; + auto db_base = db + b_idx * T * Hv; + + auto cm_base = chunk_mats + n * n_chunks * 3 * 256; + auto cd_base = chunk_delta + n * n_chunks * C * Dv + dv_idx; + auto ck_base = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + // Each simdgroup owns a distinct dv slice, so these regions are disjoint and + // the replay needs no cross-simdgroup synchronisation. + auto seg_base = seg_states + (n * Ckpt * Dv + dv_idx) * Dk; + + // Per-chunk pointers, assigned from the bases before each process_chunk call. + auto q_ = q_base; + auto k_ = k_base; + auto dq_ = dq_base; + auto dk_ = dk_base; + auto v_ = v_base; + auto dv_ = dv_base; + auto co_ = co_base; + auto g_ = g_base; + auto beta_ = beta_base; + auto dg_ = dg_base; + auto db_ = db_base; + auto i_chunk_mats = cm_base; + auto i_chunk_delta = cd_base; + auto i_seg = seg_base; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, taken from the replayed segment. + _M16xDk S_tile; + + _M16x32 K_tile, Q_tile; + _M16x16 V_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // From the replayed segment rather than a per-chunk checkpoint. + S_tile.load(i_seg, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + if (fm < valid_rows) { + db_st[fm] = _b0; + } + if (fm1 < valid_rows) { + db_st[fm1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (fm == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (fm < valid_rows) { + dg_st[fm] = _d0; + } + if (fm1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (fm1 < valid_rows) { + dg_st[fm1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk segments in reverse. Each is replayed forward from its checkpoint to + // recover the entry states, then walked backwards. + // Backward over one segment: replay its entry states from the checkpoint, + // then walk it in reverse. HasTail is a compile-time tag so valid_rows is the + // constant C on every chunk of an interior segment, which folds away the + // row guards in the dq/dk stores and the load_rows switch in the replay. + auto process_segment = [&](const int seg, + auto tail_tag) __attribute__((always_inline)) { + constexpr bool HasTail = decltype(tail_tag)::value; + + const int seg_start = seg * Ckpt; + const int rem = n_chunks - seg_start; + const int n_in_seg = (rem < Ckpt) ? rem : Ckpt; + const int n_full = HasTail ? n_in_seg - 1 : n_in_seg; + + // delta is cached per chunk, so the replay is the state recurrence alone: + // S <- exp(gamma_C) S + K_dec^T delta + // No T^-1, no W, no U -- roughly a tenth of a full chunk's work, which is + // what makes trading Ckpt-fold memory for it worthwhile. + // + // Scoped so S is dead before process_chunk runs: it is a _M16xDk, and + // having it live alongside S_tile and dS_tile would put three of them in + // flight. + { + _M16xDk S; + S.load(ck_base + seg * Dv * Dk, Dk); + + auto replay_one = [&](const int j, + const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + S.store(seg_base + j * Dv * Dk, Dk); + + const int c = seg_start + j; + auto k_c = k_base + c * C * Hk * Dk; + auto g_c = g_base + c * C * Hv; + auto cd_c = cd_base + c * C * Dv; + + float gv = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max( + g_c[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + auto gs = simd_prefix_inclusive_sum(gv); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gs); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float g_last = gamma[C - 1]; + const float dec[2] = { + metal::fast::exp(g_last - gamma[fm]), + metal::fast::exp(g_last - gamma[fm1])}; + + _M16x16 delta_tile; + delta_tile.load(cd_c, Dv); + + S = S * metal::fast::exp(g_last); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 Kd; + if constexpr (B) { + Kd.load_rows(k_c + kk, Dk * Hk, valid_rows); + } else { + Kd.load(k_c + kk, Dk * Hk); + } + Kd = scale_rows(Kd, dec); + MMA16x32x16(S, kk / 16, delta_tile, true, 0, Kd, false, 0); + } + }; + + for (int j = 0; j < n_full; j++) { + replay_one(j, C, metal::false_type{}); + } + if constexpr (HasTail) { + replay_one(n_in_seg - 1, tail, metal::true_type{}); + } + } + + auto set_chunk_ptrs = [&](const int j) __attribute__((always_inline)) { + const int c = seg_start + j; + q_ = q_base + c * C * Hk * Dk; + k_ = k_base + c * C * Hk * Dk; + dq_ = dq_base + c * C * Hk * Dk; + dk_ = dk_base + c * C * Hk * Dk; + v_ = v_base + c * C * Hv * Dv; + dv_ = dv_base + c * C * Hv * Dv; + co_ = co_base + c * C * Hv * Dv; + g_ = g_base + c * C * Hv; + beta_ = beta_base + c * C * Hv; + dg_ = dg_base + c * C * Hv; + db_ = db_base + c * C * Hv; + i_chunk_mats = cm_base + c * 3 * 256; + i_chunk_delta = cd_base + c * C * Dv; + i_seg = seg_base + j * Dv * Dk; + }; + + if constexpr (HasTail) { + set_chunk_ptrs(n_in_seg - 1); + process_chunk(tail, metal::true_type{}); + } + for (int j = n_full - 1; j >= 0; --j) { + set_chunk_ptrs(j); + process_chunk(C, metal::false_type{}); + } + }; + + // Only the last segment can hold a short chunk + int seg = n_ckpt - 1; + if (tail != C) { + process_segment(seg, metal::true_type{}); + --seg; + } + for (; seg >= 0; --seg) { + process_segment(seg, metal::false_type{}); + } + + dS_tile.store(o_dh, Dk); +} + +template +[[kernel]] void gated_delta_vjp_fused_nax1( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; // KdKb_tmp folded away + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_r0 < valid_rows) { + db_st[_r0] = _b0; + } + if (_r1 < valid_rows) { + db_st[_r1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (_r0 == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (_r0 < valid_rows) { + dg_st[_r0] = _d0; + } + if (_r1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (_r1 < valid_rows) { + dg_st[_r1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +template +METAL_FUNC void reduce_tile_tg0( + thread TileT& acc, + threadgroup float* scratch, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short lo = kNSG / 2; lo > 0; lo >>= 1) { + if (sg_id >= lo && sg_id < 2 * lo) { + const short dst = sg_id - lo; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(dst * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id < lo) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(sg_id * 32 + simd_lane_id) * kE + _i]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax0( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 2) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 NI_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(NI_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(NI_tile, _i) = (_c.x == _c.y) ? -1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw; + MUL_NAX(QKt_tile, QKt_tile, tri_decay); + + TUinv_tile = TWinv_tile; + MUL_NAX(TUinv_tile, TUinv_tile, tri_decay); + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + MUL_NAX(dODT, dODT, tri_decay); + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + SCALE2_P(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + _M16x32 Kb_tile; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + + SCALE_BETA_NAX_O(Kb_tile, K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg(dq_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dq_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + const short _fn = _c.x + _f * 16; + const short _fm = _c.y; + if (_fm < valid_rows) { + const int idx = _fm * Hk * Dk + kk + _fn; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } else { + // Dv reduction done in threadgroup memory: single writer. + mlx_atomic_store_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } + } + } + } + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + SCALE_BETA_NAX(dVb_tile, beta_fm); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dVb_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.y < valid_rows) { + dv_[_c.y * Hv * Dv + dv_idx + _c.x] = AT_NAX(dVb_tile, _i); + } + } + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + SCALE_BETA_NAX(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + MUL_NAX(dTU_tile, dTU_tile, tri_decay); // dTinv = dT_W + (dT_U * D). + + ADD_NAX(dTinv_tile, dTW_tile, dTU_tile); + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + SCALE_NAX(dA_tile, -1.0f); + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = dA_tile; + SCALE_TRIEQ_NAX1(G_tile, beta_fm); + _M16x16 GGt_tile; + GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile; + _M16x16 R_tile; + + MUL_NAX(P_tile, QKt_raw, dODT); + MUL_NAX(R_tile, TWinv_tile, dTU_tile); + ADD_NAX(dgam_pair, P_tile, R_tile); + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, dKb_tile, t1, KdKb_tmp; + _M16x32 QgdOS, TbK, KdKC_blk; + + load_seq(Q_tile, q_ + kk, Hk * Dk); // [16 x 32] + load_seq(K_tile, k_ + kk, Dk * Hk); // [16 x 32] + + // gamma: + rowsum(Q * gamma*(dO @ S)) + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(QgdOS, row_exp); + MULA_NAX(dgam_row32, QgdOS, Q_tile); + + // dODT.T @ Q and (G + G.T) @ K + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + // B (T.T @ dW_raw), dW_raw = -gamma * (ddelta @ S) + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + + // dbeta term uses dK_b before the beta scaling, with raw K + MUL_NAX(KdKb_tmp, dKb_tile, K_tile); + ADD_NAX(KdKb, KdKb, KdKb_tmp); + + SCALE_BETA_NAX(dKb_tile, beta_fm); + ADD_NAX(dk_acc, dk_acc, dKb_tile); + + // D_C * (delta @ dS) + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + SCALE2_P(t1, dec_exp); + ADD_NAX(dk_acc, dk_acc, t1); + + // gamma stuff + MUL_NAX(KdKC_blk, K_tile, t1); + SUB_NAX(dgam_row32, dgam_row32, KdKC_blk); + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC_blk)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC_blk, _i); + } + + // gamma stuff: gamma_C * sum(S * dS) + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16)[_i] * + dS_tile.frag_at(0, kk / 16)[_i]; + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]; + } + + // gamma stuff + SCALE_BETA_NAX(K_tile, beta_fm); + SCALE_NAX(dW_raw, -1.0f); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + MULS_NAX(dgam_row32, TbK, dW_raw); + + // dk reduces over Dv the same way dq does. + reduce_tile_tg(dk_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dk_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * Hk * Dk + kk + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } else { + mlx_atomic_store_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } + } + } + } + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + _M16x16 VdVb; + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + MUL_NAX(VdVb, V_tile, TUddelta); + + _M16x16 AKKt; + TRIL_NAX(AKKt, dA_tile); + MUL_NAX(AKKt, AKKt, KKt_tile); + + ADD_NAX(VdVb, VdVb, AKKt); + ROWSUM1_NAX(dbeta_acc, VdVb); + ROWSUM1_NAX(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _r = 0; _r < 2; _r++) { + float _b = dbeta_acc[_r]; + _b += simd_shuffle_xor(_b, ushort(1)); + _b += simd_shuffle_xor(_b, ushort(8)); + + const short _row = fm + _r * mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_row < valid_rows) { + db_st[_row] = _b; + } + } + } + + // Fold the two fragments: only the row sum of dgam_row is used downstream, + // and row sums are additive across fragments. + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + AT_NAX(dgam_row, _i) = AT_NAX(dgam_row32, _i) + + AT_NAX(dgam_row32, mlx::steel::BaseNAXFrag::kElemsPerFrag + _i); + } + + // reduce and store dgamma: rowsum(row + pair) - colsum(pair) + ADD_NAX(dgam_row, dgam_row, dgam_pair); + _M16x16 dgam_tile, cs_tile; + MM16x16x16(dgam_tile, 0, dgam_row, false, 0, Ones_tile, false, 0); + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + SUB_NAX(dgam_tile, dgam_tile, cs_tile); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dgam_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.x == 0) { + dg_st[_c.y] = AT_NAX(dgam_tile, _i); + } + } + // The gamma_{C-1}-only term lands on the same slot the loop just wrote, + // so the lanes must be ordered before lane 0 accumulates into it. + simdgroup_barrier(mem_flags::mem_threadgroup); + const float dgam_last_red = simd_sum(dgam_last); + if (simd_lane_id == 0 && valid_rows > 0) { + dg_st[valid_rows - 1] += dgam_last_red; + } + } + + // One barrier serves both stages; simdgroup 0 commits. + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + SCALE_ROW_P(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + SCALE_BETA_NAX(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + NSCALE_ROW_P(W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +// Postprocessing dg. Similar idea to what is done in the triton kernel. +// The kernel computes the gradient with respect to the log. +template +[[kernel]] void gated_delta_dgamma_to_dg( + const device InT* g [[buffer(0)]], + device float* dg [[buffer(1)]], // in: dL/dgamma, out: dL/dg + constant int& T [[buffer(2)]], + constant int& Hv [[buffer(3)]], + constant int& n_total [[buffer(4)]], // B * Hv + uint2 pos [[thread_position_in_grid]]) { + const int n = int(pos.x); // b * Hv + hv + const int c = int(pos.y); // chunk index + + if (n >= n_total) { + return; + } + + const int t0 = c * C; + if (t0 >= T) { + return; + } + const int len = min(C, T - t0); + + const int b_idx = n / Hv; + const int hv_idx = n % Hv; + const int base = b_idx * T * Hv + hv_idx; + + float acc = 0.0f; + for (int j = len - 1; j >= 0; --j) { + const int idx = base + (t0 + j) * Hv; + acc += static_cast(dg[idx]); + float gv = metal::max(static_cast(g[idx]), 1e-6f); + dg[idx] = acc / gv; + } +} + +/////////////////////////////////////////////////////////////////////////////// +)preamble"; +} + +} // namespace mlx::core::metal diff --git a/Source/Cmlx/mlx-generated/gemv.cpp b/Source/Cmlx/mlx-generated/gemv.cpp index 0a4a5c78a..71a0757cd 100644 --- a/Source/Cmlx/mlx-generated/gemv.cpp +++ b/Source/Cmlx/mlx-generated/gemv.cpp @@ -681,10 +681,20 @@ constexpr complex_t operator*(complex_t a, complex_t b) { template constexpr complex_t operator/(complex_t a, complex_t b) { - auto denom = b.real * b.real + b.imag * b.imag; - auto x = a.real * b.real + a.imag * b.imag; - auto y = a.imag * b.real - a.real * b.imag; - return {x / denom, y / denom}; + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; } template < @@ -692,11 +702,7 @@ template < typename U, enable_if_t && is_lane_convertible_v, bool> = true> constexpr complex_t operator/(U a, complex_t b) { - auto scalar = static_cast(a); - auto denom = b.real * b.real + b.imag * b.imag; - auto x = scalar * b.real; - auto y = -scalar * b.imag; - return {x / denom, y / denom}; + return complex_t(a) / b; } template diff --git a/Source/Cmlx/mlx-generated/gemv_masked.cpp b/Source/Cmlx/mlx-generated/gemv_masked.cpp index 8e2faebe0..e5269ed6d 100644 --- a/Source/Cmlx/mlx-generated/gemv_masked.cpp +++ b/Source/Cmlx/mlx-generated/gemv_masked.cpp @@ -511,7 +511,7 @@ struct GEMVTKernel { const int n_block_idx = blockM > blockN ? out_col / blockM : int(tid.x); const int out_mask_offset = - !has_output_mask ? 0 : n_block_idx; // * out_mask_strides[0]; + !has_output_mask ? 0 : n_block_idx * out_mask_strides[0]; int mat_mask_offset = !has_operand_mask ? 0 : n_block_idx * mat_mask_strides[0]; diff --git a/Source/Cmlx/mlx-generated/masked_scatter.cpp b/Source/Cmlx/mlx-generated/masked_scatter.cpp index d660afad9..25e4ffb0c 100644 --- a/Source/Cmlx/mlx-generated/masked_scatter.cpp +++ b/Source/Cmlx/mlx-generated/masked_scatter.cpp @@ -44,7 +44,7 @@ template if (src_contiguous) { out[idx] = src[batch_idx * src_batch_size + src_index]; } else { - out[idx] = src[elem_to_loc( + out[idx] = src[elem_to_loc( batch_idx * src_batch_size + src_index, src_shapes, src_strides, diff --git a/Source/Cmlx/mlx-generated/metal/complex.h b/Source/Cmlx/mlx-generated/metal/complex.h index 629b6289b..874e837ca 100644 --- a/Source/Cmlx/mlx-generated/metal/complex.h +++ b/Source/Cmlx/mlx-generated/metal/complex.h @@ -264,10 +264,20 @@ constexpr complex_t operator*(complex_t a, complex_t b) { template constexpr complex_t operator/(complex_t a, complex_t b) { - auto denom = b.real * b.real + b.imag * b.imag; - auto x = a.real * b.real + a.imag * b.imag; - auto y = a.imag * b.real - a.real * b.imag; - return {x / denom, y / denom}; + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; } template < @@ -275,11 +285,7 @@ template < typename U, enable_if_t && is_lane_convertible_v, bool> = true> constexpr complex_t operator/(U a, complex_t b) { - auto scalar = static_cast(a); - auto denom = b.real * b.real + b.imag * b.imag; - auto x = scalar * b.real; - auto y = -scalar * b.imag; - return {x / denom, y / denom}; + return complex_t(a) / b; } template diff --git a/Source/Cmlx/mlx-generated/metal/conv.metal b/Source/Cmlx/mlx-generated/metal/conv.metal index 74027df73..0f49414eb 100644 --- a/Source/Cmlx/mlx-generated/metal/conv.metal +++ b/Source/Cmlx/mlx-generated/metal/conv.metal @@ -418,8 +418,8 @@ winograd_conv_2d_weight_transform( // wt_out is stored transposed (A x A x C x O) short ohw_0 = sm * 8 + sn; short ohw_1 = sm * 8 + sn + 1; - device T* wt_out_0 = wt_out + ohw_0 * C * O + ko; - device T* wt_out_1 = wt_out + ohw_1 * C * O + ko; + device T* wt_out_0 = wt_out + size_t(ohw_0) * C * O + ko; + device T* wt_out_1 = wt_out + size_t(ohw_1) * C * O + ko; // Prepare shared memory threadgroup T Ws[BO][R][R][BC]; diff --git a/Source/Cmlx/mlx-generated/metal/fp_quantized.h b/Source/Cmlx/mlx-generated/metal/fp_quantized.h index 880ad589f..57d66a7c7 100644 --- a/Source/Cmlx/mlx-generated/metal/fp_quantized.h +++ b/Source/Cmlx/mlx-generated/metal/fp_quantized.h @@ -334,6 +334,7 @@ template < typename T, int group_size, int bits, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> METAL_FUNC void fp_qmv_fast_impl( @@ -367,6 +368,15 @@ METAL_FUNC void fp_qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // Reuse the last valid row for reads beyond the output tile. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; @@ -376,8 +386,12 @@ METAL_FUNC void fp_qmv_fast_impl( load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device auto* sl = scales + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device auto* sl = scales + src * in_vec_size_g; U s = dequantize_scale(sl[0]); result[row] += qdot(wl, x_thread, s); @@ -395,7 +409,7 @@ METAL_FUNC void fp_qmv_fast_impl( for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { if constexpr (has_global_scale) { y[row] = static_cast(result[row] * inv_scale_enc); } else { @@ -796,6 +810,7 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, const bool has_global_scale = false, const int BM = 32, const int BK = 32, @@ -805,7 +820,7 @@ METAL_FUNC void fp_qmm_t_impl( const device uint8_t* scales, const device float* global_scale, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, threadgroup T* Ws, const constant int& K, @@ -830,7 +845,7 @@ METAL_FUNC void fp_qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; using loader_w_t = QuantizedBlockLoader< @@ -1243,6 +1258,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv_fast( @@ -1284,6 +1300,7 @@ template < T, group_size, bits, + partial_rows, has_global_scale, results_per_simdgroup>( w, @@ -1303,6 +1320,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv( @@ -1511,14 +1529,14 @@ template template < typename T, - const int group_size, - const int bits, - const bool aligned_N, - const bool batched, - const bool has_global_scale = false, - const int BM = 32, - const int BK = 32, - const int BN = 32> + int group_size, + int bits, + bool aligned_N, + bool batched, + bool has_global_scale = false, + int BM = 32, + int BK = 32, + int BN = 32> [[kernel]] void fp_qmm_t( const device uint32_t* w, const device uint8_t* scales, @@ -1562,7 +1580,16 @@ template < s_strides, tid); } - fp_qmm_t_impl( + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( w, scales, global_scale, @@ -1684,7 +1711,7 @@ template w_strides, s_strides, tid); - fp_qmv_fast_impl( + fp_qmv_fast_impl( w, scales, global_scale, @@ -1881,7 +1908,16 @@ template < w_strides, s_strides, tid); - fp_qmm_t_impl( + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( w, scales, global_scale, @@ -1911,7 +1947,7 @@ template < const device uint32_t* w [[buffer(0)]], const device uint8_t* scales [[buffer(1)]], const device T* x [[buffer(2)]], - device T* y [[buffer(3)]], + device float* y [[buffer(3)]], const constant int& K [[buffer(4)]], const constant int& N [[buffer(5)]], const constant int& M [[buffer(6)]], @@ -1936,7 +1972,7 @@ template < scales += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - fp_qmm_t_impl( + fp_qmm_t_impl( (const device uint32_t*)wl, scales, nullptr, diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_nax_ops.h b/Source/Cmlx/mlx-generated/metal/gated_delta_nax_ops.h new file mode 100644 index 000000000..154a6e4ba --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_nax_ops.h @@ -0,0 +1,588 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include + +#include +#include + +#include "steel/gemm/nax.h" + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +typedef mlx::steel::NAXTile _M16x16; +typedef mlx::steel::NAXTile _M16x32; + +// NAX MACROS +#define AT_NAX(TILE, IDX) TILE.elems()[IDX] + +// out = a - b +template +METAL_FUNC T operator-(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) - b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator-(const thread T& a) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = -a.frag_at(0, f); + } + return out; +} + +// out = a + b +template +METAL_FUNC T operator+(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator+(const thread T& a, float addend) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + addend; + } + return out; +} + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +// out = a * b, elementwise. Not a matmul. +template +METAL_FUNC T operator*(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator*(const thread T& a, float s) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * s; + } + return out; +} + +template +METAL_FUNC T fmadd(const thread T& a, const thread T& b, const thread T& c) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f) + c.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC _M16x16 reduce(const thread T& a) { + _M16x16 out; + out.frag_at(0, 0) = a.frag_at(0, 0); + STEEL_PRAGMA_UNROLL + for (short f = 1; f < T::kNumFrags; f++) { + out.frag_at(0, 0) += a.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T scale_rows(const thread T& tile, const thread float* s) { + typename T::frag_type sv; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + sv[i] = s[i >> 2]; + } + + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = tile.frag_at(0, f) * sv; + } + return out; +} + +template +METAL_FUNC void row_sum(thread float* dst, const thread T& tile) { + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + dst[i >> 2] += tile.frag_at(0, f)[i]; + } + } +} + +// Scales row i by DEC2[group(i)] == exp(gamma_{C-1} - gamma_i). +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + +#define SUB_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) - AT_NAX(TILE2, _i); \ + } \ + } + +#define ADD_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) + AT_NAX(TILE2, _i); \ + } \ + } + +#define FMA_NAX(TILE0, S, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { \ + (TILE0)[_i] = (S) * (TILE1)[_i] + (TILE2)[_i]; \ + } \ + } + +#define SCALE_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) *= (S); \ + } \ + } + +#define SCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +#define SCALE_BETA_NAX(TILE0, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (BETA2)[_w >> 2]; \ + } \ + } + +#define SCALE2_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + const short _fm = mlx::steel::BaseNAXFrag::get_coord(_w).y; \ + AT_NAX(TILE0, _i) *= metal::fast::exp((GAMMA)[(C) - 1] - (GAMMA)[_fm]); \ + } \ + } + +#define SCALE_TRI_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x > _c.y) \ + ? 0.f \ + : metal::fast::exp((GAMMA)[_c.y] - (GAMMA)[_c.x]); \ + } \ + } + +#define SCALE_TRIEQ_NAX1(TILE0, BETA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x >= _c.y) ? 0.f : (BETA)[_i >> 2]; \ + } \ + } + +namespace mlx { +namespace steel { +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A0, + const thread BaseNAXFrag::dtype_frag_t& A1, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B0, + const thread BaseNAXFrag::dtype_frag_t& B1, + metal::bool_constant) { + // M=16, N=16, K=32: A and B each two K-fragments, single 16x16 C. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 16, 32, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A0[i]; + ct_a[BaseNAXFrag::kElemsPerFrag + i] = A1[i]; + ct_b[i] = B0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = B1[i]; + ct_c[i] = C[i]; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a, + bool transpose_b, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B, + metal::bool_constant) { + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = B[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + ct_c[i] = C[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mman( + thread BaseNAXFrag::dtype_frag_t& Cn0, + thread BaseNAXFrag::dtype_frag_t& Cn1, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& Bn0, + const thread BaseNAXFrag::dtype_frag_t& Bn1, + metal::bool_constant) { + // M=16, N=32, K=16: single A (K=16), B and C two N-fragments each. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + // Create matmul operands in registers + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = Bn0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = Bn1[i]; + ct_c[i] = Cn0[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = Cn1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + Cn0[i] = ct_c[i]; + Cn1[i] = ct_c[BaseNAXFrag::kElemsPerFrag + i]; + } +} + +} // namespace steel +} // namespace mlx + +#define MM16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x32(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + A.frag_at(0, (AO) + 1), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MM16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MMA16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +// Row sum of an elementwise product, reduced over the fragment's column axis. +// DST[0] is the fm row group, DST[1] the fm + kElemRowsJump group. +#define ROWSUM_NAX(DST, TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i) * AT_NAX(TILE1, _i); \ + } \ + } + +// already generic +#define SCALE_BETA_NAX_O(DST, TILE, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(DST, _i) = AT_NAX(TILE, _i) * (BETA2)[_w >> 2]; \ + } \ + } + +#define ROWSUM1_NAX(DST, TILE0) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i); \ + } \ + } + +#define MUL_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULA_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) += AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULS_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) -= AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define NSCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define SCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (ROW2)[_w >> 2]; \ + } \ + } + +// As SCALE_ROW_P but also negates, in one pass. +#define NSCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * (ROW2)[_w >> 2]; \ + } \ + } + +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } \ No newline at end of file diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update.h b/Source/Cmlx/mlx-generated/metal/gated_delta_update.h index af29ff161..841be0393 100644 --- a/Source/Cmlx/mlx-generated/metal/gated_delta_update.h +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update.h @@ -3,6 +3,8 @@ #include #include "utils.h" +constant bool save_state [[function_constant(200)]]; + #define AT(TILE, IDX) TILE.thread_elements()[IDX] #define SUB(TILE0, TILE1, TILE2) \ { \ @@ -263,25 +265,24 @@ template } /* - auto grid = MTL::Size(32, Dv, B * Hv); + auto grid = MTL::Size(32, Dv, B * Hv); auto threads = MTL::Size(32, 4, 1); */ -template +template [[kernel]] void gated_delta_seq( const device InT* q [[buffer(0)]], const device InT* k [[buffer(1)]], const device InT* v [[buffer(2)]], const device float* state_in [[buffer(3)]], - const device InT* g [[buffer(4)]], // [B, T, Hv] or [B, T, Hv, Dk] + const device InT* g [[buffer(4)]], // [B, T, Hv] const device InT* beta [[buffer(5)]], // [B, T, Hv] - // [B, Hv, Dv, Dk] device InT* y [[buffer(6)]], // [B, T, Hv, Dv] device float* state_out [[buffer(7)]], // [B, Hv, Dv, Dk] constant int& T [[buffer(8)]], + device float* state_cache [[buffer(9), function_constant(save_state)]], uint3 thread_position_in_grid [[thread_position_in_grid]], uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { - // kernel implementation auto n = thread_position_in_grid.z; auto b_idx = n / Hv; auto hv_idx = n % Hv; @@ -313,7 +314,23 @@ template auto g_ = g + b_idx * T * Hv; auto beta_ = beta + b_idx * T * Hv; + // Checkpoint every Ckpt-th step rather than every step: at T = 4096 with + // B = 4, Hv = 32 a dense cache is 34 GB, which the backward's replay makes + // unnecessary. + const int n_ckpt = (T + Ckpt - 1) / Ckpt; + auto c_state_base = state_cache + n * n_ckpt * Dv * Dk + dv_idx * Dk; + for (int t = 0; t < T; ++t) { + // Stored before the decay, so slot t/Ckpt holds the state at *entry* to + // step t. The backward replays forward from here, so it must be the entry + // state and not the exit state. + if (save_state && (t % Ckpt) == 0) { + auto c_state = c_state_base + (t / Ckpt) * Dv * Dk; + for (int i = 0; i < n_per_t; ++i) { + c_state[n_per_t * dk_idx + i] = state[i]; + } + } + float kv_mem = 0.0f; for (int i = 0; i < n_per_t; ++i) { auto s_idx = n_per_t * dk_idx + i; diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update.metal b/Source/Cmlx/mlx-generated/metal/gated_delta_update.metal index 68b86b29a..230ef4caf 100644 --- a/Source/Cmlx/mlx-generated/metal/gated_delta_update.metal +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update.metal @@ -3,15 +3,17 @@ using namespace metal; -#define instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv) \ - instantiate_kernel( \ - "seq_gated_delta_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv, \ - gated_delta_seq, \ - in_type, \ - dk, \ - dv, \ - hk, \ - hv) +#define instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, ckpt) \ + instantiate_kernel( \ + "seq_gated_delta_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv \ + "_" #ckpt, \ + gated_delta_seq, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + ckpt) #define instantiate_gated_delta_update_fused_chunk(in_type, dk, dv, hk, hv, c) \ instantiate_kernel( \ @@ -25,18 +27,24 @@ using namespace metal; hv, \ c) -#define instantiate_gated_delta_dims(in_type, dk, dv, hk, hv) \ - instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv) \ - instantiate_gated_delta_update_fused_chunk(in_type, dk, dv, hk, hv, 8) +// Ckpt is a template parameter of the sequential kernel, so the inference path +// has to name one even though it never stores. These must cover every value +// gated_delta_ckpt() can return, since the host puts it in the kernel name. +#define instantiate_gated_delta_dims(in_type, dk, dv, hk, hv) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 1) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 4) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 8) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 16) \ + instantiate_gated_delta_update_fused_chunk(in_type, dk, dv, hk, hv, 8) -#define instantiate_gated_delta(in_type) \ - instantiate_gated_delta_dims(in_type, 128, 128, 24, 24) \ - instantiate_gated_delta_dims(in_type, 128, 128, 32, 32) \ - instantiate_gated_delta_dims(in_type, 128, 128, 16, 32) \ - instantiate_gated_delta_dims(in_type, 128, 128, 16, 48) \ - instantiate_gated_delta_dims(in_type, 128, 128, 16, 16) \ - instantiate_gated_delta_dims(in_type, 128, 128, 16, 64) +#define instantiate_gated_delta(in_type) \ + instantiate_gated_delta_dims(in_type, 128, 128, 24, 24) \ + instantiate_gated_delta_dims(in_type, 128, 128, 32, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 48) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 16) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 64) instantiate_gated_delta(float); instantiate_gated_delta(bfloat16_t); -instantiate_gated_delta(float16_t); \ No newline at end of file +instantiate_gated_delta(float16_t); diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax.h b/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax.h index 15b98fd21..d9c85f432 100644 --- a/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax.h +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax.h @@ -1,336 +1,19 @@ +// Copyright © 2026 Apple Inc. #pragma once -#include - -#include -#include - -#include "steel/gemm/nax.h" +#include "gated_delta_nax_ops.h" using namespace metal; using namespace mpp; using namespace mpp::tensor_ops; -// NAX MACROS I can probably do a nice template instead of doing this -// fm = base_fm + (idx >> 2) * 8; // idx>>2 = idx/4 -> 0 for idx 0-3, 1 for -// idx 4-7 fn = base_fn + (idx % 4); // 4 consecutive columns -#define AT_NAX(TILE, IDX) TILE.elems()[IDX] - -#define SUB_NAX(TILE0, TILE1, TILE2) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ - AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) - AT_NAX(TILE2, _i); \ - } \ - } - -#define ADD_NAX(TILE0, TILE1, TILE2) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ - AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) + AT_NAX(TILE2, _i); \ - } \ - } - -#define FMA_NAX(TILE0, S, TILE1, TILE2) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { \ - (TILE0)[_i] = (S) * (TILE1)[_i] + (TILE2)[_i]; \ - } \ - } - -#define SCALE_NAX(TILE0, S) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ - AT_NAX(TILE0, _i) *= (S); \ - } \ - } - -#define SCALE_ROW_NAX(TILE0, S) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ - const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ - AT_NAX(TILE0, _i) *= \ - metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ - } \ - } - -#define SCALE_BETA_NAX(TILE0, BETA2) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ - const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ - AT_NAX(TILE0, _i) *= (BETA2)[_w >> 2]; \ - } \ - } - -#define SCALE2_NAX(TILE0, GAMMA) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ - const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ - const short _fm = mlx::steel::BaseNAXFrag::get_coord(_w).y; \ - AT_NAX(TILE0, _i) *= metal::fast::exp((GAMMA)[(C) - 1] - (GAMMA)[_fm]); \ - } \ - } - -#define SCALE_TRI_NAX(TILE0, GAMMA) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ - const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ - AT_NAX(TILE0, _i) *= (_c.x > _c.y) \ - ? 0.f \ - : metal::fast::exp((GAMMA)[_c.y] - (GAMMA)[_c.x]); \ - } \ - } - -#define SCALE_TRIEQ_NAX1(TILE0, BETA) \ - { \ - STEEL_PRAGMA_UNROLL \ - for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ - const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ - AT_NAX(TILE0, _i) *= (_c.x >= _c.y) ? 0.f : (BETA)[_i >> 2]; \ - } \ - } - -namespace mlx { -namespace steel { -template < - typename CType, - typename AType, - typename BType, - bool transpose_a = false, - bool transpose_b = false, - mpp::tensor_ops::matmul2d_descriptor::mode Mode = - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> -METAL_FUNC static constexpr void mma( - thread BaseNAXFrag::dtype_frag_t& C, - const thread BaseNAXFrag::dtype_frag_t& A0, - const thread BaseNAXFrag::dtype_frag_t& A1, - metal::bool_constant, - const thread BaseNAXFrag::dtype_frag_t& B0, - const thread BaseNAXFrag::dtype_frag_t& B1, - metal::bool_constant) { - // M=16, N=16, K=32: A and B each two K-fragments, single 16x16 C. - constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( - 16, 16, 32, transpose_a, transpose_b, true, Mode); - - mpp::tensor_ops::matmul2d gemm_op; - - auto ct_a = - gemm_op.template get_left_input_cooperative_tensor(); - auto ct_b = - gemm_op - .template get_right_input_cooperative_tensor(); - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); - - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - ct_a[i] = A0[i]; - ct_a[BaseNAXFrag::kElemsPerFrag + i] = A1[i]; - ct_b[i] = B0[i]; - ct_b[BaseNAXFrag::kElemsPerFrag + i] = B1[i]; - ct_c[i] = C[i]; - } - - gemm_op.run(ct_a, ct_b, ct_c); - - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - C[i] = ct_c[i]; - } -} - -template < - typename CType, - typename AType, - typename BType, - bool transpose_a, - bool transpose_b, - mpp::tensor_ops::matmul2d_descriptor::mode Mode = - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> -METAL_FUNC static constexpr void mma( - thread BaseNAXFrag::dtype_frag_t& C, - const thread BaseNAXFrag::dtype_frag_t& A, - metal::bool_constant, - const thread BaseNAXFrag::dtype_frag_t& B, - metal::bool_constant) { - constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( - 16, 32, 16, transpose_a, transpose_b, true, Mode); - - mpp::tensor_ops::matmul2d gemm_op; - - auto ct_a = - gemm_op.template get_left_input_cooperative_tensor(); - auto ct_b = - gemm_op - .template get_right_input_cooperative_tensor(); - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); - - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - ct_a[i] = A[i]; - ct_b[i] = B[i]; - ct_b[BaseNAXFrag::kElemsPerFrag + i] = 0.0; - ct_c[i] = C[i]; - ct_c[BaseNAXFrag::kElemsPerFrag + i] = 0.0; - } +/////////////////////////////////////////////////////////////////////////////// +// Function constants +/////////////////////////////////////////////////////////////////////////////// - gemm_op.run(ct_a, ct_b, ct_c); +constant bool save_state_cache [[function_constant(200)]]; - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - C[i] = ct_c[i]; - } -} - -template < - typename CType, - typename AType, - typename BType, - bool transpose_a = false, - bool transpose_b = false, - mpp::tensor_ops::matmul2d_descriptor::mode Mode = - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> -METAL_FUNC static constexpr void mman( - thread BaseNAXFrag::dtype_frag_t& Cn0, - thread BaseNAXFrag::dtype_frag_t& Cn1, - const thread BaseNAXFrag::dtype_frag_t& A, - metal::bool_constant, - const thread BaseNAXFrag::dtype_frag_t& Bn0, - const thread BaseNAXFrag::dtype_frag_t& Bn1, - metal::bool_constant) { - // M=16, N=32, K=16: single A (K=16), B and C two N-fragments each. - constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( - 16, 32, 16, transpose_a, transpose_b, true, Mode); - - // Create matmul op - mpp::tensor_ops::matmul2d gemm_op; - - // Create matmul operands in registers - auto ct_a = - gemm_op.template get_left_input_cooperative_tensor(); - auto ct_b = - gemm_op - .template get_right_input_cooperative_tensor(); - - // Create matmul output in register - auto ct_c = gemm_op.template get_destination_cooperative_tensor< - decltype(ct_a), - decltype(ct_b), - CType>(); - - // Load A in to left operand registers - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - ct_a[i] = A[i]; - ct_b[i] = Bn0[i]; - ct_b[BaseNAXFrag::kElemsPerFrag + i] = Bn1[i]; - ct_c[i] = Cn0[i]; - ct_c[BaseNAXFrag::kElemsPerFrag + i] = Cn1[i]; - } - - // Do matmul - gemm_op.run(ct_a, ct_b, ct_c); - - // Copy out results - STEEL_PRAGMA_UNROLL - for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { - Cn0[i] = ct_c[i]; - Cn1[i] = ct_c[BaseNAXFrag::kElemsPerFrag + i]; - } -} - -} // namespace steel -} // namespace mlx - -#define MM16x16x16(C, CO, A, TA, AO, B, TB, BO) \ - mlx::steel::mma< \ - float, \ - float, \ - float, \ - TA, \ - TB, \ - mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ - C.frag_at(0, (CO)), \ - A.frag_at(0, (AO)), \ - metal::bool_constant{}, \ - B.frag_at(0, (BO)), \ - metal::bool_constant{}); - -#define MMA16x16x16(C, CO, A, TA, AO, B, TB, BO) \ - mlx::steel::mma< \ - float, \ - float, \ - float, \ - TA, \ - TB, \ - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ - C.frag_at(0, (CO)), \ - A.frag_at(0, (AO)), \ - metal::bool_constant{}, \ - B.frag_at(0, (BO)), \ - metal::bool_constant{}); - -#define MMA16x16x32(C, CO, A, TA, AO, B, TB, BO) \ - mlx::steel::mma< \ - float, \ - float, \ - float, \ - TA, \ - TB, \ - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ - C.frag_at(0, (CO)), \ - A.frag_at(0, (AO)), \ - A.frag_at(0, (AO) + 1), \ - metal::bool_constant{}, \ - B.frag_at(0, (BO)), \ - B.frag_at(0, (BO) + 1), \ - metal::bool_constant{}); - -#define MM16x32x16(C, CO, A, TA, AO, B, TB, BO) \ - mlx::steel::mman< \ - float, \ - float, \ - float, \ - TA, \ - TB, \ - mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ - C.frag_at(0, (CO)), \ - C.frag_at(0, (CO) + 1), \ - A.frag_at(0, (AO)), \ - metal::bool_constant{}, \ - B.frag_at(0, (BO)), \ - B.frag_at(0, (BO) + 1), \ - metal::bool_constant{}); - -#define MMA16x32x16(C, CO, A, TA, AO, B, TB, BO) \ - mlx::steel::mman< \ - float, \ - float, \ - float, \ - TA, \ - TB, \ - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ - C.frag_at(0, (CO)), \ - C.frag_at(0, (CO) + 1), \ - A.frag_at(0, (AO)), \ - metal::bool_constant{}, \ - B.frag_at(0, (BO)), \ - B.frag_at(0, (BO) + 1), \ - metal::bool_constant{}); - -template +template [[kernel]] void gated_delta_fused_nax( const device InT* q [[buffer(0)]], const device InT* k [[buffer(1)]], @@ -341,6 +24,9 @@ template device InT* y [[buffer(6)]], device float* state_out [[buffer(7)]], constant int& T [[buffer(8)]], + device float* state_cache [[buffer(9)]], // [B, Hv, n_ckpt, Dv, Dk] + device float* chunk_mats [[buffer(10)]], // [B, Hv, n_chunks, 3, 16, 16] + device float* chunk_delta [[buffer(11)]], // [B, Hv, n_chunks, C, Dv] uint3 thread_position_in_grid [[thread_position_in_grid]], uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { @@ -373,6 +59,13 @@ template auto i_state = state_in + (n * Dv + dv_idx) * Dk; auto o_state = state_out + (n * Dv + dv_idx) * Dk; + const int n_chunks = (T + C - 1) / C; + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + auto c_state = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + + auto o_chunk_mats = chunk_mats + n * n_chunks * 3 * 256; + auto o_chunk_delta = chunk_delta + n * n_chunks * C * Dv + dv_idx; + threadgroup float gamma_all[C * 4]; threadgroup float* gamma = gamma_all + sg_id * C; @@ -405,6 +98,10 @@ template } mlx::steel::NAXTile TMP_tile; + // Which chunk process_chunk is on, so it knows whether this is a segment + // boundary. + int chunk_idx = 0; + auto process_chunk = [&](const short valid_rows, auto bounded_tag) __attribute__((always_inline)) { constexpr bool B = decltype(bounded_tag)::value; @@ -417,19 +114,23 @@ template } }; + // Checkpoint the state entering this chunk before anything mutates it, on + // segment boundaries only. + if (save_state_cache && (chunk_idx % Ckpt) == 0) { + S_tile.store(c_state, Dk); + c_state += Dv * Dk; + } + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) ? metal::fast::log( metal::max( - static_cast( - g_[thread_index_in_simdgroup * Hv + hv_idx]), - 1e-6f)) + float(g_[thread_index_in_simdgroup * Hv + hv_idx]), 1e-6)) : 0.0f; auto gamma_val = simd_prefix_inclusive_sum(g_val); if (thread_index_in_simdgroup < C) { gamma[thread_index_in_simdgroup] = static_cast(gamma_val); } - simdgroup_barrier(mem_flags::mem_threadgroup); beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; @@ -441,6 +142,12 @@ template MMA16x16x32(KKt_tile, 0, K_tile, false, 0, K_tile, true, 0); } + // KKt_raw is identical for every Dv tile of this chunk; only the first + // tile needs to write it out for the vjp kernel to reuse. + if (save_state_cache && dv_idx == 0) { + KKt_tile.store(o_chunk_mats, 16); + } + KKtK_tile = KKt_tile; SCALE_TRIEQ_NAX1(KKtK_tile, beta_fm); @@ -451,6 +158,12 @@ template SUB_NAX(Tinv_tile, I_tile, TMP_tile); } + // Same as KKt_raw: cache the pre-decay inverse before it is overwritten + // below by the gamma-scaled (TUinv) version. + if (save_state_cache && dv_idx == 0) { + Tinv_tile.store(o_chunk_mats + 256, 16); + } + STEEL_PRAGMA_UNROLL for (short nn = 0; nn < Dk / 16; nn += 2) { load_seq(K_tile, k_ + nn * 16, Dk * Hk); @@ -472,20 +185,29 @@ template SUB_NAX(delta_tile, U_tile, WS_tile) - tmp_tile.clear(); QKt_tile.clear(); + tmp_tile.clear(); for (int kk = 0; kk < Dk; kk += 32) { load_seq(Q_tile, q_ + kk, Hk * Dk); load_seq(K_tile, k_ + kk, Hk * Dk); - MMA16x16x32(QKt_tile, 0, Q_tile, false, 0, K_tile, true, 0); - SCALE_ROW_NAX(Q_tile, gamma); MMA16x16x32(tmp_tile, 0, Q_tile, false, 0, S_tile, true, kk / 16); } - SCALE_TRI_NAX(QKt_tile, gamma) + if (save_state_cache) { + if (dv_idx == 0) { + QKt_tile.store(o_chunk_mats + 512, 16); + } + // Every Dv tile stores its own slice. + delta_tile.store(o_chunk_delta, Dv); + o_chunk_mats += 3 * 256; + o_chunk_delta += C * Dv; + } + // Output path runs unconditionally: the forward serves both inference and + // the training save, so y and state_out are always needed. + SCALE_TRI_NAX(QKt_tile, gamma) out_tile = tmp_tile; MMA16x16x16(out_tile, 0, QKt_tile, false, 0, delta_tile, false, 0); @@ -507,6 +229,8 @@ template SCALE2_NAX(K_tile, gamma); MMA16x32x16(S_tile, kk / 16, delta_tile, true, 0, K_tile, false, 0); } + + chunk_idx++; }; int t = 0; @@ -524,4 +248,4 @@ template } S_tile.store(o_state, Dk); -} \ No newline at end of file +} diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax_vjp.h b/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax_vjp.h new file mode 100644 index 000000000..0e6ea0939 --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update_nax_vjp.h @@ -0,0 +1,1737 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include "gated_delta_nax_ops.h" + +#include +#include "atomic.h" + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +template +METAL_FUNC void reduce_tile_tg( + thread TileT& acc, + threadgroup float* scratch, + device mlx_atomic* out, + int row_stride, + int col_off, + short valid_rows, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(sg_id * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _s = 1; _s < kNSG; _s++) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(_s * 32 + simd_lane_id) * kE + _i]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Simdgroup 0 alone holds the total. + if (sg_id != 0) { + return; + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * row_stride + col_off + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(out, AT_NAX(acc, _i), idx); + } else { + mlx_atomic_store_explicit(out, AT_NAX(acc, _i), idx); + } + } + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_ckpt, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + device float* seg_states [[buffer(17)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + const int n_chunks = (T + C - 1) / C; + // Ceiling: the floor form gives 0 when n_chunks < Ckpt, which would leave the + // allocation empty and fault on the first read. + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + const short tail = short(T - (n_chunks - 1) * C); + + // Bases, indexed by chunk rather than walked. With two nested loops the + // incremental decrements are no longer expressible. + auto q_base = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_base = k + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dq_base = dq + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dk_base = dk + b_idx * T * Hk * Dk + hk_idx * Dk; + + auto v_base = v + b_idx * T * Hv * Dv + hv_idx * Dv; + auto dv_base = dv + b_idx * T * Hv * Dv + hv_idx * Dv; + auto co_base = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv; + + auto g_base = g + b_idx * T * Hv; + auto beta_base = beta + b_idx * T * Hv; + auto dg_base = dg + b_idx * T * Hv; + auto db_base = db + b_idx * T * Hv; + + auto cm_base = chunk_mats + n * n_chunks * 3 * 256; + auto cd_base = chunk_delta + n * n_chunks * C * Dv + dv_idx; + auto ck_base = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + // Each simdgroup owns a distinct dv slice, so these regions are disjoint and + // the replay needs no cross-simdgroup synchronisation. + auto seg_base = seg_states + (n * Ckpt * Dv + dv_idx) * Dk; + + // Per-chunk pointers, assigned from the bases before each process_chunk call. + auto q_ = q_base; + auto k_ = k_base; + auto dq_ = dq_base; + auto dk_ = dk_base; + auto v_ = v_base; + auto dv_ = dv_base; + auto co_ = co_base; + auto g_ = g_base; + auto beta_ = beta_base; + auto dg_ = dg_base; + auto db_ = db_base; + auto i_chunk_mats = cm_base; + auto i_chunk_delta = cd_base; + auto i_seg = seg_base; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, taken from the replayed segment. + _M16xDk S_tile; + + _M16x32 K_tile, Q_tile; + _M16x16 V_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // From the replayed segment rather than a per-chunk checkpoint. + S_tile.load(i_seg, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + if (fm < valid_rows) { + db_st[fm] = _b0; + } + if (fm1 < valid_rows) { + db_st[fm1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (fm == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (fm < valid_rows) { + dg_st[fm] = _d0; + } + if (fm1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (fm1 < valid_rows) { + dg_st[fm1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk segments in reverse. Each is replayed forward from its checkpoint to + // recover the entry states, then walked backwards. + // Backward over one segment: replay its entry states from the checkpoint, + // then walk it in reverse. HasTail is a compile-time tag so valid_rows is the + // constant C on every chunk of an interior segment, which folds away the + // row guards in the dq/dk stores and the load_rows switch in the replay. + auto process_segment = [&](const int seg, + auto tail_tag) __attribute__((always_inline)) { + constexpr bool HasTail = decltype(tail_tag)::value; + + const int seg_start = seg * Ckpt; + const int rem = n_chunks - seg_start; + const int n_in_seg = (rem < Ckpt) ? rem : Ckpt; + const int n_full = HasTail ? n_in_seg - 1 : n_in_seg; + + // delta is cached per chunk, so the replay is the state recurrence alone: + // S <- exp(gamma_C) S + K_dec^T delta + // No T^-1, no W, no U -- roughly a tenth of a full chunk's work, which is + // what makes trading Ckpt-fold memory for it worthwhile. + // + // Scoped so S is dead before process_chunk runs: it is a _M16xDk, and + // having it live alongside S_tile and dS_tile would put three of them in + // flight. + { + _M16xDk S; + S.load(ck_base + seg * Dv * Dk, Dk); + + auto replay_one = [&](const int j, + const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + S.store(seg_base + j * Dv * Dk, Dk); + + const int c = seg_start + j; + auto k_c = k_base + c * C * Hk * Dk; + auto g_c = g_base + c * C * Hv; + auto cd_c = cd_base + c * C * Dv; + + float gv = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max( + g_c[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + auto gs = simd_prefix_inclusive_sum(gv); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gs); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float g_last = gamma[C - 1]; + const float dec[2] = { + metal::fast::exp(g_last - gamma[fm]), + metal::fast::exp(g_last - gamma[fm1])}; + + _M16x16 delta_tile; + delta_tile.load(cd_c, Dv); + + S = S * metal::fast::exp(g_last); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 Kd; + if constexpr (B) { + Kd.load_rows(k_c + kk, Dk * Hk, valid_rows); + } else { + Kd.load(k_c + kk, Dk * Hk); + } + Kd = scale_rows(Kd, dec); + MMA16x32x16(S, kk / 16, delta_tile, true, 0, Kd, false, 0); + } + }; + + for (int j = 0; j < n_full; j++) { + replay_one(j, C, metal::false_type{}); + } + if constexpr (HasTail) { + replay_one(n_in_seg - 1, tail, metal::true_type{}); + } + } + + auto set_chunk_ptrs = [&](const int j) __attribute__((always_inline)) { + const int c = seg_start + j; + q_ = q_base + c * C * Hk * Dk; + k_ = k_base + c * C * Hk * Dk; + dq_ = dq_base + c * C * Hk * Dk; + dk_ = dk_base + c * C * Hk * Dk; + v_ = v_base + c * C * Hv * Dv; + dv_ = dv_base + c * C * Hv * Dv; + co_ = co_base + c * C * Hv * Dv; + g_ = g_base + c * C * Hv; + beta_ = beta_base + c * C * Hv; + dg_ = dg_base + c * C * Hv; + db_ = db_base + c * C * Hv; + i_chunk_mats = cm_base + c * 3 * 256; + i_chunk_delta = cd_base + c * C * Dv; + i_seg = seg_base + j * Dv * Dk; + }; + + if constexpr (HasTail) { + set_chunk_ptrs(n_in_seg - 1); + process_chunk(tail, metal::true_type{}); + } + for (int j = n_full - 1; j >= 0; --j) { + set_chunk_ptrs(j); + process_chunk(C, metal::false_type{}); + } + }; + + // Only the last segment can hold a short chunk + int seg = n_ckpt - 1; + if (tail != C) { + process_segment(seg, metal::true_type{}); + --seg; + } + for (; seg >= 0; --seg) { + process_segment(seg, metal::false_type{}); + } + + dS_tile.store(o_dh, Dk); +} + +template +[[kernel]] void gated_delta_vjp_fused_nax1( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; // KdKb_tmp folded away + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_r0 < valid_rows) { + db_st[_r0] = _b0; + } + if (_r1 < valid_rows) { + db_st[_r1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (_r0 == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (_r0 < valid_rows) { + dg_st[_r0] = _d0; + } + if (_r1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (_r1 < valid_rows) { + dg_st[_r1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +template +METAL_FUNC void reduce_tile_tg0( + thread TileT& acc, + threadgroup float* scratch, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short lo = kNSG / 2; lo > 0; lo >>= 1) { + if (sg_id >= lo && sg_id < 2 * lo) { + const short dst = sg_id - lo; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(dst * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id < lo) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(sg_id * 32 + simd_lane_id) * kE + _i]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax0( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 2) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 NI_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(NI_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(NI_tile, _i) = (_c.x == _c.y) ? -1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw; + MUL_NAX(QKt_tile, QKt_tile, tri_decay); + + TUinv_tile = TWinv_tile; + MUL_NAX(TUinv_tile, TUinv_tile, tri_decay); + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + MUL_NAX(dODT, dODT, tri_decay); + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + SCALE2_P(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + _M16x32 Kb_tile; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + + SCALE_BETA_NAX_O(Kb_tile, K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg(dq_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dq_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + const short _fn = _c.x + _f * 16; + const short _fm = _c.y; + if (_fm < valid_rows) { + const int idx = _fm * Hk * Dk + kk + _fn; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } else { + // Dv reduction done in threadgroup memory: single writer. + mlx_atomic_store_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } + } + } + } + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + SCALE_BETA_NAX(dVb_tile, beta_fm); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dVb_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.y < valid_rows) { + dv_[_c.y * Hv * Dv + dv_idx + _c.x] = AT_NAX(dVb_tile, _i); + } + } + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + SCALE_BETA_NAX(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + MUL_NAX(dTU_tile, dTU_tile, tri_decay); // dTinv = dT_W + (dT_U * D). + + ADD_NAX(dTinv_tile, dTW_tile, dTU_tile); + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + SCALE_NAX(dA_tile, -1.0f); + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = dA_tile; + SCALE_TRIEQ_NAX1(G_tile, beta_fm); + _M16x16 GGt_tile; + GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile; + _M16x16 R_tile; + + MUL_NAX(P_tile, QKt_raw, dODT); + MUL_NAX(R_tile, TWinv_tile, dTU_tile); + ADD_NAX(dgam_pair, P_tile, R_tile); + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, dKb_tile, t1, KdKb_tmp; + _M16x32 QgdOS, TbK, KdKC_blk; + + load_seq(Q_tile, q_ + kk, Hk * Dk); // [16 x 32] + load_seq(K_tile, k_ + kk, Dk * Hk); // [16 x 32] + + // gamma: + rowsum(Q * gamma*(dO @ S)) + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(QgdOS, row_exp); + MULA_NAX(dgam_row32, QgdOS, Q_tile); + + // dODT.T @ Q and (G + G.T) @ K + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + // B (T.T @ dW_raw), dW_raw = -gamma * (ddelta @ S) + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + + // dbeta term uses dK_b before the beta scaling, with raw K + MUL_NAX(KdKb_tmp, dKb_tile, K_tile); + ADD_NAX(KdKb, KdKb, KdKb_tmp); + + SCALE_BETA_NAX(dKb_tile, beta_fm); + ADD_NAX(dk_acc, dk_acc, dKb_tile); + + // D_C * (delta @ dS) + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + SCALE2_P(t1, dec_exp); + ADD_NAX(dk_acc, dk_acc, t1); + + // gamma stuff + MUL_NAX(KdKC_blk, K_tile, t1); + SUB_NAX(dgam_row32, dgam_row32, KdKC_blk); + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC_blk)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC_blk, _i); + } + + // gamma stuff: gamma_C * sum(S * dS) + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16)[_i] * + dS_tile.frag_at(0, kk / 16)[_i]; + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]; + } + + // gamma stuff + SCALE_BETA_NAX(K_tile, beta_fm); + SCALE_NAX(dW_raw, -1.0f); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + MULS_NAX(dgam_row32, TbK, dW_raw); + + // dk reduces over Dv the same way dq does. + reduce_tile_tg(dk_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dk_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * Hk * Dk + kk + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } else { + mlx_atomic_store_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } + } + } + } + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + _M16x16 VdVb; + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + MUL_NAX(VdVb, V_tile, TUddelta); + + _M16x16 AKKt; + TRIL_NAX(AKKt, dA_tile); + MUL_NAX(AKKt, AKKt, KKt_tile); + + ADD_NAX(VdVb, VdVb, AKKt); + ROWSUM1_NAX(dbeta_acc, VdVb); + ROWSUM1_NAX(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _r = 0; _r < 2; _r++) { + float _b = dbeta_acc[_r]; + _b += simd_shuffle_xor(_b, ushort(1)); + _b += simd_shuffle_xor(_b, ushort(8)); + + const short _row = fm + _r * mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_row < valid_rows) { + db_st[_row] = _b; + } + } + } + + // Fold the two fragments: only the row sum of dgam_row is used downstream, + // and row sums are additive across fragments. + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + AT_NAX(dgam_row, _i) = AT_NAX(dgam_row32, _i) + + AT_NAX(dgam_row32, mlx::steel::BaseNAXFrag::kElemsPerFrag + _i); + } + + // reduce and store dgamma: rowsum(row + pair) - colsum(pair) + ADD_NAX(dgam_row, dgam_row, dgam_pair); + _M16x16 dgam_tile, cs_tile; + MM16x16x16(dgam_tile, 0, dgam_row, false, 0, Ones_tile, false, 0); + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + SUB_NAX(dgam_tile, dgam_tile, cs_tile); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dgam_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.x == 0) { + dg_st[_c.y] = AT_NAX(dgam_tile, _i); + } + } + // The gamma_{C-1}-only term lands on the same slot the loop just wrote, + // so the lanes must be ordered before lane 0 accumulates into it. + simdgroup_barrier(mem_flags::mem_threadgroup); + const float dgam_last_red = simd_sum(dgam_last); + if (simd_lane_id == 0 && valid_rows > 0) { + dg_st[valid_rows - 1] += dgam_last_red; + } + } + + // One barrier serves both stages; simdgroup 0 commits. + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + SCALE_ROW_P(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + SCALE_BETA_NAX(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + NSCALE_ROW_P(W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +// Postprocessing dg. Similar idea to what is done in the triton kernel. +// The kernel computes the gradient with respect to the log. +template +[[kernel]] void gated_delta_dgamma_to_dg( + const device InT* g [[buffer(0)]], + device float* dg [[buffer(1)]], // in: dL/dgamma, out: dL/dg + constant int& T [[buffer(2)]], + constant int& Hv [[buffer(3)]], + constant int& n_total [[buffer(4)]], // B * Hv + uint2 pos [[thread_position_in_grid]]) { + const int n = int(pos.x); // b * Hv + hv + const int c = int(pos.y); // chunk index + + if (n >= n_total) { + return; + } + + const int t0 = c * C; + if (t0 >= T) { + return; + } + const int len = min(C, T - t0); + + const int b_idx = n / Hv; + const int hv_idx = n % Hv; + const int base = b_idx * T * Hv + hv_idx; + + float acc = 0.0f; + for (int j = len - 1; j >= 0; --j) { + const int idx = base + (t0 + j) * Hv; + acc += static_cast(dg[idx]); + float gv = metal::max(static_cast(g[idx]), 1e-6f); + dg[idx] = acc / gv; + } +} diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.h b/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.h new file mode 100644 index 000000000..86082c272 --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.h @@ -0,0 +1,184 @@ +// Copyright © 2024 Apple Inc. +#pragma once + +#include +#include + +#include "atomic.h" +#include "utils.h" + +using namespace metal; + +template +[[kernel]] void gated_delta_vjp_seq( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* b [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B*Hv, n_ckpt, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device mlx_atomic* dg [[buffer(12)]], + device mlx_atomic* db [[buffer(13)]], + device float* dh [[buffer(14)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + constexpr int n_per_t = Dk / 32; + + auto dk_idx = thread_position_in_threadgroup.x; + auto dv_idx = thread_position_in_grid.y; + + const int qk_stride = Hk * Dk; + const int v_stride = Hv * Dv; + const int g_stride = Hv; + + auto q_base = q + b_idx * T * qk_stride + hk_idx * Dk; + auto k_base = k + b_idx * T * qk_stride + hk_idx * Dk; + auto dq_base = dq + b_idx * T * qk_stride + hk_idx * Dk; + auto dk_base = dk + b_idx * T * qk_stride + hk_idx * Dk; + + auto v_base = v + b_idx * T * v_stride + hv_idx * Dv; + auto dv_base = dv + b_idx * T * v_stride + hv_idx * Dv; + auto co_base = cot_o + b_idx * T * v_stride + hv_idx * Dv; + + auto g_base = g + b_idx * T * g_stride + hv_idx; + auto b_base = b + b_idx * T * g_stride + hv_idx; + auto dg_base = dg + b_idx * T * g_stride + hv_idx; + auto db_base = db + b_idx * T * g_stride + hv_idx; + + const int n_ckpt = (T + Ckpt - 1) / Ckpt; + + float s_hat[n_per_t]; + auto base_state = cot_h + (n * Dv + dv_idx) * Dk; + for (int i = 0; i < n_per_t; i++) { + s_hat[i] = base_state[n_per_t * dk_idx + i]; + } + + // Only this thread's n_per_t slice of the state is ever needed, so a whole + // segment of entry states costs Ckpt * n_per_t registers and the replay needs + // no device buffer. + float seg[Ckpt][n_per_t]; + float s_prev[n_per_t]; + float s_dec[n_per_t]; + + for (int seg_idx = n_ckpt - 1; seg_idx >= 0; --seg_idx) { + const int t0 = seg_idx * Ckpt; + const int seg_len = metal::min(Ckpt, T - t0); + + // Replay forward from the checkpoint, recording the entry state of each + // step in the segment. + auto c_state = + state_cache + n * n_ckpt * Dv * Dk + seg_idx * Dv * Dk + dv_idx * Dk; + + float s[n_per_t]; + for (int i = 0; i < n_per_t; ++i) { + s[i] = c_state[n_per_t * dk_idx + i]; + } + + for (int j = 0; j < seg_len; ++j) { + const int t = t0 + j; + + for (int i = 0; i < n_per_t; ++i) { + seg[j][i] = s[i]; + } + + float gamma = static_cast(g_base[t * g_stride]); + float beta = static_cast(b_base[t * g_stride]); + + auto k_t = k_base + t * qk_stride; + + float kv_mem = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + const int s_idx = n_per_t * dk_idx + i; + s[i] *= gamma; + kv_mem += s[i] * static_cast(k_t[s_idx]); + } + kv_mem = simd_sum(kv_mem); + + float delta = + beta * (static_cast(v_base[t * v_stride + dv_idx]) - kv_mem); + + for (int i = 0; i < n_per_t; ++i) { + s[i] += delta * static_cast(k_t[n_per_t * dk_idx + i]); + } + } + + // Backward over the same steps, newest first. + for (int j = seg_len - 1; j >= 0; --j) { + const int t = t0 + j; + + float gamma = static_cast(g_base[t * g_stride]); + float beta = static_cast(b_base[t * g_stride]); + + auto q_t = q_base + t * qk_stride; + auto k_t = k_base + t * qk_stride; + auto dq_t = dq_base + t * qk_stride; + auto dk_t = dk_base + t * qk_stride; + + float kv_mem = 0.0f; + float co = static_cast(co_base[t * v_stride + dv_idx]); + float w = 0.0f; + for (int i = 0; i < n_per_t; i++) { + const int s_idx = n_per_t * dk_idx + i; + s_prev[i] = seg[j][i]; + s_dec[i] = s_prev[i] * gamma; + kv_mem += s_dec[i] * static_cast(k_t[s_idx]); + + s_hat[i] += co * static_cast(q_t[s_idx]); + + w += s_hat[i] * static_cast(k_t[s_idx]); + } + kv_mem = simd_sum(kv_mem); + w = simd_sum(w); + + if (thread_index_in_simdgroup == 0) { + dv_base[t * v_stride + dv_idx] = beta * w; + } + + float u = static_cast(v_base[t * v_stride + dv_idx]) - kv_mem; + float delta = beta * u; + + if (thread_index_in_simdgroup == 0) { + mlx_atomic_fetch_add_explicit(db_base + t * g_stride, w * u, 0); + } + + float dgamma = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + + float s_t = s_dec[i] + delta * static_cast(k_t[s_idx]); + mlx_atomic_fetch_add_explicit(dq_t, co * s_t, s_idx); + + float contrib = beta * (u * s_hat[i] - w * s_dec[i]); + mlx_atomic_fetch_add_explicit(dk_t, contrib, s_idx); + + s_hat[i] -= beta * w * static_cast(k_t[s_idx]); + + dgamma += s_hat[i] * s_prev[i]; + } + dgamma = simd_sum(dgamma); + if (thread_index_in_simdgroup == 0) { + mlx_atomic_fetch_add_explicit(dg_base + t * g_stride, dgamma, 0); + } + + for (int i = 0; i < n_per_t; ++i) { + s_hat[i] *= gamma; + } + } + } + + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + dh[(n * Dv + dv_idx) * Dk + s_idx] = s_hat[i]; + } +} diff --git a/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.metal b/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.metal new file mode 100644 index 000000000..172cef32a --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/gated_delta_update_vjp.metal @@ -0,0 +1,35 @@ +#include "gated_delta_update_vjp.h" +#include "gated_delta_update.h" +#include "utils.h" + +using namespace metal; + +#define instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, ckpt) \ + instantiate_kernel( \ + "seq_gated_delta_vjp_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv \ + "_" #ckpt, \ + gated_delta_vjp_seq, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + ckpt) + +#define instantiate_gated_delta_vjp_dims(in_type, dk, dv, hk, hv) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 1) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 4) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 8) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 16) + +#define instantiate_gated_delta_vjp(in_type) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 24, 24) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 32, 32) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 32) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 48) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 16) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 64) + +instantiate_gated_delta_vjp(float); +instantiate_gated_delta_vjp(bfloat16_t); +instantiate_gated_delta_vjp(float16_t); \ No newline at end of file diff --git a/Source/Cmlx/mlx-generated/metal/gemv_masked.h b/Source/Cmlx/mlx-generated/metal/gemv_masked.h index 30371eb06..930ba3b94 100644 --- a/Source/Cmlx/mlx-generated/metal/gemv_masked.h +++ b/Source/Cmlx/mlx-generated/metal/gemv_masked.h @@ -452,7 +452,7 @@ struct GEMVTKernel { const int n_block_idx = blockM > blockN ? out_col / blockM : int(tid.x); const int out_mask_offset = - !has_output_mask ? 0 : n_block_idx; // * out_mask_strides[0]; + !has_output_mask ? 0 : n_block_idx * out_mask_strides[0]; int mat_mask_offset = !has_operand_mask ? 0 : n_block_idx * mat_mask_strides[0]; diff --git a/Source/Cmlx/mlx-generated/metal/indexing/masked_scatter.h b/Source/Cmlx/mlx-generated/metal/indexing/masked_scatter.h index 2ba547400..fe2e2b2fe 100644 --- a/Source/Cmlx/mlx-generated/metal/indexing/masked_scatter.h +++ b/Source/Cmlx/mlx-generated/metal/indexing/masked_scatter.h @@ -32,7 +32,7 @@ template if (src_contiguous) { out[idx] = src[batch_idx * src_batch_size + src_index]; } else { - out[idx] = src[elem_to_loc( + out[idx] = src[elem_to_loc( batch_idx * src_batch_size + src_index, src_shapes, src_strides, diff --git a/Source/Cmlx/mlx-generated/metal/indexing/scatter.h b/Source/Cmlx/mlx-generated/metal/indexing/scatter.h index 3a97de9bb..e361e7414 100644 --- a/Source/Cmlx/mlx-generated/metal/indexing/scatter.h +++ b/Source/Cmlx/mlx-generated/metal/indexing/scatter.h @@ -38,8 +38,8 @@ METAL_FUNC void scatter_impl( for (int j = 0; j < NWORK && ind_idx < idx_size; ++j, ind_idx++) { LocT out_idx = out_offset; for (int i = 0; i < NIDX; ++i) { - auto idx_loc = indices.row_contiguous[i] - ? ind_idx + LocT idx_loc = indices.row_contiguous[i] + ? LocT(ind_idx) : elem_to_loc( ind_idx, &indices.shapes[indices.ndim * i], @@ -50,7 +50,7 @@ METAL_FUNC void scatter_impl( out_idx += static_cast(idx_val) * static_cast(out_strides[ax]); } - auto upd_idx = ind_idx * static_cast(upd_size) + gid.x; + LocT upd_idx = ind_idx * static_cast(upd_size) + gid.x; if constexpr (!UPD_ROW_CONTIG) { upd_idx = elem_to_loc(upd_idx, upd_shape, upd_strides, upd_ndim); } diff --git a/Source/Cmlx/mlx-generated/metal/quantized.h b/Source/Cmlx/mlx-generated/metal/quantized.h index be1ebff59..48fe55cd9 100644 --- a/Source/Cmlx/mlx-generated/metal/quantized.h +++ b/Source/Cmlx/mlx-generated/metal/quantized.h @@ -28,15 +28,30 @@ inline constexpr short get_bytes_per_pack() { template inline U load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -46,8 +61,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 3) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; x_thread[i + 2] = x[i + 2] / 64.0f; @@ -61,7 +76,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 4) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -71,8 +86,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 5) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -86,7 +101,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 6) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -107,15 +122,30 @@ inline U load_vector(const device T* x, thread U* x_thread) { template inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -125,8 +155,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 3) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; @@ -141,7 +171,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 4) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -151,8 +181,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 5) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -166,7 +196,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 6) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -196,13 +226,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -298,13 +342,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -395,11 +453,25 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + result[8 * i] += x * (select(U(0), scale, bool(wb & 0x01)) + bias); + result[8 * i + 1] += x * (select(U(0), scale, bool(wb & 0x02)) + bias); + result[8 * i + 2] += x * (select(U(0), scale, bool(wb & 0x04)) + bias); + result[8 * i + 3] += x * (select(U(0), scale, bool(wb & 0x08)) + bias); + result[8 * i + 4] += x * (select(U(0), scale, bool(wb & 0x10)) + bias); + result[8 * i + 5] += x * (select(U(0), scale, bool(wb & 0x20)) + bias); + result[8 * i + 6] += x * (select(U(0), scale, bool(wb & 0x40)) + bias); + result[8 * i + 7] += x * (select(U(0), scale, bool(wb & 0x80)) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -485,14 +557,36 @@ qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { template inline void dequantize(const device uint8_t* w, U scale, U bias, W w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -585,9 +679,9 @@ struct QuantizedBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -753,7 +847,7 @@ METAL_FUNC void qmv_quad_impl( } } -template +template METAL_FUNC void qmv_fast_impl( const device uint32_t* w, const device T* scales, @@ -765,7 +859,8 @@ METAL_FUNC void qmv_fast_impl( uint3 tid [[threadgroup_position_in_grid]], uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { - constexpr int packs_per_thread = bits == 2 ? 1 : 2; + constexpr int packs_per_thread = + bits <= 2 ? 1 : 2; // 1-bit: 1 pack (vpt=32) for occupancy constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int pack_factor = get_pack_factor(); @@ -787,19 +882,37 @@ METAL_FUNC void qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // With partial rows the output size need not be a multiple of 8. Rows of the + // last SIMD-group that fall past the output reuse the weights of the last + // valid output row, so the reduction loop needs no per-row bounds check, and + // are not stored. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; y += tid.x * out_vec_size + out_row; - for (int k = 0; k < in_vec_size; k += block_size) { + const int aligned_end = (in_vec_size / block_size) * block_size; + + for (int k = 0; k < aligned_end; k += block_size) { U sum = load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device T* sl = scales + row * in_vec_size_g; - const device T* bl = biases + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; U s = sl[0]; U b = bl[0]; @@ -812,9 +925,37 @@ METAL_FUNC void qmv_fast_impl( x += block_size; } + // Tail block: handles K that is a multiple of 512 (dispatch gate) but not + // of block_size. Only 1-bit has block_size > 512 (it uses 2048), so for + // >=2-bit this is a no-op. Out-of-bounds lanes skip the qdot call entirely; + // their result[row] stays at 0 and contributes 0 to the simd_sum below. + if (aligned_end < in_vec_size) { + bool in_bounds = + (aligned_end + static_cast(simd_lid) * values_per_thread) < + in_vec_size; + if (in_bounds) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + } + } + for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { y[row] = static_cast(result[row]); } } @@ -1193,6 +1334,7 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, const int BM = 32, const int BK = 32, const int BN = 32> @@ -1201,7 +1343,7 @@ METAL_FUNC void qmm_t_impl( const device T* scales, const device T* biases, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, threadgroup T* Ws, const constant int& K, @@ -1226,7 +1368,7 @@ METAL_FUNC void qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; using loader_w_t = QuantizedBlockLoader< @@ -1602,6 +1744,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv_fast( @@ -1642,7 +1785,7 @@ template < b_strides, tid); } - qmv_fast_impl( + qmv_fast_impl( w, scales, biases, @@ -1660,6 +1803,7 @@ template < int group_size, const int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv( @@ -1946,7 +2090,7 @@ template < b_strides, tid); } - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -1977,7 +2121,7 @@ template < const device T* scales [[buffer(1)]], const device T* biases [[buffer(2)]], const device T* x [[buffer(3)]], - device T* y [[buffer(4)]], + device float* y [[buffer(4)]], const constant int& K [[buffer(5)]], const constant int& N [[buffer(6)]], const constant int& M [[buffer(7)]], @@ -2005,7 +2149,7 @@ template < biases += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - qmm_t_impl( + qmm_t_impl( (const device uint32_t*)wl, scales, biases, @@ -2336,7 +2480,7 @@ template < s_strides, b_strides, tid); - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -2617,14 +2761,23 @@ template w_min = simd_min(w_min); w_max = simd_max(w_max); - float scale = max((w_max - w_min) / n_bins, eps); - bool side = abs(w_min) > abs(w_max); - scale = side ? scale : -scale; - float edge = side ? w_min : w_max; - float q0 = round(edge / scale); - bool at_zero = q0 == 0.0f; - scale = at_zero ? scale : edge / q0; - float bias = at_zero ? 0 : edge; + float scale; + float bias; + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scale = max(w_max - w_min, eps); + bias = w_min; + } else { + scale = max((w_max - w_min) / n_bins, eps); + bool side = abs(w_min) > abs(w_max); + scale = side ? scale : -scale; + float edge = side ? w_min : w_max; + float q0 = round(edge / scale); + bool at_zero = q0 == 0.0f; + scale = at_zero ? scale : edge / q0; + bias = at_zero ? 0 : edge; + } // Write out the scales and biases size_t gindex = in_index / group_size; @@ -2728,7 +2881,9 @@ template #pragma clang loop unroll(full) for (int i = 0; i < pack_factor; i++) { uint8_t d; - if (bits == 2) { + if (bits == 1) { + d = (val >> i) & 0x01; + } else if (bits == 2) { d = (val >> (bits * i)) & 0x03; } else if (bits == 4) { d = (val >> (bits * i)) & 0x0f; diff --git a/Source/Cmlx/mlx-generated/metal/quantized_nax.h b/Source/Cmlx/mlx-generated/metal/quantized_nax.h index a34774992..95f26868f 100644 --- a/Source/Cmlx/mlx-generated/metal/quantized_nax.h +++ b/Source/Cmlx/mlx-generated/metal/quantized_nax.h @@ -31,15 +31,30 @@ inline constexpr short get_bytes_per_pack() { template inline U load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -49,8 +64,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 3) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; x_thread[i + 2] = x[i + 2] / 64.0f; @@ -64,7 +79,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 4) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -74,8 +89,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 5) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -89,7 +104,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 6) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -110,15 +125,30 @@ inline U load_vector(const device T* x, thread U* x_thread) { template inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -128,8 +158,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 3) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; @@ -144,7 +174,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 4) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -154,8 +184,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 5) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -169,7 +199,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 6) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -199,13 +229,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -301,13 +345,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -398,11 +456,33 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + U s[8] = { + scale, + scale / 2.0f, + scale / 4.0f, + scale / 8.0f, + scale / 16.0f, + scale / 32.0f, + scale / 64.0f, + scale / 128.0f}; + for (int i = 0; i < (values_per_thread / 8); i++) { + result[8 * i] += x * (s[0] * (w[i] & 0x01) + bias); + result[8 * i + 1] += x * (s[1] * (w[i] & 0x02) + bias); + result[8 * i + 2] += x * (s[2] * (w[i] & 0x04) + bias); + result[8 * i + 3] += x * (s[3] * (w[i] & 0x08) + bias); + result[8 * i + 4] += x * (s[4] * (w[i] & 0x10) + bias); + result[8 * i + 5] += x * (s[5] * (w[i] & 0x20) + bias); + result[8 * i + 6] += x * (s[6] * (w[i] & 0x40) + bias); + result[8 * i + 7] += x * (s[7] * (w[i] & 0x80) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -487,14 +567,36 @@ template inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -587,9 +689,9 @@ struct QuantizedBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -715,9 +817,9 @@ struct QuantizedBlockLoader< BCOLS % group_size == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); diff --git a/Source/Cmlx/mlx-generated/metal/reduction/reduce_col.h b/Source/Cmlx/mlx-generated/metal/reduction/reduce_col.h index b1546adb5..fce36a4cd 100644 --- a/Source/Cmlx/mlx-generated/metal/reduction/reduce_col.h +++ b/Source/Cmlx/mlx-generated/metal/reduction/reduce_col.h @@ -117,7 +117,7 @@ template IdxT out_idx = gid.x + gsize.x * IdxT(gid.y); IdxT in_idx = elem_to_loc(out_idx, shape, strides, ndim); - in += in_idx + lid.x; + in += in_idx + IdxT(lid.x); U total = Op::init; IdxT total_rows = IdxT(non_col_reductions) * IdxT(reduction_size); @@ -172,6 +172,7 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], + const constant int64_t& column_offset [[buffer(11)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -193,7 +194,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT out_idx = gid.y + gsize.y * IdxT(gid.z); @@ -243,7 +244,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += out_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { @@ -311,7 +312,8 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], - const constant size_t& out_size [[buffer(11)]], + const constant int64_t& column_offset [[buffer(11)]], + const constant size_t& out_size [[buffer(12)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -336,7 +338,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT full_idx = gid.y + gsize.y * IdxT(gid.z); @@ -383,7 +385,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += full_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { diff --git a/Source/Cmlx/mlx-generated/metal/reduction/reduce_init.h b/Source/Cmlx/mlx-generated/metal/reduction/reduce_init.h index 604efa785..9a1e363e1 100644 --- a/Source/Cmlx/mlx-generated/metal/reduction/reduce_init.h +++ b/Source/Cmlx/mlx-generated/metal/reduction/reduce_init.h @@ -3,6 +3,7 @@ template [[kernel]] void init_reduce( device T* out [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = Op::init; + uint2 index [[thread_position_in_grid]], + uint2 grid_dim [[threads_per_grid]]) { + out[index.x + grid_dim.x * int64_t(index.y)] = Op::init; } diff --git a/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention.metal b/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention.metal index 6797bdf3e..a27ad455b 100644 --- a/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention.metal +++ b/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention.metal @@ -2,10 +2,28 @@ // clang-format off #include "utils.h" +#include "sdpa_blocked.h" #include "sdpa_vector.h" using namespace metal; +instantiate_kernel( + "sdpa_blocked_scale_copy_bfloat16", + sdpa_blocked_scale_copy, + bfloat16_t) +instantiate_kernel( + "sdpa_blocked_scale_copy_float16", + sdpa_blocked_scale_copy, + float16_t) +instantiate_kernel( + "sdpa_blocked_causal_mask_bfloat16", + sdpa_blocked_causal_mask, + bfloat16_t) +instantiate_kernel( + "sdpa_blocked_causal_mask_float16", + sdpa_blocked_causal_mask, + float16_t) + // SDPA vector instantiations #define instantiate_sdpa_vector_aggregation(type, value_dim) \ instantiate_kernel( \ @@ -61,4 +79,17 @@ using namespace metal; instantiate_sdpa_vector_heads(float) instantiate_sdpa_vector_heads(bfloat16_t) instantiate_sdpa_vector_heads(float16_t) - // clang-format on + +#define instantiate_sdpa_vector_tk1(type, dim) \ + instantiate_kernel( \ + "sdpa_vector_2pass_1_" #type "_" #dim "_" #dim "_tk1", \ + sdpa_vector_2pass_1, \ + type, \ + dim, \ + dim, \ + 1) + +instantiate_sdpa_vector_tk1(bfloat16_t, 256) +instantiate_sdpa_vector_tk1(float, 192) +instantiate_sdpa_vector_tk1(float, 256) +// clang-format on diff --git a/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention_vjp.metal b/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention_vjp.metal new file mode 100644 index 000000000..b96809e52 --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/scaled_dot_product_attention_vjp.metal @@ -0,0 +1,154 @@ +// Copyright © 2026 Apple Inc. + +#include "utils.h" + +using namespace metal; + +template +[[kernel]] void sdpa_vjp_odo( + const device InT* o [[buffer(0)]], // [B, H, qL, Dv] + const device InT* cot_o [[buffer(1)]], // [B, H, qL, Dv] + device float* odo [[buffer(2)]], // [B, H, qL] + constant int& qL [[buffer(3)]], + uint3 tpg [[thread_position_in_grid]], + uint simd_lane_id [[thread_index_in_simdgroup]]) { + const uint bh = tpg.z; + const int i = int(tpg.y); + + if (i >= qL) { + return; + } + + const size_t row = (size_t)bh * qL + i; + auto o_i = o + row * Dv; + auto co_i = cot_o + row * Dv; + + float acc = 0.0f; + for (int d = int(simd_lane_id); d < Dv; d += 32) { + acc += float(o_i[d]) * float(co_i[d]); + } + acc = simd_sum(acc); + + if (simd_lane_id == 0) { + odo[row] = acc; + } +} + +struct SDPAVJPTileParams { + int bq; + int bk; + int qL; + int i0; + int j0; + float scale; + int diag_off; + int causal; +}; + +template +[[kernel]] void sdpa_vjp_ds( + const device T* S [[buffer(0)]], // [BH, bq, bk] + const device T* dP [[buffer(1)]], // [BH, bq, bk] + const device float* lse [[buffer(2)]], // [B, H, qL] + const device float* odo [[buffer(3)]], // [B, H, qL] + device T* dS [[buffer(4)]], // [BH, bq, bk] + device T* P [[buffer(5)]], // [BH, bk, bq] + const constant SDPAVJPTileParams& p [[buffer(6)]], + uint3 gid [[thread_position_in_grid]]) { + int col = int(gid.x); + int row = int(gid.y); + int bh = int(gid.z); + if (row >= p.bq || col >= p.bk) { + return; + } + + size_t sbase = (size_t(bh) * size_t(p.bq) + size_t(row)) * size_t(p.bk); + size_t qi = size_t(bh) * size_t(p.qL) + size_t(p.i0 + row); + + float l = lse[qi]; + float dlt = odo[qi]; + // Fully masked rows carry lse == -inf; exp(-inf - -inf) would be NaN. + bool dead = (l < 0.0f) && metal::isinf(l); + int lim = p.i0 + row + p.diag_off; + + float pv; + if (dead || (p.causal != 0 && (p.j0 + col) > lim)) { + pv = 0.0f; + } else { + pv = metal::fast::exp(static_cast(S[sbase + col]) * p.scale - l); + } + float dsv = pv * (static_cast(dP[sbase + col]) - dlt) * p.scale; + + dS[sbase + col] = static_cast(dsv); + P[sbase + col] = static_cast(pv); +} + +template +[[kernel]] void sdpa_vjp_reduce( + const device T* src [[buffer(0)]], + device float* acc [[buffer(1)]], + device T* out [[buffer(2)]], + const constant int& rows [[buffer(3)]], + const constant int& dim [[buffer(4)]], + const constant int& group [[buffer(5)]], + const constant int& acc_rows [[buffer(6)]], + const constant int& row_off [[buffer(7)]], + uint3 gid [[thread_position_in_grid]]) { + int c = int(gid.x); + int row = int(gid.y); + int bh = int(gid.z); + if (c >= dim || row >= rows) { + return; + } + + size_t sbase = size_t(bh) * size_t(group) * size_t(rows) * size_t(dim); + float sum = 0.0f; + for (int g = 0; g < group; ++g) { + size_t si = sbase + + (size_t(g) * size_t(rows) + size_t(row)) * size_t(dim) + size_t(c); + sum += static_cast(src[si]); + } + + size_t ai = + (size_t(bh) * size_t(acc_rows) + size_t(row_off + row)) * size_t(dim) + + size_t(c); + float total = Accum ? acc[ai] + sum : sum; + acc[ai] = total; + out[ai] = static_cast(total); +} + +// Instantiations +#define instantiate_odo(in_type, dv) \ + instantiate_kernel( \ + "sdpa_vjp_odo_" #in_type "_" #dv, sdpa_vjp_odo, in_type, dv) + +#define instantiate_odo_shapes(in_type) \ + instantiate_odo(in_type, 64); \ + instantiate_odo(in_type, 72); \ + instantiate_odo(in_type, 80); \ + instantiate_odo(in_type, 96); \ + instantiate_odo(in_type, 128); \ + instantiate_odo(in_type, 192); \ + instantiate_odo(in_type, 256); \ + instantiate_odo(in_type, 512); \ + +instantiate_odo_shapes(bfloat16_t); +instantiate_odo_shapes(float16_t); +instantiate_odo_shapes(float); + +#define instantiate_sdpa_vjp_ds(tname, type) \ + instantiate_kernel("sdpa_vjp_ds_" #tname, sdpa_vjp_ds, type) + +instantiate_sdpa_vjp_ds(float, float); +instantiate_sdpa_vjp_ds(float16_t, float16_t); +instantiate_sdpa_vjp_ds(bfloat16_t, bfloat16_t); + +#define instantiate_sdpa_vjp_reduce(tname, type) \ + instantiate_kernel( \ + "sdpa_vjp_reduce_add_" #tname, sdpa_vjp_reduce, type, true) \ + instantiate_kernel( \ + "sdpa_vjp_reduce_set_" #tname, sdpa_vjp_reduce, type, false) + +instantiate_sdpa_vjp_reduce(float, float); +instantiate_sdpa_vjp_reduce(float16_t, float16_t); +instantiate_sdpa_vjp_reduce(bfloat16_t, bfloat16_t); diff --git a/Source/Cmlx/mlx-generated/metal/sdpa_blocked.h b/Source/Cmlx/mlx-generated/metal/sdpa_blocked.h new file mode 100644 index 000000000..444d5e9ed --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/sdpa_blocked.h @@ -0,0 +1,45 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include + +#include "defines.h" + +using namespace metal; + +template +[[kernel]] void sdpa_blocked_scale_copy( + const device T* q [[buffer(0)]], + device T* q_block [[buffer(1)]], + constant float& scale [[buffer(2)]], + constant int64_t* q_strides [[buffer(3)]], + constant int& heads [[buffer(4)]], + constant int& rows [[buffer(5)]], + constant int& head_dim [[buffer(6)]], + constant int& q_offset [[buffer(7)]], + uint3 elem [[thread_position_in_grid]]) { + int d = elem.x; + int row = elem.y; + int head = elem.z % heads; + int batch = elem.z / heads; + int64_t q_index = int64_t(batch) * q_strides[0] + + int64_t(head) * q_strides[1] + int64_t(q_offset + row) * q_strides[2] + d; + size_t q_block_index = (size_t(elem.z) * rows + row) * head_dim + d; + q_block[q_block_index] = q[q_index] * static_cast(scale); +} + +template +[[kernel]] void sdpa_blocked_causal_mask( + device T* scores [[buffer(0)]], + constant int& tile_rows [[buffer(1)]], + constant int& columns [[buffer(2)]], + uint2 elem [[thread_position_in_grid]]) { + int column = elem.x; + int score_row = elem.y; + int row = score_row % tile_rows; + if (column > row) { + size_t index = size_t(score_row) * columns + columns - tile_rows + column; + scores[index] = Limits::finite_min; + } +} diff --git a/Source/Cmlx/mlx-generated/metal/sdpa_vector.h b/Source/Cmlx/mlx-generated/metal/sdpa_vector.h index 8d159a0db..1d312038c 100644 --- a/Source/Cmlx/mlx-generated/metal/sdpa_vector.h +++ b/Source/Cmlx/mlx-generated/metal/sdpa_vector.h @@ -61,6 +61,7 @@ template const int q_batch_head_idx = tid.x; const int q_seq_idx = tid.y; const int kv_head_idx = q_batch_head_idx / gqa_factor; + const int kv_seq_idx = simd_gid; const int o_offset = q_batch_head_idx * tpg.y + q_seq_idx; const int q_offset = query_transposed ? tpg.x * q_seq_idx + q_batch_head_idx : o_offset; @@ -71,11 +72,11 @@ template simd_lid * v_per_thread; if (bool_mask) { bmask += q_batch_head_idx * mask_head_stride + - simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + kv_seq_idx * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; } if (float_mask) { fmask += q_batch_head_idx * mask_head_stride + - simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + kv_seq_idx * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; } out += o_offset * V + simd_gid * v_per_thread; @@ -176,7 +177,7 @@ template } } -template +template [[kernel]] void sdpa_vector_2pass_1( const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], @@ -259,8 +260,73 @@ template sum_exp_score = 1; } + const int stride_k_tok = blocks * int(k_seq_stride); + const int stride_v_tok = blocks * int(v_seq_stride); + const int stride_mask_tok = + (bool_mask || float_mask) ? blocks * mask_kv_seq_stride : 0; + // For each key - for (int i = block_idx; i < N; i += blocks) { + int i = block_idx; + for (; i + (TK - 1) * blocks < N; i += blocks * TK) { + // Prefetch: issue all TK K/V loads first so the HW can overlap them. + T k_reg[TK][qk_per_thread]; + T v_reg[TK][v_per_thread]; + for (int t = 0; t < TK; t++) { + const device T* kp = keys + t * stride_k_tok; + for (int j = 0; j < qk_per_thread; j++) { + k_reg[t][j] = kp[j]; + } + } + for (int t = 0; t < TK; t++) { + const device T* vp = values + t * stride_v_tok; + for (int j = 0; j < v_per_thread; j++) { + v_reg[t][j] = vp[j]; + } + } + + for (int t = 0; t < TK; t++) { + int ii = i + t * blocks; + bool use_key = true; + if (do_causal) { + use_key = ii <= (N - q_seq_len + int(q_seq_idx)); + } else if (bool_mask) { + use_key = bmask[t * stride_mask_tok]; + } else if (float_mask) { + use_key = (fmask[t * stride_mask_tok] >= Limits::finite_min); + } + if (use_key) { + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(k_reg[t][j]); + } + score = simd_sum(score); + if (float_mask) { + score += static_cast(fmask[t * stride_mask_tok]); + } + + U new_max = max(max_score, score); + U factor = fast::exp(max_score - new_max); + U exp_score = fast::exp(score - new_max); + max_score = new_max; + sum_exp_score = sum_exp_score * factor + exp_score; + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * static_cast(v_reg[t][j]); + } + } + } + + keys += TK * stride_k_tok; + values += TK * stride_v_tok; + if (bool_mask) { + bmask += TK * stride_mask_tok; + } + if (float_mask) { + fmask += TK * stride_mask_tok; + } + } + + // Tail (fewer than TK remaining keys) + for (; i < N; i += blocks) { bool use_key = true; if (do_causal) { use_key = i <= (N - q_seq_len + int(q_seq_idx)); @@ -272,8 +338,8 @@ template if (use_key) { // Compute the i-th score U score = 0; - for (int i = 0; i < qk_per_thread; i++) { - score += q[i] * keys[i]; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * keys[j]; } score = simd_sum(score); @@ -290,19 +356,19 @@ template sum_exp_score = sum_exp_score * factor + exp_score; // Update the output accumulator - for (int i = 0; i < v_per_thread; i++) { - o[i] = o[i] * factor + exp_score * values[i]; + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * values[j]; } } // Move the pointers to the next kv - keys += blocks * int(k_seq_stride); - values += blocks * int(v_seq_stride); + keys += stride_k_tok; + values += stride_v_tok; if (bool_mask) { - bmask += blocks * mask_kv_seq_stride; + bmask += stride_mask_tok; } if (float_mask) { - fmask += blocks * mask_kv_seq_stride; + fmask += stride_mask_tok; } } diff --git a/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention.h b/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention.h index bc833474e..53a4017c3 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention.h +++ b/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention.h @@ -14,6 +14,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; struct MaxOp { template @@ -77,6 +78,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -103,6 +105,12 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -532,6 +540,20 @@ template < Otile.template row_bin_op(sum_score); threadgroup_barrier(mem_flags::mem_none); + // Store the logsumexp for the backward pass + if (save_lse && sn == 0) { + using stile_t = decltype(Stile); + const bool is_last_q = int(tid.x) == (params->NQ_aligned); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + sm + i * stile_t::kFragRows; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = M_LN2_F * (max_score[i] + metal::log2(sum_score[i])); + } + } + } + // Store results O += (tm + sm) * params->O_strides[2] + d_half * BVh + sn; @@ -545,4 +567,4 @@ template < } else { Otile.template store(O, params->O_strides[2]); } -} +} \ No newline at end of file diff --git a/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention_nax.h b/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention_nax.h index bf2f026ba..43dc2db87 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention_nax.h +++ b/Source/Cmlx/mlx-generated/metal/steel/attn/kernels/steel_attention_nax.h @@ -17,6 +17,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; template struct TransformScale { @@ -90,6 +91,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -117,6 +119,13 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + // [B, H, qL], contiguous. + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -475,6 +484,16 @@ template < Otile.template row_bin_op(rcp); + if (save_lse && sn == 0) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + i * otile_t::kFragRowsJump + sm; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = max_score[i] * M_LN2_F + metal::log(sum_score[i]); + } + } + } + // Store results O += tm * int(params->O_strides[2]); @@ -516,6 +535,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* LSE [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -903,6 +923,21 @@ template < rcp[i] = 1.f / sum_score[i]; } + if (save_lse && d_group == 0 && sn == 0) { + const int lse_row_base = int(tid.x) * BQ + tm; + const int lse_head_off = (int(tid.z) * params->H + int(tid.y)) * params->qL; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const int row = lse_row_base + i * stile_t::kFragRowsJump + sm; + if (row < params->qL) { + LSE[lse_head_off + row] = (sum_score[i] == 0) + ? -INFINITY + : float(M_LN2_F * (max_score[i] + metal::log2(sum_score[i]))); + } + } + } + Otile.template row_bin_op(rcp); if (!align_Q && is_last_q) { diff --git a/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv.h b/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv.h index f559596b7..f948ec069 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv.h +++ b/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv.h @@ -46,7 +46,7 @@ implicit_gemm_conv_2d( using loader_a_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DInputBlockLoaderSmallChannels< @@ -84,7 +84,7 @@ implicit_gemm_conv_2d( // Weight loader using loader_b_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DWeightBlockLoaderSmallChannels< diff --git a/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv_general.h b/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv_general.h index d0797ebea..de623ee4b 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv_general.h +++ b/Source/Cmlx/mlx-generated/metal/steel/conv/kernels/steel_conv_general.h @@ -186,7 +186,7 @@ implicit_gemm_conv_2d_general( if (offset_n >= gemm_params->N) return; - short diff = gemm_params->N - offset_n; + int diff = gemm_params->N - offset_n; STEEL_PRAGMA_UNROLL for (int i = 0; i < mma_t::TM; i++) { diff --git a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_l.h b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_l.h index 1284efe4a..9c134007e 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_l.h +++ b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_l.h @@ -47,8 +47,8 @@ struct Conv2DInputBlockLoaderLargeFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -197,8 +197,8 @@ struct Conv2DInputBlockLoaderSmallFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -384,6 +384,7 @@ struct Conv2DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -405,6 +406,7 @@ struct Conv2DWeightBlockLoader { weight_hw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -419,7 +421,7 @@ struct Conv2DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; @@ -481,9 +483,9 @@ struct Conv3DInputBlockLoaderLargeFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; short kdil_d; short kdil_h; @@ -665,9 +667,9 @@ struct Conv3DInputBlockLoaderSmallFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -887,6 +889,7 @@ struct Conv3DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -908,6 +911,7 @@ struct Conv3DWeightBlockLoader { weight_dhw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -922,7 +926,7 @@ struct Conv3DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; diff --git a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_n.h b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_n.h index a90e9c886..a2016fb50 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_n.h +++ b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_channel_n.h @@ -71,6 +71,7 @@ struct Conv2DInputBlockLoaderSmallChannels { // Rows / strided reads within the block STEEL_CONST short n_rows = BROWS / TROWS; + static_assert(n_rows > 0, "BM must be at least tgp_size * vec_size / BK"); // Thread location indices const short thread_idx; @@ -233,6 +234,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { int weight_hw; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -253,6 +255,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { params(params_), weight_hw(thread_idx % TCOLS), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + BN <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -260,7 +263,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { if (bi >= BROWS || bj >= BCOLS) return; - if (read_n >= params->O || weight_hw >= params->wS[1] * params->wS[0]) { + if (read_n >= N || weight_hw >= params->wS[1] * params->wS[0]) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BROWS; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -289,7 +292,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { } } else { for (short i = 0; i < BROWS; i += TROWS) { - if (((read_n + i) < params->O)) { + if (((read_n + i) < N)) { STEEL_PRAGMA_UNROLL for (short j = 0; j < n_channels; j++) { dst[i * dst_ld + j] = curr_src[i * src_ld + j]; diff --git a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_general.h b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_general.h index b44ff341e..1f4c66029 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_general.h +++ b/Source/Cmlx/mlx-generated/metal/steel/conv/loaders/loader_general.h @@ -48,8 +48,8 @@ struct Conv2DInputBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -248,8 +248,8 @@ struct Conv2DWeightBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const int start_row; diff --git a/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented.h b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented.h index 5a43e2233..6814ef50d 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented.h +++ b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented.h @@ -79,8 +79,8 @@ template < k_start = segments[tid.z]; k_end = segments[tid.z + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid.z * params->batch_stride_d; // Prepare threadgroup mma operation diff --git a/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented_nax.h b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented_nax.h index 9cfece5c5..5731cb8c1 100644 --- a/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented_nax.h +++ b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_segmented_nax.h @@ -51,8 +51,8 @@ void segmented_mm_nax( k_start = segments[tid_s]; k_end = segments[tid_s + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid_s * params->batch_stride_d; constexpr short SM = BM / WM; diff --git a/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_thin_nax.h b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_thin_nax.h new file mode 100644 index 000000000..28229a03c --- /dev/null +++ b/Source/Cmlx/mlx-generated/metal/steel/gemm/kernels/steel_gemm_thin_nax.h @@ -0,0 +1,223 @@ +// Copyright © 2026 Apple Inc. + +using namespace mlx::steel; + +constant bool use_out_source [[function_constant(100)]]; +constant bool do_axpby [[function_constant(110)]]; + +constant bool align_M [[function_constant(200)]]; +constant bool align_N [[function_constant(201)]]; +constant bool align_K [[function_constant(202)]]; + +// Each simdgroup computes one (16 * UM) x (16 * UN) block of D. It keeps a K +// chunk of A in registers and MPP reads the B chunk from device memory. +// KS groups of SM x SN simdgroups split K. +// clang-format off +template < + typename T, + int UM, + int UN, + int SM, + int SN, + int KS, + bool transpose_b> +[[kernel, max_total_threads_per_threadgroup(SM * SN * KS * 32)]] void gemm_thin_nax( + const device T* A [[buffer(0)]], + const device T* B [[buffer(1)]], + const device T* C [[buffer(2), function_constant(use_out_source)]], + device T* D [[buffer(3)]], + const constant GEMMParams* params [[buffer(4)]], + const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on + using extents_t = metal::dextents; + using strides_t = metal::array; + using tensor_t = metal::tensor; + + constexpr int TSM = 16 * UM; + constexpr int TSN = 16 * UN; + constexpr int BK = 64; + + const int M = params->M; + const int N = params->N; + const int K = params->K; + const int lda = params->lda; + const int ldb = params->ldb; + + // Threadgroups go along M first, so groups that run together share B. + const int tgp = tid.x; + const int tile_m = tgp % params->tiles_m; + const int tile_n = tgp / params->tiles_m; + + const int k_group = simd_group_id / (SM * SN); + const int sg = simd_group_id % (SM * SN); + int m_off = (tile_m * SM + sg % SM) * TSM; + int n_off = (tile_n * SN + sg / SM) * TSN; + + // A block at the edge moves back inside if the matrix is large enough. It + // then writes again some outputs of a neighbor block, with equal values. + const bool active = (align_M || m_off < M) && (align_N || n_off < N); + if (!align_M && m_off + TSM > M && M >= TSM) { + m_off = M - TSM; + } + if (!align_N && n_off + TSN > N && N >= TSN) { + n_off = N - TSN; + } + const bool inside = + (align_M || m_off + TSM <= M) && (align_N || n_off + TSN <= N); + const int rows = active ? M - m_off : 0; + const int cols = active ? N - n_off : 0; + + A += int64_t(m_off) * lda; + B += transpose_b ? int64_t(n_off) * ldb : int64_t(n_off); + D += int64_t(m_off) * params->ldd + n_off; + if (use_out_source) { + C += + int64_t(m_off) * addmm_params->ldc + int64_t(n_off) * addmm_params->fdc; + } + + tensor_t tA((device T*)A, extents_t(K, rows), strides_t{1, lda}); + tensor_t tB( + (device T*)B, + transpose_b ? extents_t(K, cols) : extents_t(cols, K), + strides_t{1, ldb}); + + auto a_chunk = [&](int k) { return tA.template slice(k, 0); }; + auto b_chunk = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + auto b_tail = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + using a_chunk_t = decltype(a_chunk(0)); + using b_chunk_t = decltype(b_chunk(0)); + + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + TSM, + TSN, + BK, + false, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + mpp::tensor_ops::matmul2d op; + + // The accumulator layout depends only on the element types, so the masked + // runs below can also use it. + auto Dacc = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] = 0.0f; + } + auto Areg = op.template get_left_input_cooperative_tensor(); + + const int k_iters = params->gemm_k_iterations_aligned; + for (int it = 0; it < k_iters; it++) { + // Keep the simdgroups near each other in K, so that their shared loads + // hit in cache. + if ((it & 3) == 0) { + threadgroup_barrier(mem_flags::mem_none); + } + const int k = (it * KS + k_group) * BK; + if (!active || k >= K) { + continue; + } + if (inside && (align_K || k + BK <= K)) { + auto a = a_chunk(k); + Areg.load(a); + auto b = b_chunk(k); + op.run(Areg, b, Dacc); + } else if (inside) { + auto a = tA.template slice(k, 0); + auto b = b_tail(k); + op.run(a, b, Dacc); + } else { + // The views stop at the matrix edge and MPP masks the rest. + const int kk = min(BK, K - k); + tensor_t vA((device T*)A + k, extents_t(kk, rows), strides_t{1, lda}); + tensor_t vB( + (device T*)B + (transpose_b ? int64_t(k) : int64_t(k) * ldb), + transpose_b ? extents_t(kk, cols) : extents_t(cols, kk), + strides_t{1, ldb}); + op.run(vA, vB, Dacc); + } + } + + if constexpr (KS > 1) { + // K groups 1 to KS - 1 store their partial sums and group 0 adds them. + using tg_tensor_t = + metal::tensor; + constexpr int kBlockSize = TSM * TSN; + static_assert( + (KS - 1) * SM * SN * kBlockSize <= 4096, + "Partial sums need more than 16 KB of threadgroup memory"); + threadgroup float partials[(KS - 1) * SM * SN * kBlockSize]; + + if (active && k_group > 0) { + tg_tensor_t tP( + partials + ((k_group - 1) * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + Dacc.store(tP); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (active && k_group == 0) { + for (int g = 0; g < KS - 1; g++) { + tg_tensor_t tP( + partials + (g * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + auto part = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + part.load(tP); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] += part[i]; + } + } + } + } + if (k_group != 0 || !active) { + return; + } + + auto Dout = + op.template get_destination_cooperative_tensor(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + float d = Dacc[i]; + if (use_out_source) { + auto idx = Dacc.get_multidimensional_index(i); + const int r = idx[1]; + const int c = idx[0]; + if (inside || (r < rows && c < cols)) { + float c_val = static_cast( + C[int64_t(r) * addmm_params->ldc + int64_t(c) * addmm_params->fdc]); + d = do_axpby ? addmm_params->alpha * d + addmm_params->beta * c_val + : d + c_val; + } + } + Dout[i] = static_cast(d); + } + + tensor_t tD(D, extents_t(cols, rows), strides_t{1, params->ldd}); + if (inside) { + auto d = tD.template slice(0, 0); + Dout.store(d); + } else { + Dout.store(tD); + } +} diff --git a/Source/Cmlx/mlx-generated/quantized.cpp b/Source/Cmlx/mlx-generated/quantized.cpp index 0ec148ade..22009b9a8 100644 --- a/Source/Cmlx/mlx-generated/quantized.cpp +++ b/Source/Cmlx/mlx-generated/quantized.cpp @@ -41,15 +41,30 @@ inline constexpr short get_bytes_per_pack() { template inline U load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -59,8 +74,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 3) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; x_thread[i + 2] = x[i + 2] / 64.0f; @@ -74,7 +89,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 4) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -84,8 +99,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 5) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -99,7 +114,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 6) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -120,15 +135,30 @@ inline U load_vector(const device T* x, thread U* x_thread) { template inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -138,8 +168,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 3) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; @@ -154,7 +184,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 4) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -164,8 +194,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 5) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -179,7 +209,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 6) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -209,13 +239,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -311,13 +355,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -408,11 +466,25 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + result[8 * i] += x * (select(U(0), scale, bool(wb & 0x01)) + bias); + result[8 * i + 1] += x * (select(U(0), scale, bool(wb & 0x02)) + bias); + result[8 * i + 2] += x * (select(U(0), scale, bool(wb & 0x04)) + bias); + result[8 * i + 3] += x * (select(U(0), scale, bool(wb & 0x08)) + bias); + result[8 * i + 4] += x * (select(U(0), scale, bool(wb & 0x10)) + bias); + result[8 * i + 5] += x * (select(U(0), scale, bool(wb & 0x20)) + bias); + result[8 * i + 6] += x * (select(U(0), scale, bool(wb & 0x40)) + bias); + result[8 * i + 7] += x * (select(U(0), scale, bool(wb & 0x80)) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -498,14 +570,36 @@ qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { template inline void dequantize(const device uint8_t* w, U scale, U bias, W w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -598,9 +692,9 @@ struct QuantizedBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -766,7 +860,7 @@ METAL_FUNC void qmv_quad_impl( } } -template +template METAL_FUNC void qmv_fast_impl( const device uint32_t* w, const device T* scales, @@ -778,7 +872,8 @@ METAL_FUNC void qmv_fast_impl( uint3 tid [[threadgroup_position_in_grid]], uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { - constexpr int packs_per_thread = bits == 2 ? 1 : 2; + constexpr int packs_per_thread = + bits <= 2 ? 1 : 2; // 1-bit: 1 pack (vpt=32) for occupancy constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int pack_factor = get_pack_factor(); @@ -800,19 +895,37 @@ METAL_FUNC void qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // With partial rows the output size need not be a multiple of 8. Rows of the + // last SIMD-group that fall past the output reuse the weights of the last + // valid output row, so the reduction loop needs no per-row bounds check, and + // are not stored. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; y += tid.x * out_vec_size + out_row; - for (int k = 0; k < in_vec_size; k += block_size) { + const int aligned_end = (in_vec_size / block_size) * block_size; + + for (int k = 0; k < aligned_end; k += block_size) { U sum = load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device T* sl = scales + row * in_vec_size_g; - const device T* bl = biases + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; U s = sl[0]; U b = bl[0]; @@ -825,9 +938,37 @@ METAL_FUNC void qmv_fast_impl( x += block_size; } + // Tail block: handles K that is a multiple of 512 (dispatch gate) but not + // of block_size. Only 1-bit has block_size > 512 (it uses 2048), so for + // >=2-bit this is a no-op. Out-of-bounds lanes skip the qdot call entirely; + // their result[row] stays at 0 and contributes 0 to the simd_sum below. + if (aligned_end < in_vec_size) { + bool in_bounds = + (aligned_end + static_cast(simd_lid) * values_per_thread) < + in_vec_size; + if (in_bounds) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + } + } + for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { y[row] = static_cast(result[row]); } } @@ -1206,6 +1347,7 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, const int BM = 32, const int BK = 32, const int BN = 32> @@ -1214,7 +1356,7 @@ METAL_FUNC void qmm_t_impl( const device T* scales, const device T* biases, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, threadgroup T* Ws, const constant int& K, @@ -1239,7 +1381,7 @@ METAL_FUNC void qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; using loader_w_t = QuantizedBlockLoader< @@ -1615,6 +1757,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv_fast( @@ -1655,7 +1798,7 @@ template < b_strides, tid); } - qmv_fast_impl( + qmv_fast_impl( w, scales, biases, @@ -1673,6 +1816,7 @@ template < int group_size, const int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv( @@ -1959,7 +2103,7 @@ template < b_strides, tid); } - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -1990,7 +2134,7 @@ template < const device T* scales [[buffer(1)]], const device T* biases [[buffer(2)]], const device T* x [[buffer(3)]], - device T* y [[buffer(4)]], + device float* y [[buffer(4)]], const constant int& K [[buffer(5)]], const constant int& N [[buffer(6)]], const constant int& M [[buffer(7)]], @@ -2018,7 +2162,7 @@ template < biases += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - qmm_t_impl( + qmm_t_impl( (const device uint32_t*)wl, scales, biases, @@ -2349,7 +2493,7 @@ template < s_strides, b_strides, tid); - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -2630,14 +2774,23 @@ template w_min = simd_min(w_min); w_max = simd_max(w_max); - float scale = max((w_max - w_min) / n_bins, eps); - bool side = abs(w_min) > abs(w_max); - scale = side ? scale : -scale; - float edge = side ? w_min : w_max; - float q0 = round(edge / scale); - bool at_zero = q0 == 0.0f; - scale = at_zero ? scale : edge / q0; - float bias = at_zero ? 0 : edge; + float scale; + float bias; + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scale = max(w_max - w_min, eps); + bias = w_min; + } else { + scale = max((w_max - w_min) / n_bins, eps); + bool side = abs(w_min) > abs(w_max); + scale = side ? scale : -scale; + float edge = side ? w_min : w_max; + float q0 = round(edge / scale); + bool at_zero = q0 == 0.0f; + scale = at_zero ? scale : edge / q0; + bias = at_zero ? 0 : edge; + } // Write out the scales and biases size_t gindex = in_index / group_size; @@ -2741,7 +2894,9 @@ template #pragma clang loop unroll(full) for (int i = 0; i < pack_factor; i++) { uint8_t d; - if (bits == 2) { + if (bits == 1) { + d = (val >> i) & 0x01; + } else if (bits == 2) { d = (val >> (bits * i)) & 0x03; } else if (bits == 4) { d = (val >> (bits * i)) & 0x0f; diff --git a/Source/Cmlx/mlx-generated/quantized_nax.cpp b/Source/Cmlx/mlx-generated/quantized_nax.cpp index 05277f64d..8f5d2297c 100644 --- a/Source/Cmlx/mlx-generated/quantized_nax.cpp +++ b/Source/Cmlx/mlx-generated/quantized_nax.cpp @@ -44,15 +44,30 @@ inline constexpr short get_bytes_per_pack() { template inline U load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -62,8 +77,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 3) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; x_thread[i + 2] = x[i + 2] / 64.0f; @@ -77,7 +92,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 4) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -87,8 +102,8 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 5) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -102,7 +117,7 @@ inline U load_vector(const device T* x, thread U* x_thread) { else if (bits == 6) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -123,15 +138,30 @@ inline U load_vector(const device T* x, thread U* x_thread) { template inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -141,8 +171,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 3) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; @@ -157,7 +187,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 4) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -167,8 +197,8 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 5) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -182,7 +212,7 @@ inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 6) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -212,13 +242,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -314,13 +358,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -411,11 +469,33 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + U s[8] = { + scale, + scale / 2.0f, + scale / 4.0f, + scale / 8.0f, + scale / 16.0f, + scale / 32.0f, + scale / 64.0f, + scale / 128.0f}; + for (int i = 0; i < (values_per_thread / 8); i++) { + result[8 * i] += x * (s[0] * (w[i] & 0x01) + bias); + result[8 * i + 1] += x * (s[1] * (w[i] & 0x02) + bias); + result[8 * i + 2] += x * (s[2] * (w[i] & 0x04) + bias); + result[8 * i + 3] += x * (s[3] * (w[i] & 0x08) + bias); + result[8 * i + 4] += x * (s[4] * (w[i] & 0x10) + bias); + result[8 * i + 5] += x * (s[5] * (w[i] & 0x20) + bias); + result[8 * i + 6] += x * (s[6] * (w[i] & 0x40) + bias); + result[8 * i + 7] += x * (s[7] * (w[i] & 0x80) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -500,14 +580,36 @@ template inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -600,9 +702,9 @@ struct QuantizedBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -728,9 +830,9 @@ struct QuantizedBlockLoader< BCOLS % group_size == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); diff --git a/Source/Cmlx/mlx-generated/reduce.cpp b/Source/Cmlx/mlx-generated/reduce.cpp index cac2d8de5..3cb5e0ca0 100644 --- a/Source/Cmlx/mlx-generated/reduce.cpp +++ b/Source/Cmlx/mlx-generated/reduce.cpp @@ -202,7 +202,7 @@ template IdxT out_idx = gid.x + gsize.x * IdxT(gid.y); IdxT in_idx = elem_to_loc(out_idx, shape, strides, ndim); - in += in_idx + lid.x; + in += in_idx + IdxT(lid.x); U total = Op::init; IdxT total_rows = IdxT(non_col_reductions) * IdxT(reduction_size); @@ -257,6 +257,7 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], + const constant int64_t& column_offset [[buffer(11)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -278,7 +279,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT out_idx = gid.y + gsize.y * IdxT(gid.z); @@ -328,7 +329,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += out_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { @@ -396,7 +397,8 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], - const constant size_t& out_size [[buffer(11)]], + const constant int64_t& column_offset [[buffer(11)]], + const constant size_t& out_size [[buffer(12)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -421,7 +423,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT full_idx = gid.y + gsize.y * IdxT(gid.z); @@ -468,7 +470,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += full_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { @@ -492,8 +494,9 @@ template < template [[kernel]] void init_reduce( device T* out [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = Op::init; + uint2 index [[thread_position_in_grid]], + uint2 grid_dim [[threads_per_grid]]) { + out[index.x + grid_dim.x * int64_t(index.y)] = Op::init; } /////////////////////////////////////////////////////////////////////////////// diff --git a/Source/Cmlx/mlx-generated/scatter.cpp b/Source/Cmlx/mlx-generated/scatter.cpp index b8bf7c108..ed991a65d 100644 --- a/Source/Cmlx/mlx-generated/scatter.cpp +++ b/Source/Cmlx/mlx-generated/scatter.cpp @@ -77,8 +77,8 @@ METAL_FUNC void scatter_impl( for (int j = 0; j < NWORK && ind_idx < idx_size; ++j, ind_idx++) { LocT out_idx = out_offset; for (int i = 0; i < NIDX; ++i) { - auto idx_loc = indices.row_contiguous[i] - ? ind_idx + LocT idx_loc = indices.row_contiguous[i] + ? LocT(ind_idx) : elem_to_loc( ind_idx, &indices.shapes[indices.ndim * i], @@ -89,7 +89,7 @@ METAL_FUNC void scatter_impl( out_idx += static_cast(idx_val) * static_cast(out_strides[ax]); } - auto upd_idx = ind_idx * static_cast(upd_size) + gid.x; + LocT upd_idx = ind_idx * static_cast(upd_size) + gid.x; if constexpr (!UPD_ROW_CONTIG) { upd_idx = elem_to_loc(upd_idx, upd_shape, upd_strides, upd_ndim); } diff --git a/Source/Cmlx/mlx-generated/steel_attention.cpp b/Source/Cmlx/mlx-generated/steel_attention.cpp index acd115969..31469e831 100644 --- a/Source/Cmlx/mlx-generated/steel_attention.cpp +++ b/Source/Cmlx/mlx-generated/steel_attention.cpp @@ -1795,6 +1795,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; struct MaxOp { template @@ -1858,6 +1859,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -1884,6 +1886,12 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -2313,6 +2321,20 @@ template < Otile.template row_bin_op(sum_score); threadgroup_barrier(mem_flags::mem_none); + // Store the logsumexp for the backward pass + if (save_lse && sn == 0) { + using stile_t = decltype(Stile); + const bool is_last_q = int(tid.x) == (params->NQ_aligned); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + sm + i * stile_t::kFragRows; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = M_LN2_F * (max_score[i] + metal::log2(sum_score[i])); + } + } + } + // Store results O += (tm + sm) * params->O_strides[2] + d_half * BVh + sn; diff --git a/Source/Cmlx/mlx-generated/steel_attention_nax.cpp b/Source/Cmlx/mlx-generated/steel_attention_nax.cpp index 3d4595d3c..222bb185d 100644 --- a/Source/Cmlx/mlx-generated/steel_attention_nax.cpp +++ b/Source/Cmlx/mlx-generated/steel_attention_nax.cpp @@ -1305,6 +1305,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; template struct TransformScale { @@ -1378,6 +1379,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -1405,6 +1407,13 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + // [B, H, qL], contiguous. + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -1763,6 +1772,16 @@ template < Otile.template row_bin_op(rcp); + if (save_lse && sn == 0) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + i * otile_t::kFragRowsJump + sm; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = max_score[i] * M_LN2_F + metal::log(sum_score[i]); + } + } + } + // Store results O += tm * int(params->O_strides[2]); @@ -1804,6 +1823,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* LSE [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -2191,6 +2211,21 @@ template < rcp[i] = 1.f / sum_score[i]; } + if (save_lse && d_group == 0 && sn == 0) { + const int lse_row_base = int(tid.x) * BQ + tm; + const int lse_head_off = (int(tid.z) * params->H + int(tid.y)) * params->qL; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const int row = lse_row_base + i * stile_t::kFragRowsJump + sm; + if (row < params->qL) { + LSE[lse_head_off + row] = (sum_score[i] == 0) + ? -INFINITY + : float(M_LN2_F * (max_score[i] + metal::log2(sum_score[i]))); + } + } + } + Otile.template row_bin_op(rcp); if (!align_Q && is_last_q) { diff --git a/Source/Cmlx/mlx-generated/steel_conv.cpp b/Source/Cmlx/mlx-generated/steel_conv.cpp index 2af0e5605..85aca4026 100644 --- a/Source/Cmlx/mlx-generated/steel_conv.cpp +++ b/Source/Cmlx/mlx-generated/steel_conv.cpp @@ -59,7 +59,7 @@ implicit_gemm_conv_2d( using loader_a_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DInputBlockLoaderSmallChannels< @@ -97,7 +97,7 @@ implicit_gemm_conv_2d( // Weight loader using loader_b_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DWeightBlockLoaderSmallChannels< diff --git a/Source/Cmlx/mlx-generated/steel_conv_general.cpp b/Source/Cmlx/mlx-generated/steel_conv_general.cpp index 0024a77f5..a3e98ac47 100644 --- a/Source/Cmlx/mlx-generated/steel_conv_general.cpp +++ b/Source/Cmlx/mlx-generated/steel_conv_general.cpp @@ -71,8 +71,8 @@ struct Conv2DInputBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -271,8 +271,8 @@ struct Conv2DWeightBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const int start_row; @@ -595,7 +595,7 @@ implicit_gemm_conv_2d_general( if (offset_n >= gemm_params->N) return; - short diff = gemm_params->N - offset_n; + int diff = gemm_params->N - offset_n; STEEL_PRAGMA_UNROLL for (int i = 0; i < mma_t::TM; i++) { diff --git a/Source/Cmlx/mlx-generated/steel_gemm_segmented.cpp b/Source/Cmlx/mlx-generated/steel_gemm_segmented.cpp index 848428230..1e1d37269 100644 --- a/Source/Cmlx/mlx-generated/steel_gemm_segmented.cpp +++ b/Source/Cmlx/mlx-generated/steel_gemm_segmented.cpp @@ -92,8 +92,8 @@ template < k_start = segments[tid.z]; k_end = segments[tid.z + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid.z * params->batch_stride_d; // Prepare threadgroup mma operation diff --git a/Source/Cmlx/mlx-generated/steel_gemm_segmented_nax.cpp b/Source/Cmlx/mlx-generated/steel_gemm_segmented_nax.cpp index 519087e1b..2e7adfb0c 100644 --- a/Source/Cmlx/mlx-generated/steel_gemm_segmented_nax.cpp +++ b/Source/Cmlx/mlx-generated/steel_gemm_segmented_nax.cpp @@ -64,8 +64,8 @@ void segmented_mm_nax( k_start = segments[tid_s]; k_end = segments[tid_s + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid_s * params->batch_stride_d; constexpr short SM = BM / WM; diff --git a/Source/Cmlx/mlx-generated/steel_gemm_thin_nax.cpp b/Source/Cmlx/mlx-generated/steel_gemm_thin_nax.cpp new file mode 100644 index 000000000..d9253fc8b --- /dev/null +++ b/Source/Cmlx/mlx-generated/steel_gemm_thin_nax.cpp @@ -0,0 +1,242 @@ +namespace mlx::core::metal { + +const char* steel_gemm_thin_nax() { + return R"preamble( +// Copyright © 2025 Apple Inc. + +// Auto generated source for mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h + +/////////////////////////////////////////////////////////////////////////////// +// Contents from "mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h" +/////////////////////////////////////////////////////////////////////////////// + +#line 1 "mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h" +// Copyright © 2026 Apple Inc. + +using namespace mlx::steel; + +constant bool use_out_source [[function_constant(100)]]; +constant bool do_axpby [[function_constant(110)]]; + +constant bool align_M [[function_constant(200)]]; +constant bool align_N [[function_constant(201)]]; +constant bool align_K [[function_constant(202)]]; + +// Each simdgroup computes one (16 * UM) x (16 * UN) block of D. It keeps a K +// chunk of A in registers and MPP reads the B chunk from device memory. +// KS groups of SM x SN simdgroups split K. +// clang-format off +template < + typename T, + int UM, + int UN, + int SM, + int SN, + int KS, + bool transpose_b> +[[kernel, max_total_threads_per_threadgroup(SM * SN * KS * 32)]] void gemm_thin_nax( + const device T* A [[buffer(0)]], + const device T* B [[buffer(1)]], + const device T* C [[buffer(2), function_constant(use_out_source)]], + device T* D [[buffer(3)]], + const constant GEMMParams* params [[buffer(4)]], + const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on + using extents_t = metal::dextents; + using strides_t = metal::array; + using tensor_t = metal::tensor; + + constexpr int TSM = 16 * UM; + constexpr int TSN = 16 * UN; + constexpr int BK = 64; + + const int M = params->M; + const int N = params->N; + const int K = params->K; + const int lda = params->lda; + const int ldb = params->ldb; + + // Threadgroups go along M first, so groups that run together share B. + const int tgp = tid.x; + const int tile_m = tgp % params->tiles_m; + const int tile_n = tgp / params->tiles_m; + + const int k_group = simd_group_id / (SM * SN); + const int sg = simd_group_id % (SM * SN); + int m_off = (tile_m * SM + sg % SM) * TSM; + int n_off = (tile_n * SN + sg / SM) * TSN; + + // A block at the edge moves back inside if the matrix is large enough. It + // then writes again some outputs of a neighbor block, with equal values. + const bool active = (align_M || m_off < M) && (align_N || n_off < N); + if (!align_M && m_off + TSM > M && M >= TSM) { + m_off = M - TSM; + } + if (!align_N && n_off + TSN > N && N >= TSN) { + n_off = N - TSN; + } + const bool inside = + (align_M || m_off + TSM <= M) && (align_N || n_off + TSN <= N); + const int rows = active ? M - m_off : 0; + const int cols = active ? N - n_off : 0; + + A += int64_t(m_off) * lda; + B += transpose_b ? int64_t(n_off) * ldb : int64_t(n_off); + D += int64_t(m_off) * params->ldd + n_off; + if (use_out_source) { + C += + int64_t(m_off) * addmm_params->ldc + int64_t(n_off) * addmm_params->fdc; + } + + tensor_t tA((device T*)A, extents_t(K, rows), strides_t{1, lda}); + tensor_t tB( + (device T*)B, + transpose_b ? extents_t(K, cols) : extents_t(cols, K), + strides_t{1, ldb}); + + auto a_chunk = [&](int k) { return tA.template slice(k, 0); }; + auto b_chunk = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + auto b_tail = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + using a_chunk_t = decltype(a_chunk(0)); + using b_chunk_t = decltype(b_chunk(0)); + + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + TSM, + TSN, + BK, + false, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + mpp::tensor_ops::matmul2d op; + + // The accumulator layout depends only on the element types, so the masked + // runs below can also use it. + auto Dacc = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] = 0.0f; + } + auto Areg = op.template get_left_input_cooperative_tensor(); + + const int k_iters = params->gemm_k_iterations_aligned; + for (int it = 0; it < k_iters; it++) { + // Keep the simdgroups near each other in K, so that their shared loads + // hit in cache. + if ((it & 3) == 0) { + threadgroup_barrier(mem_flags::mem_none); + } + const int k = (it * KS + k_group) * BK; + if (!active || k >= K) { + continue; + } + if (inside && (align_K || k + BK <= K)) { + auto a = a_chunk(k); + Areg.load(a); + auto b = b_chunk(k); + op.run(Areg, b, Dacc); + } else if (inside) { + auto a = tA.template slice(k, 0); + auto b = b_tail(k); + op.run(a, b, Dacc); + } else { + // The views stop at the matrix edge and MPP masks the rest. + const int kk = min(BK, K - k); + tensor_t vA((device T*)A + k, extents_t(kk, rows), strides_t{1, lda}); + tensor_t vB( + (device T*)B + (transpose_b ? int64_t(k) : int64_t(k) * ldb), + transpose_b ? extents_t(kk, cols) : extents_t(cols, kk), + strides_t{1, ldb}); + op.run(vA, vB, Dacc); + } + } + + if constexpr (KS > 1) { + // K groups 1 to KS - 1 store their partial sums and group 0 adds them. + using tg_tensor_t = + metal::tensor; + constexpr int kBlockSize = TSM * TSN; + static_assert( + (KS - 1) * SM * SN * kBlockSize <= 4096, + "Partial sums need more than 16 KB of threadgroup memory"); + threadgroup float partials[(KS - 1) * SM * SN * kBlockSize]; + + if (active && k_group > 0) { + tg_tensor_t tP( + partials + ((k_group - 1) * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + Dacc.store(tP); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (active && k_group == 0) { + for (int g = 0; g < KS - 1; g++) { + tg_tensor_t tP( + partials + (g * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + auto part = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + part.load(tP); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] += part[i]; + } + } + } + } + if (k_group != 0 || !active) { + return; + } + + auto Dout = + op.template get_destination_cooperative_tensor(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + float d = Dacc[i]; + if (use_out_source) { + auto idx = Dacc.get_multidimensional_index(i); + const int r = idx[1]; + const int c = idx[0]; + if (inside || (r < rows && c < cols)) { + float c_val = static_cast( + C[int64_t(r) * addmm_params->ldc + int64_t(c) * addmm_params->fdc]); + d = do_axpby ? addmm_params->alpha * d + addmm_params->beta * c_val + : d + c_val; + } + } + Dout[i] = static_cast(d); + } + + tensor_t tD(D, extents_t(cols, rows), strides_t{1, params->ldd}); + if (inside) { + auto d = tD.template slice(0, 0); + Dout.store(d); + } else { + Dout.store(tD); + } +} + +/////////////////////////////////////////////////////////////////////////////// +)preamble"; +} + +} // namespace mlx::core::metal diff --git a/Source/Cmlx/mlx-generated/utils.cpp b/Source/Cmlx/mlx-generated/utils.cpp index c8cf785e0..047bcd788 100644 --- a/Source/Cmlx/mlx-generated/utils.cpp +++ b/Source/Cmlx/mlx-generated/utils.cpp @@ -681,10 +681,20 @@ constexpr complex_t operator*(complex_t a, complex_t b) { template constexpr complex_t operator/(complex_t a, complex_t b) { - auto denom = b.real * b.real + b.imag * b.imag; - auto x = a.real * b.real + a.imag * b.imag; - auto y = a.imag * b.real - a.real * b.imag; - return {x / denom, y / denom}; + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; } template < @@ -692,11 +702,7 @@ template < typename U, enable_if_t && is_lane_convertible_v, bool> = true> constexpr complex_t operator/(U a, complex_t b) { - auto scalar = static_cast(a); - auto denom = b.real * b.real + b.imag * b.imag; - auto x = scalar * b.real; - auto y = -scalar * b.imag; - return {x / denom, y / denom}; + return complex_t(a) / b; } template diff --git a/tools/fix-metal-includes.sh b/tools/fix-metal-includes.sh index 36055fd6c..81f8d0f30 100755 --- a/tools/fix-metal-includes.sh +++ b/tools/fix-metal-includes.sh @@ -24,6 +24,7 @@ arg_reduce.metal \ conv.metal \ dot.metal \ gated_delta_update.metal \ +gated_delta_update_vjp.metal \ gather_mm_offsets.metal \ layer_norm.metal \ random.metal \ @@ -31,6 +32,7 @@ rms_norm.metal \ rope.metal \ searchsorted.metal \ scaled_dot_product_attention.metal \ +scaled_dot_product_attention_vjp.metal \ steel/attn/kernels/steel_attention.metal" # We fixup all the header files AND the listed kernel files diff --git a/xcode/MLX.xcodeproj/project.pbxproj b/xcode/MLX.xcodeproj/project.pbxproj index 8277ab7b1..3815cfbd4 100644 --- a/xcode/MLX.xcodeproj/project.pbxproj +++ b/xcode/MLX.xcodeproj/project.pbxproj @@ -525,7 +525,6 @@ benchmarks/python/synchronize_bench.py, benchmarks/python/time_utils.py, CITATION.cff, - CLAUDE.md, cmake/extension.cmake, cmake/FindCUDNN.cmake, cmake/FindNCCL.cmake, @@ -615,6 +614,16 @@ docs/src/usage/saving_and_loading.rst, docs/src/usage/unified_memory.rst, docs/src/usage/using_streams.rst, + examples/cmake_extension/axpby/axpby.cpp, + examples/cmake_extension/axpby/axpby.h, + examples/cmake_extension/axpby/axpby.metal, + examples/cmake_extension/bindings.cpp, + examples/cmake_extension/CMakeLists.txt, + examples/cmake_extension/pyproject.toml, + examples/cmake_extension/README.md, + examples/cmake_extension/requirements.txt, + examples/cmake_extension/setup.py, + examples/cmake_extension/test.py, examples/cmake_project/CMakeLists.txt, examples/cmake_project/example.cpp, examples/cmake_project/README.md, @@ -631,17 +640,13 @@ examples/export/README.md, examples/export/train_mlp.cpp, examples/export/train_mlp.py, - examples/extensions/axpby/axpby.cpp, - examples/extensions/axpby/axpby.h, - examples/extensions/axpby/axpby.metal, - examples/extensions/bindings.cpp, - examples/extensions/CMakeLists.txt, - examples/extensions/mlx_sample_extensions/__init__.py, - examples/extensions/pyproject.toml, - examples/extensions/README.md, - examples/extensions/requirements.txt, - examples/extensions/setup.py, - examples/extensions/test.py, + examples/metal_extension/activation.cpp, + examples/metal_extension/pyproject.toml, + examples/metal_extension/README.md, + examples/metal_extension/requirements.txt, + examples/metal_extension/setup.py, + examples/metal_extension/silu_and_mul.metal, + examples/metal_extension/test.py, examples/python/distributed_data_parallel.py, examples/python/distributed_tensor_parallel.py, examples/python/linear_regression.py, @@ -715,6 +720,7 @@ mlx/backend/cuda/binary/CMakeLists.txt, mlx/backend/cuda/binary/divide.cu, mlx/backend/cuda/binary/equal.cu, + mlx/backend/cuda/binary/floor_divide.cu, mlx/backend/cuda/binary/greater_equal.cu, mlx/backend/cuda/binary/greater.cu, mlx/backend/cuda/binary/less_equal.cu, @@ -729,8 +735,8 @@ mlx/backend/cuda/binary/power.cu, mlx/backend/cuda/binary/remainder.cu, mlx/backend/cuda/binary/subtract.cu, - mlx/backend/cuda/CMakeLists.txt, mlx/backend/cuda/cholesky.cu, + mlx/backend/cuda/CMakeLists.txt, mlx/backend/cuda/compiled.cpp, mlx/backend/cuda/conv.cpp, mlx/backend/cuda/conv/conv.h, @@ -949,8 +955,13 @@ mlx/backend/metal/kernels/fp_quantized.metal, mlx/backend/metal/kernels/fp4.h, mlx/backend/metal/kernels/fp8.h, + mlx/backend/metal/kernels/gated_delta_nax_ops.h, + mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h, + mlx/backend/metal/kernels/gated_delta_update_nax_vjp.metal, mlx/backend/metal/kernels/gated_delta_update_nax.h, mlx/backend/metal/kernels/gated_delta_update_nax.metal, + mlx/backend/metal/kernels/gated_delta_update_vjp.h, + mlx/backend/metal/kernels/gated_delta_update_vjp.metal, mlx/backend/metal/kernels/gated_delta_update.h, mlx/backend/metal/kernels/gated_delta_update.metal, mlx/backend/metal/kernels/gather_mm_offsets.metal, @@ -986,9 +997,11 @@ mlx/backend/metal/kernels/reduction/reduce_row.h, mlx/backend/metal/kernels/rms_norm.metal, mlx/backend/metal/kernels/rope.metal, + mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal, mlx/backend/metal/kernels/scaled_dot_product_attention.metal, mlx/backend/metal/kernels/scan.h, mlx/backend/metal/kernels/scan.metal, + mlx/backend/metal/kernels/sdpa_blocked.h, mlx/backend/metal/kernels/sdpa_vector.h, mlx/backend/metal/kernels/searchsorted.h, mlx/backend/metal/kernels/searchsorted.metal, @@ -1039,6 +1052,8 @@ mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk_nax.metal, mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk.h, mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk.metal, + mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h, + mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.metal, mlx/backend/metal/kernels/steel/gemm/loader.h, mlx/backend/metal/kernels/steel/gemm/mma.h, mlx/backend/metal/kernels/steel/gemm/nax.h, @@ -1251,6 +1266,7 @@ python/tests/test_einsum.py, python/tests/test_eval.py, python/tests/test_export_import.py, + python/tests/test_extension.py, python/tests/test_fast_gated_delta.py, python/tests/test_fast_sdpa.py, python/tests/test_fast.py, @@ -1271,6 +1287,8 @@ python/tests/test_tree.py, python/tests/test_upsample.py, python/tests/test_vmap.py, + "python/tests/xp-tests/skips.txt", + "python/tests/xp-tests/xfail.txt", README.md, setup.py, tests/allocator_tests.cpp, @@ -1406,7 +1424,10 @@ metal/fp_quantized.h, metal/fp4.h, metal/fp8.h, + metal/gated_delta_nax_ops.h, + metal/gated_delta_update_nax_vjp.h, metal/gated_delta_update_nax.h, + metal/gated_delta_update_vjp.h, metal/gated_delta_update.h, metal/gemv_masked.h, metal/gemv.h, @@ -1431,6 +1452,7 @@ metal/reduction/reduce_init.h, metal/reduction/reduce_row.h, metal/scan.h, + metal/sdpa_blocked.h, metal/sdpa_vector.h, metal/searchsorted.h, metal/softmax.h, @@ -1464,6 +1486,7 @@ metal/steel/gemm/kernels/steel_gemm_segmented.h, metal/steel/gemm/kernels/steel_gemm_splitk_nax.h, metal/steel/gemm/kernels/steel_gemm_splitk.h, + metal/steel/gemm/kernels/steel_gemm_thin_nax.h, metal/steel/gemm/loader.h, metal/steel/gemm/mma.h, metal/steel/gemm/nax.h, From a4dbf45f4b6ac4e4aa8c6afe0b4ae088b0227af1 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Mon, 19 Oct 2026 13:16:24 -0700 Subject: [PATCH 2/3] Report MLX v0.32.4 as its version The merge brought over the 0.32.3 branch's MLX_VERSION, and VersionTests caught it: ("0.32.3") is not equal to ("0.32.4"). Package.swift and Cmlx.xcconfig now say 0.32.4. That's what the version-sync lines in tools/update-mlx.sh read from this branch's mlx/version.h. Co-Authored-By: Claude Opus 5.5 --- Package.swift | 2 +- xcode/xcconfig/Cmlx.xcconfig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index fa5a0900d..794e2adeb 100644 --- a/Package.swift +++ b/Package.swift @@ -319,7 +319,7 @@ let cmlx = Target.target( .headerSearchPath("json/single_include/nlohmann"), .headerSearchPath("fmt/include"), // MLX's CMake reads this from mlx/version.h; tools/update-mlx.sh keeps it in sync - .define("MLX_VERSION", to: "\"0.32.3\""), + .define("MLX_VERSION", to: "\"0.32.4\""), ], linkerSettings: linkerSettings, plugins: cudaBuildPlugins, diff --git a/xcode/xcconfig/Cmlx.xcconfig b/xcode/xcconfig/Cmlx.xcconfig index 98c0fdf69..4dcf80ea2 100644 --- a/xcode/xcconfig/Cmlx.xcconfig +++ b/xcode/xcconfig/Cmlx.xcconfig @@ -13,5 +13,5 @@ USER_HEADER_SEARCH_PATHS = $(SRCROOT)/../Source/Cmlx/mlx-c $(SRCROOT)/../Source/ MTL_COMPILER_FLAGS = -Wall -Wextra -fno-fast-math -Wno-c++17-extensions -Wno-c++20-extensions -GCC_PREPROCESSOR_DEFINITIONS = _METAL_=1 SWIFTPM_BUNDLE=\"com.apple.mlx.Cmlx\" MLX_VERSION=\"0.32.3\" MLX_USE_ACCELERATE=1 METAL_PATH=\"default.metallib\" ACCELERATE_NEW_LAPACK=1 +GCC_PREPROCESSOR_DEFINITIONS = _METAL_=1 SWIFTPM_BUNDLE=\"com.apple.mlx.Cmlx\" MLX_VERSION=\"0.32.4\" MLX_USE_ACCELERATE=1 METAL_PATH=\"default.metallib\" ACCELERATE_NEW_LAPACK=1 From 375eb612d5903a0ed1809283cdb11145720182ad Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Fri, 23 Oct 2026 15:50:58 -0700 Subject: [PATCH 3/3] Build MLX with MLX_RING_SOURCE_IPS for the ring's outgoing connections The ring backend opens its outgoing connections without naming a source address, so macOS picks the interface from its routing table. With two Macs on a Thunderbolt Bridge, the general route for self-assigned 169.254 addresses can belong to Wi-Fi, and the connection to the other Mac then leaves over Wi-Fi and never arrives. The mlx submodule now points at PicoMLX/mlx pico/0.32.4: v0.32.4 plus MLX_RING_SOURCE_IPS, a comma-separated list of IPs that the ring binds its outgoing connections to, one for each address of the next rank, with ports the OS picks. When it isn't set, the ring behaves as before. A list that doesn't match the connections, or an empty one, fails before anything connects. CMake fetches the same commit. DistributedTests.testRingSourceIPsMustMatchTheConnections sets a list that is too long, then an empty one, as rank 1, which connects first. Without the check, both fail only once rank 1's connection attempts run out, with "Couldn't connect" instead. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 2 +- CMakeLists.txt | 6 ++++-- Source/Cmlx/mlx | 2 +- Tests/MLXTests/DistributedTests.swift | 31 +++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index 8407808e2..ce4a5445e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "submodules/mlx"] path = Source/Cmlx/mlx - url = https://github.com/ml-explore/mlx + url = https://github.com/PicoMLX/mlx [submodule "submodules/mlx-c"] path = Source/Cmlx/mlx-c url = https://github.com/PicoMLX/mlx-c diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c0ed8cfd..7008f8669 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,10 +46,12 @@ set(MLX_BUILD_EXAMPLES OFF) set(MLX_BUILD_BENCHMARKS OFF) set(MLX_BUILD_PYTHON_BINDINGS OFF) +# mlx: v0.32.4 plus MLX_RING_SOURCE_IPS, which binds the ring's outgoing +# connections to given IPs, the same commit as the Source/Cmlx/mlx submodule FetchContent_Declare( mlx - GIT_REPOSITORY "https://github.com/ml-explore/mlx.git" - GIT_TAG "v0.32.4") + GIT_REPOSITORY "https://github.com/PicoMLX/mlx.git" + GIT_TAG "598b041ba7146e830a340a6317476815d42e7ab5") FetchContent_MakeAvailable(mlx) # mlx-c: 0.7.0 plus ml-explore/mlx-c#137 (gather_qmm for MLX v0.32.3), the same diff --git a/Source/Cmlx/mlx b/Source/Cmlx/mlx index 36969c094..598b041ba 160000 --- a/Source/Cmlx/mlx +++ b/Source/Cmlx/mlx @@ -1 +1 @@ -Subproject commit 36969c094354086e15d2a327a9c50feb20b9cf11 +Subproject commit 598b041ba7146e830a340a6317476815d42e7ab5 diff --git a/Tests/MLXTests/DistributedTests.swift b/Tests/MLXTests/DistributedTests.swift index 4946ea6bb..67774e51b 100644 --- a/Tests/MLXTests/DistributedTests.swift +++ b/Tests/MLXTests/DistributedTests.swift @@ -89,6 +89,37 @@ class DistributedTests: XCTestCase { XCTAssertThrowsError(try MLXDistributed.initialize(backend: .any)) } + /// The ring backend refuses `MLX_RING_SOURCE_IPS` unless it gives one IP for + /// each connection to the next rank, before it connects. Set but empty is + /// refused too, rather than read as not set. + /// + /// This is rank 1, which connects first: without the check it would fail + /// later, for another reason, once its connection attempts to rank 0 ran out. + func testRingSourceIPsMustMatchTheConnections() throws { + let hostfile = FileManager.default.temporaryDirectory + .appendingPathComponent("ring-hostfile-\(UUID().uuidString).json") + try JSONSerialization.data(withJSONObject: [["127.0.0.1:1"], ["127.0.0.1:2"]]) + .write(to: hostfile) + setenv("MLX_HOSTFILE", hostfile.path, 1) + setenv("MLX_RANK", "1", 1) + defer { + unsetenv("MLX_HOSTFILE") + unsetenv("MLX_RANK") + unsetenv("MLX_RING_SOURCE_IPS") + try? FileManager.default.removeItem(at: hostfile) + } + + for sourceIPs in ["127.0.0.1,127.0.0.1", ""] { + setenv("MLX_RING_SOURCE_IPS", sourceIPs, 1) + XCTAssertThrowsError(try MLXDistributed.initialize(backend: .any), sourceIPs) { error in + guard case .caught(let message) = error as? MLXError else { + return XCTFail("unexpected error for \"\(sourceIPs)\": \(error)") + } + XCTAssertTrue(message.contains("MLX_RING_SOURCE_IPS"), "\"\(sourceIPs)\": \(message)") + } + } + } + func testSplitSingletonGroupThrows() throws { let group = try MLXDistributed.initialize() XCTAssertThrowsError(try group.split(color: 0))