diff --git a/CMakeLists.txt b/CMakeLists.txt index 01b329b2f2..89fd9f3225 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,29 @@ option(MLX_BUILD_GGUF "Include support for GGUF format" ON) option(MLX_BUILD_SAFETENSORS "Include support for safetensors format" ON) option(MLX_BUILD_PYTHON_STUBS "Build stub files for python bindings" ON) option(MLX_METAL_JIT "Use JIT compilation for Metal kernels" OFF) +# Highway SIMD kernels for the CPU backend, on by default for Linux x86-64. +if(MLX_BUILD_CPU + AND CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") + set(_MLX_USE_HIGHWAY_DEFAULT ON) +else() + set(_MLX_USE_HIGHWAY_DEFAULT OFF) +endif() +option(MLX_USE_HIGHWAY "Build the CPU backend's Highway SIMD kernels" + ${_MLX_USE_HIGHWAY_DEFAULT}) +# MLX_ENABLE_X86_SIMD (ml-explore/mlx#3019's name) sets it on any configure. +if(DEFINED MLX_ENABLE_X86_SIMD) + set(MLX_USE_HIGHWAY + ${MLX_ENABLE_X86_SIMD} + CACHE BOOL "Build the CPU backend's Highway SIMD kernels" FORCE) + unset(MLX_ENABLE_X86_SIMD CACHE) +endif() +set(MLX_HIGHWAY_SOURCE_DIR + "" + CACHE PATH "Path to a local Highway source checkout") +set(MLX_HIGHWAY_GIT_TAG + "1.4.0" + CACHE STRING "Highway git tag or commit used when fetching Highway") option(MLX_USE_CCACHE "Use CCache for compilation cache when available" ON) option(MLX_EXPORT_ALL_SYMBOLS "Export all symbols in the library" OFF) option(BUILD_SHARED_LIBS "Build mlx as a shared library" OFF) diff --git a/mlx.pc.in b/mlx.pc.in index a202028b1f..df82f29388 100644 --- a/mlx.pc.in +++ b/mlx.pc.in @@ -11,6 +11,11 @@ @PACKAGE_INIT@ +if (@MLX_BUILD_CPU@ AND @MLX_USE_HIGHWAY@) + include(CMakeFindDependencyMacro) + find_dependency(hwy CONFIG PATHS "${PACKAGE_PREFIX_DIR}" NO_DEFAULT_PATH) +endif() + include(CMakeFindDependencyMacro) if(WIN32 AND @MLX_BUILD_CPU@ AND NOT TARGET MLX::OpenBLAS) diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index ddd6c53364..5bfdad4c06 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -6,6 +6,72 @@ else() set(CLANG FALSE) endif() +set(MLX_HIGHWAY_INCLUDE_DIR "") + +if(MLX_USE_HIGHWAY) + if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") + message(FATAL_ERROR "MLX_USE_HIGHWAY requires an x86-64 target") + endif() + + set(HWY_ENABLE_CONTRIB + OFF + CACHE BOOL "" FORCE) + set(HWY_ENABLE_EXAMPLES + OFF + CACHE BOOL "" FORCE) + set(HWY_ENABLE_INSTALL + ON + CACHE BOOL "" FORCE) + set(HWY_ENABLE_TESTS + OFF + CACHE BOOL "" FORCE) + set(HWY_FORCE_STATIC_LIBS + ON + CACHE BOOL "" FORCE) + if(MLX_HIGHWAY_SOURCE_DIR) + set(MLX_HIGHWAY_INCLUDE_DIR ${MLX_HIGHWAY_SOURCE_DIR}) + add_subdirectory(${MLX_HIGHWAY_SOURCE_DIR} ${CMAKE_BINARY_DIR}/highway) + else() + FetchContent_Declare( + highway + GIT_REPOSITORY https://github.com/google/highway.git + GIT_TAG ${MLX_HIGHWAY_GIT_TAG} + GIT_SHALLOW TRUE + EXCLUDE_FROM_ALL) + FetchContent_MakeAvailable(highway) + set(MLX_HIGHWAY_INCLUDE_DIR ${highway_SOURCE_DIR}) + endif() + if(NOT TARGET hwy) + message(FATAL_ERROR "MLX_USE_HIGHWAY requires Highway target hwy") + endif() + if(NOT TARGET hwy::hwy) + add_library(hwy::hwy ALIAS hwy) + endif() + + set(MLX_HIGHWAY_TARGET_DEFINITIONS HWY_DISABLE_PCLMUL_AES) + if(MSVC AND NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") + # Highway marks its AVX3-family targets broken for MSVC. Mirror that policy + # here by using Highway's target-filtering define. + set(MLX_HIGHWAY_DISABLED_AVX3_TARGETS + "HWY_DISABLED_TARGETS=(HWY_AVX3+HWY_AVX3_DL+HWY_AVX3_ZEN4+HWY_AVX3_SPR+HWY_AVX10_2)" + ) + list(APPEND MLX_HIGHWAY_TARGET_DEFINITIONS + ${MLX_HIGHWAY_DISABLED_AVX3_TARGETS}) + endif() + + # Keep ISA flags out of the main MLX target. Clang/GCC use Highway's + # foreach-target attributes; MSVC uses per-target shims below because it needs + # /arch:AVX2 on AVX2 codegen to avoid slow SSE/AVX transitions. + target_compile_definitions(hwy PRIVATE ${MLX_HIGHWAY_TARGET_DEFINITIONS}) + # PUBLIC, since installed headers (fast_primitives.h, unary.h, binary.h) + # change with it. Highway's own definitions stay PRIVATE. + target_compile_definitions(mlx PUBLIC MLX_USE_HIGHWAY_KERNELS) + target_compile_definitions(mlx PRIVATE ${MLX_HIGHWAY_TARGET_DEFINITIONS}) + target_include_directories(mlx PRIVATE ${MLX_HIGHWAY_INCLUDE_DIR}) + target_link_libraries(mlx PRIVATE hwy::hwy) + message(STATUS "Highway: runtime-dispatched CPU kernels enabled") +endif() + set(COMPILE_DEPS ${PROJECT_SOURCE_DIR}/mlx/types/half_types.h ${PROJECT_SOURCE_DIR}/mlx/types/fp16.h @@ -76,6 +142,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/masked_mm.cpp ${CMAKE_CURRENT_SOURCE_DIR}/primitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/quantized.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/precision.cpp ${CMAKE_CURRENT_SOURCE_DIR}/reduce.cpp ${CMAKE_CURRENT_SOURCE_DIR}/scan.cpp ${CMAKE_CURRENT_SOURCE_DIR}/select.cpp @@ -93,6 +160,87 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) +if(MLX_USE_HIGHWAY) + # Highway quantization dispatch and kernel counters. + target_sources( + mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway_backend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/highway_info.cpp) + + # #3019's native norms, RoPE and attention; without Highway, fast_primitives.h + # keeps their inline eval_cpu. + target_sources( + mlx + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/norms.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sdpa.cpp) + + # The thread pool the Highway kernels use. + add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/threading) + + if(MSVC AND NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(MLX_HIGHWAY_MSVC_DISPATCH_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/norms_highway_dispatch.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway_dispatch.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rope_highway_dispatch.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sdpa_highway_dispatch.cpp) + set(MLX_HIGHWAY_MSVC_TARGET_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/norms_highway.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rope_highway.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sdpa_highway.cpp) + + # Native MSVC needs per-target object builds because /arch:AVX2 is TU-wide. + function(mlx_add_highway_msvc_target target_name suffix) + add_library(${target_name} OBJECT ${MLX_HIGHWAY_MSVC_TARGET_SOURCES}) + target_link_libraries(${target_name} PRIVATE hwy::hwy) + target_include_directories( + ${target_name} PRIVATE ${PROJECT_SOURCE_DIR} ${MLX_HIGHWAY_INCLUDE_DIR}) + target_compile_definitions( + ${target_name} + PRIVATE MLX_USE_HIGHWAY_KERNELS + ${MLX_HIGHWAY_TARGET_DEFINITIONS} + MLX_HIGHWAY_MANUAL_TARGET + MLX_HIGHWAY_TARGET_SUFFIX=${suffix} + HWY_COMPILE_ONLY_STATIC + NOMINMAX + WIN32_LEAN_AND_MEAN + FMT_UNICODE=0) + if(BUILD_SHARED_LIBS) + target_compile_definitions(${target_name} PRIVATE MLX_EXPORT) + else() + target_compile_definitions(${target_name} PRIVATE MLX_STATIC) + endif() + target_compile_options(${target_name} PRIVATE /bigobj /Zc:preprocessor) + endfunction() + + mlx_add_highway_msvc_target(mlx_highway_msvc_avx2 _avx2) + # Highway's AVX2 target assumes AVX2/BMI2/FMA/F16C. Limit /arch:AVX2 to the + # AVX2 target bodies; public dispatch wrappers stay baseline-safe and only + # call them after runtime CPU detection. + target_compile_options(mlx_highway_msvc_avx2 PRIVATE /arch:AVX2) + mlx_add_highway_msvc_target(mlx_highway_msvc_sse4 _sse4) + target_compile_definitions(mlx_highway_msvc_sse4 PRIVATE HWY_WANT_SSSE3=1 + HWY_WANT_SSE4=1) + mlx_add_highway_msvc_target(mlx_highway_msvc_ssse3 _ssse3) + target_compile_definitions(mlx_highway_msvc_ssse3 PRIVATE HWY_WANT_SSSE3=1) + mlx_add_highway_msvc_target(mlx_highway_msvc_sse2 _sse2) + + target_sources( + mlx + PRIVATE ${MLX_HIGHWAY_MSVC_DISPATCH_SOURCES} + $ + $ + $ + $) + else() + target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/norms_highway.cpp) + target_sources(mlx + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway.cpp) + target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/rope_highway.cpp) + target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sdpa_highway.cpp) + endif() +endif() + if(MLX_BUILD_ACCELERATE) target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/gemms/bnns.cpp) else() diff --git a/mlx/backend/cpu/binary.h b/mlx/backend/cpu/binary.h index 2eb4afc95b..956d0489ab 100644 --- a/mlx/backend/cpu/binary.h +++ b/mlx/backend/cpu/binary.h @@ -10,6 +10,9 @@ #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS namespace mlx::core { @@ -18,6 +21,13 @@ struct VectorScalar { template void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *b; +#if defined(MLX_USE_HIGHWAY_KERNELS) + process_chunk(a, scalar, dst, static_cast(size)); + } + + template + static void process_chunk(const T* a, T scalar, U* dst, size_t size) { +#endif // MLX_USE_HIGHWAY_KERNELS constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::load(a), simd::Simd(scalar))); @@ -38,6 +48,13 @@ struct ScalarVector { template void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *a; +#if defined(MLX_USE_HIGHWAY_KERNELS) + process_chunk(scalar, b, dst, static_cast(size)); + } + + template + static void process_chunk(T scalar, const T* b, U* dst, size_t size) { +#endif // MLX_USE_HIGHWAY_KERNELS constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::Simd(scalar), simd::load(b))); @@ -57,6 +74,13 @@ template struct VectorVector { template void operator()(const T* a, const T* b, U* dst, size_t size) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + process_chunk(a, b, dst, static_cast(size)); + } + + template + static void process_chunk(const T* a, const T* b, U* dst, size_t size) { +#endif // MLX_USE_HIGHWAY_KERNELS constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::load(a), simd::load(b))); @@ -132,9 +156,12 @@ void binary_op_dispatch_dims( return; } +#if !defined(MLX_USE_HIGHWAY_KERNELS) ContiguousIterator a_it(shape, a_strides, dim - 3); ContiguousIterator b_it(shape, b_strides, dim - 3); +#endif // MLX_USE_HIGHWAY_KERNELS auto stride = out_strides[dim - 4]; +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (size_t elem = 0; elem < size; elem += stride) { binary_op_dims( a + a_it.loc, @@ -147,6 +174,65 @@ void binary_op_dispatch_dims( dim - 3); a_it.step(); b_it.step(); +#else + if (size == 0) { + return; + } + int64_t num_iterations = size / stride; + + // Check if parallelization is beneficial + auto& pool = cpu::ThreadPool::instance(); + int n_threads = + cpu::effective_threads(static_cast(size), pool.max_threads()); + + if (n_threads > 1 && num_iterations >= n_threads) { + // Parallel path for strided binary operations + pool.parallel_for(n_threads, [&](int tid, int nth) { + int64_t chunk = (num_iterations + nth - 1) / nth; + int64_t start_iter = chunk * tid; + int64_t end_iter = std::min(start_iter + chunk, num_iterations); + + if (start_iter >= end_iter) { + return; + } + + ContiguousIterator a_it(shape, a_strides, dim - 3); + ContiguousIterator b_it(shape, b_strides, dim - 3); + a_it.seek(start_iter); + b_it.seek(start_iter); + + for (int64_t iter = start_iter; iter < end_iter; ++iter) { + binary_op_dims( + a + a_it.loc, + b + b_it.loc, + out + iter * stride, + shape, + a_strides, + b_strides, + out_strides, + dim - 3); + a_it.step(); + b_it.step(); + } + }); + } else { + // Sequential path + ContiguousIterator a_it(shape, a_strides, dim - 3); + ContiguousIterator b_it(shape, b_strides, dim - 3); + for (int64_t elem = 0; elem < size; elem += stride) { + binary_op_dims( + a + a_it.loc, + b + b_it.loc, + out + elem, + shape, + a_strides, + b_strides, + out_strides, + dim - 3); + a_it.step(); + b_it.step(); + } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -164,19 +250,78 @@ void binary_op(const array& a, const array& b, array& out, BinaryOpType bopt) { // The full computation is scalar vector so delegate to the op if (bopt == BinaryOpType::ScalarVector) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) ScalarVector{}(a_ptr, b_ptr, out_ptr, b.data_size()); +#else + size_t size = b.data_size(); + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(size, pool.max_threads()); + if (n_threads > 1) { + T scalar = *a_ptr; + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size); + if (start < end) { + ScalarVector::template process_chunk( + scalar, b_ptr + start, out_ptr + start, end - start); + } + }); + } else { + ScalarVector{}(a_ptr, b_ptr, out_ptr, size); + } +#endif // MLX_USE_HIGHWAY_KERNELS return; } // The full computation is vector scalar so delegate to the op if (bopt == BinaryOpType::VectorScalar) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) VectorScalar{}(a_ptr, b_ptr, out_ptr, a.data_size()); +#else + size_t size = a.data_size(); + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(size, pool.max_threads()); + if (n_threads > 1) { + T scalar = *b_ptr; + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size); + if (start < end) { + VectorScalar::template process_chunk( + a_ptr + start, scalar, out_ptr + start, end - start); + } + }); + } else { + VectorScalar{}(a_ptr, b_ptr, out_ptr, size); + } +#endif // MLX_USE_HIGHWAY_KERNELS return; } // The full computation is vector vector so delegate to the op if (bopt == BinaryOpType::VectorVector) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) VectorVector{}(a_ptr, b_ptr, out_ptr, a.size()); +#else + size_t size = a.size(); + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(size, pool.max_threads()); + if (n_threads > 1) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size); + if (start < end) { + VectorVector::template process_chunk( + a_ptr + start, b_ptr + start, out_ptr + start, end - start); + } + }); + } else { + VectorVector{}(a_ptr, b_ptr, out_ptr, size); + } +#endif // MLX_USE_HIGHWAY_KERNELS return; } diff --git a/mlx/backend/cpu/copy.cpp b/mlx/backend/cpu/copy.cpp index acfc128974..17f7f4861d 100644 --- a/mlx/backend/cpu/copy.cpp +++ b/mlx/backend/cpu/copy.cpp @@ -7,6 +7,9 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/dtype_utils.h" #if defined(__aarch64__) @@ -312,10 +315,13 @@ void copy_general_general( auto size = std::accumulate( shape.begin(), shape.end(), int64_t{1}, std::multiplies()); +#if !defined(MLX_USE_HIGHWAY_KERNELS) ContiguousIterator in(shape, strides[0], ndim - 3); ContiguousIterator out(shape, strides[1], ndim - 3); +#endif // MLX_USE_HIGHWAY_KERNELS auto stride = std::accumulate( shape.end() - 3, shape.end(), 1, std::multiplies()); +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int64_t elem = 0; elem < size; elem += stride) { copy_dims( src_ptr + in.loc, @@ -326,6 +332,62 @@ void copy_general_general( ndim - 3); in.step(); out.step(); +#else + if (size == 0) { + return; + } + int64_t num_iterations = size / stride; + + // Check if parallelization is beneficial + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads( + static_cast(num_iterations * stride), pool.max_threads()); + + if (n_threads > 1 && num_iterations >= n_threads) { + // Parallel path: each thread processes a chunk of iterations + pool.parallel_for(n_threads, [&](int tid, int nth) { + int64_t chunk = (num_iterations + nth - 1) / nth; + int64_t start_iter = chunk * tid; + int64_t end_iter = std::min(start_iter + chunk, num_iterations); + + if (start_iter >= end_iter) { + return; + } + + // Create iterators and seek to starting position + ContiguousIterator in(shape, strides[0], ndim - 3); + ContiguousIterator out(shape, strides[1], ndim - 3); + in.seek(start_iter); + out.seek(start_iter); + + for (int64_t iter = start_iter; iter < end_iter; ++iter) { + copy_dims( + src_ptr + in.loc, + dst_ptr + out.loc, + shape, + strides[0], + strides[1], + ndim - 3); + in.step(); + out.step(); + } + }); + } else { + // Sequential path + ContiguousIterator in(shape, strides[0], ndim - 3); + ContiguousIterator out(shape, strides[1], ndim - 3); + for (int64_t elem = 0; elem < size; elem += stride) { + copy_dims( + src_ptr + in.loc, + dst_ptr + out.loc, + shape, + strides[0], + strides[1], + ndim - 3); + in.step(); + out.step(); + } +#endif // MLX_USE_HIGHWAY_KERNELS } } diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 765e9f539a..00aae41dc2 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -3,9 +3,19 @@ #include "mlx/backend/common/utils.h" #include "mlx/backend/cpu/gemm.h" #include "mlx/backend/cpu/lapack.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS namespace mlx::core { +#if defined(MLX_USE_HIGHWAY_KERNELS) +// Minimum batches per thread before parallelizing batch matmul +// Higher threshold than unary/binary ops because BLAS calls are heavier +constexpr int MIN_BATCHES_PER_THREAD = 4; + +#endif // MLX_USE_HIGHWAY_KERNELS template <> void matmul( const float* a, @@ -28,6 +38,7 @@ void matmul( size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int i = 0; i < batch_size; ++i) { cblas_sgemm( CblasRowMajor, @@ -44,6 +55,136 @@ void matmul( beta, out + M * N * i, ldc); +#else + // Check if parallelization over batches is beneficial + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / MIN_BATCHES_PER_THREAD)); + + if (n_threads > 1) { + // Parallel path: each thread handles a chunk of batches + // Note: For many small batches, BLAS threading has minimal benefit, + // so we parallelize ourselves without adjusting BLAS thread count. + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (batch_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, batch_size); + for (size_t i = start; i < end; ++i) { + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a + elem_to_loc(M * K * i, a_shape, a_strides), + lda, + b + elem_to_loc(K * N * i, b_shape, b_strides), + ldb, + beta, + out + M * N * i, + ldc); + } + }); + } else { + // Sequential batch path. When BLAS is pinned to 1 thread, parallelize + // large GEMMs by splitting M rows across our thread pool. + for (size_t i = 0; i < batch_size; ++i) { + const auto* a_ptr = a + elem_to_loc(M * K * i, a_shape, a_strides); + const auto* b_ptr = b + elem_to_loc(K * N * i, b_shape, b_strides); + auto* out_ptr = out + M * N * i; + + int m_threads = 1; + if (M >= 16 && M * N * K >= 65536) { + m_threads = + std::min(pool.max_threads(), std::max(1, static_cast(M / 8))); + } + + // Short inputs (M < 16) split by columns, so that a pinned OpenBLAS never + // leaves a large GEMM on one core. Each slice writes its own columns. + int col_threads = 1; + if (m_threads == 1 && M * N * K >= 65536) { + col_threads = + std::min(pool.max_threads(), std::max(1, static_cast(N / 64))); + } + if (col_threads > 1) { + cpu::highway_info::record_sgemm_column_split(); + pool.parallel_for(col_threads, [&](int tid, int nth) { + size_t n_chunk = (N + nth - 1) / nth; + size_t n_start = n_chunk * tid; + size_t n_end = std::min(n_start + n_chunk, N); + if (n_start < n_end) { + // Column n of op(B) is row n of a transposed B (stored N x K), and + // column n of B otherwise (stored K x N). + size_t b_offset = b_transposed ? n_start * ldb : n_start; + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + n_end - n_start, + K, + alpha, + a_ptr, + lda, + b_ptr + b_offset, + ldb, + beta, + out_ptr + n_start, + ldc); + } + }); + continue; + } + + if (m_threads > 1) { + pool.parallel_for(m_threads, [&](int tid, int nth) { + size_t m_chunk = (M + nth - 1) / nth; + size_t m_start = m_chunk * tid; + size_t m_end = std::min(m_start + m_chunk, M); + if (m_start < m_end) { + // When a_transposed: A stored as KxM (row-major), op(A)=A^T is MxK. + // Splitting M rows of A^T = splitting columns of stored A. + // Column offset = m_start; row offset = m_start * lda. + size_t a_offset = a_transposed ? m_start : m_start * lda; + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + alpha, + a_ptr + a_offset, + lda, + b_ptr, + ldb, + beta, + out_ptr + m_start * ldc, + ldc); + } + }); + } else { + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a_ptr, + lda, + b_ptr, + ldb, + beta, + out_ptr, + ldc); + } + } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -69,6 +210,7 @@ void matmul( size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int i = 0; i < batch_size; ++i) { cblas_dgemm( CblasRowMajor, @@ -85,6 +227,90 @@ void matmul( beta, out + M * N * i, ldc); +#else + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / MIN_BATCHES_PER_THREAD)); + + if (n_threads > 1) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (batch_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, batch_size); + for (size_t i = start; i < end; ++i) { + cblas_dgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a + elem_to_loc(M * K * i, a_shape, a_strides), + lda, + b + elem_to_loc(K * N * i, b_shape, b_strides), + ldb, + beta, + out + M * N * i, + ldc); + } + }); + } else { + for (size_t i = 0; i < batch_size; ++i) { + const auto* a_ptr = a + elem_to_loc(M * K * i, a_shape, a_strides); + const auto* b_ptr = b + elem_to_loc(K * N * i, b_shape, b_strides); + auto* out_ptr = out + M * N * i; + + int m_threads = 1; + if (M >= 16 && M * N * K >= 65536) { + m_threads = + std::min(pool.max_threads(), std::max(1, static_cast(M / 8))); + } + + if (m_threads > 1) { + pool.parallel_for(m_threads, [&](int tid, int nth) { + size_t m_chunk = (M + nth - 1) / nth; + size_t m_start = m_chunk * tid; + size_t m_end = std::min(m_start + m_chunk, M); + if (m_start < m_end) { + size_t a_offset = a_transposed ? m_start : m_start * lda; + cblas_dgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + alpha, + a_ptr + a_offset, + lda, + b_ptr, + ldb, + beta, + out_ptr + m_start * ldc, + ldc); + } + }); + } else { + cblas_dgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a_ptr, + lda, + b_ptr, + ldb, + beta, + out_ptr, + ldc); + } + } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -112,6 +338,7 @@ void matmul( auto calpha = static_cast(alpha); auto cbeta = static_cast(beta); +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int i = 0; i < batch_size; ++i) { cblas_cgemm( CblasRowMajor, @@ -128,6 +355,90 @@ void matmul( &cbeta, out + M * N * i, ldc); +#else + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / MIN_BATCHES_PER_THREAD)); + + if (n_threads > 1) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (batch_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, batch_size); + for (size_t i = start; i < end; ++i) { + cblas_cgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + &calpha, + a + elem_to_loc(M * K * i, a_shape, a_strides), + lda, + b + elem_to_loc(K * N * i, b_shape, b_strides), + ldb, + &cbeta, + out + M * N * i, + ldc); + } + }); + } else { + for (size_t i = 0; i < batch_size; ++i) { + const auto* a_ptr = a + elem_to_loc(M * K * i, a_shape, a_strides); + const auto* b_ptr = b + elem_to_loc(K * N * i, b_shape, b_strides); + auto* out_ptr = out + M * N * i; + + int m_threads = 1; + if (M >= 16 && M * N * K >= 65536) { + m_threads = + std::min(pool.max_threads(), std::max(1, static_cast(M / 8))); + } + + if (m_threads > 1) { + pool.parallel_for(m_threads, [&](int tid, int nth) { + size_t m_chunk = (M + nth - 1) / nth; + size_t m_start = m_chunk * tid; + size_t m_end = std::min(m_start + m_chunk, M); + if (m_start < m_end) { + size_t a_offset = a_transposed ? m_start : m_start * lda; + cblas_cgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + &calpha, + a_ptr + a_offset, + lda, + b_ptr, + ldb, + &cbeta, + out_ptr + m_start * ldc, + ldc); + } + }); + } else { + cblas_cgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + &calpha, + a_ptr, + lda, + b_ptr, + ldb, + &cbeta, + out_ptr, + ldc); + } + } +#endif // MLX_USE_HIGHWAY_KERNELS } } diff --git a/mlx/backend/cpu/gemms/simd_bf16.cpp b/mlx/backend/cpu/gemms/simd_bf16.cpp index 1948c64518..a5640c8731 100644 --- a/mlx/backend/cpu/gemms/simd_bf16.cpp +++ b/mlx/backend/cpu/gemms/simd_bf16.cpp @@ -1,8 +1,14 @@ // Copyright © 2025 Apple Inc. +#if !defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/common/utils.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/backend/cpu/gemm.h" +#if !defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/gemms/simd_gemm.h" +#else +#include "mlx/backend/cpu/gemms/simd_low_precision_gemm.h" +#endif // MLX_USE_HIGHWAY_KERNELS namespace mlx::core { @@ -23,6 +29,7 @@ void matmul( const Strides& a_strides, const Shape& b_shape, const Strides& b_strides) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto ndim = a_shape.size(); size_t M = a_shape[ndim - 2]; size_t N = b_shape[ndim - 1]; @@ -42,6 +49,24 @@ void matmul( alpha, beta); } +#else + detail::matmul_lowp( + a, + b, + out, + a_transposed, + b_transposed, + lda, + ldb, + ldc, + alpha, + beta, + batch_size, + a_shape, + a_strides, + b_shape, + b_strides); +#endif // MLX_USE_HIGHWAY_KERNELS } } // namespace mlx::core diff --git a/mlx/backend/cpu/gemms/simd_fp16.cpp b/mlx/backend/cpu/gemms/simd_fp16.cpp index b94523429a..7d00f6aa14 100644 --- a/mlx/backend/cpu/gemms/simd_fp16.cpp +++ b/mlx/backend/cpu/gemms/simd_fp16.cpp @@ -1,8 +1,14 @@ // Copyright © 2025 Apple Inc. +#if !defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/common/utils.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/backend/cpu/gemm.h" +#if !defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/gemms/simd_gemm.h" +#else +#include "mlx/backend/cpu/gemms/simd_low_precision_gemm.h" +#endif // MLX_USE_HIGHWAY_KERNELS namespace mlx::core { @@ -23,6 +29,7 @@ void matmul( const Strides& a_strides, const Shape& b_shape, const Strides& b_strides) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto ndim = a_shape.size(); size_t M = a_shape[ndim - 2]; size_t N = b_shape[ndim - 1]; @@ -42,6 +49,24 @@ void matmul( alpha, beta); } +#else + detail::matmul_lowp( + a, + b, + out, + a_transposed, + b_transposed, + lda, + ldb, + ldc, + alpha, + beta, + batch_size, + a_shape, + a_strides, + b_shape, + b_strides); +#endif // MLX_USE_HIGHWAY_KERNELS } } // namespace mlx::core diff --git a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h new file mode 100644 index 0000000000..0bd0eec137 --- /dev/null +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -0,0 +1,407 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/backend/common/utils.h" +#include "mlx/backend/cpu/gemm.h" +#include "mlx/backend/cpu/gemms/simd_gemm.h" +#include "mlx/backend/cpu/lapack.h" +#include "mlx/backend/cpu/scratch.h" +#include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" + +#include +#include +#include + +namespace mlx::core::detail { + +constexpr int LOWP_MIN_BATCHES_PER_THREAD = 4; + +// Thread-local scratch for low-precision <-> f32 conversion, borrowed through +// ScratchLease: no mmap/munmap cycles or page faults from repeated allocations. +inline std::vector& lowp_gemm_buffer() { + thread_local std::vector buf; + return buf; +} + +template +void lowp_to_f32(const T* src, float* dst, size_t n) { + constexpr int N = simd::max_size; + size_t i = 0; + for (; i + N <= n; i += N) { + simd::store(dst + i, simd::Simd(simd::load(src + i))); + } + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template +void f32_to_lowp(const float* src, T* dst, size_t n) { + constexpr int N = simd::max_size; + size_t i = 0; + for (; i + N <= n; i += N) { + simd::store(dst + i, simd::Simd(simd::load(src + i))); + } + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +// Fused low-precision GEMV: reads weights directly, converts in-register, and +// accumulates in f32. This avoids the extra memory traffic of materializing +// both low-precision inputs as f32 before calling BLAS. +template +void lowp_gemv( + const T* a, + const T* b, + T* out, + bool b_transposed, + size_t N, + size_t K, + size_t ldb, + float alpha, + float beta) { + constexpr int W = simd::max_size; + + if (b_transposed) { + // B is [N][K]: each row n is a K-element weight vector for output n. + for (size_t n = 0; n < N; n++) { + const T* b_row = b + n * ldb; + simd::Simd acc0(0.0f); + simd::Simd acc1(0.0f); + simd::Simd acc2(0.0f); + simd::Simd acc3(0.0f); + size_t k = 0; + for (; k + 4 * W <= K; k += 4 * W) { + auto a0 = simd::Simd(simd::load(a + k)); + auto b0 = simd::Simd(simd::load(b_row + k)); + acc0 = acc0 + a0 * b0; + auto a1 = simd::Simd(simd::load(a + k + W)); + auto b1 = simd::Simd(simd::load(b_row + k + W)); + acc1 = acc1 + a1 * b1; + auto a2 = simd::Simd(simd::load(a + k + 2 * W)); + auto b2 = simd::Simd(simd::load(b_row + k + 2 * W)); + acc2 = acc2 + a2 * b2; + auto a3 = simd::Simd(simd::load(a + k + 3 * W)); + auto b3 = simd::Simd(simd::load(b_row + k + 3 * W)); + acc3 = acc3 + a3 * b3; + } + for (; k + W <= K; k += W) { + auto av = simd::Simd(simd::load(a + k)); + auto bv = simd::Simd(simd::load(b_row + k)); + acc0 = acc0 + av * bv; + } + float acc = simd::sum(acc0 + acc1 + acc2 + acc3); + for (; k < K; k++) { + acc += static_cast(a[k]) * static_cast(b_row[k]); + } + if (beta != 0) { + out[n] = + static_cast(alpha * acc + beta * static_cast(out[n])); + } else { + out[n] = static_cast(alpha * acc); + } + } + } else { + // B is [K][N]: accumulate outer products a[k] * B[k][:]. + cpu::ScratchLease accum_scratch(lowp_gemm_buffer(), N); + float* accum = accum_scratch.data(); + if (beta != 0) { + for (size_t n = 0; n < N; n++) { + accum[n] = beta * static_cast(out[n]); + } + } else { + std::memset(accum, 0, N * sizeof(float)); + } + for (size_t k = 0; k < K; k++) { + float a_val = alpha * static_cast(a[k]); + auto a_broadcast = simd::Simd(a_val); + const T* b_row = b + k * ldb; + size_t n = 0; + for (; n + W <= N; n += W) { + auto bv = simd::Simd(simd::load(b_row + n)); + auto cv = simd::load(accum + n); + simd::store(accum + n, cv + a_broadcast * bv); + } + for (; n < N; n++) { + accum[n] += a_val * static_cast(b_row[n]); + } + } + for (size_t n = 0; n < N; n++) { + out[n] = static_cast(accum[n]); + } + } +} + +template +void lowp_gemv_threaded( + const T* a, + const T* b, + T* out, + bool b_transposed, + size_t N, + size_t K, + size_t ldb, + float alpha, + float beta) { + auto& pool = cpu::ThreadPool::instance(); + int n_threads = + std::min(pool.max_threads(), std::max(1, static_cast(N / 128))); + + if (n_threads > 1 && b_transposed) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (N + nth - 1) / nth; + size_t n_start = chunk * tid; + size_t n_end = std::min(n_start + chunk, N); + if (n_start < n_end) { + lowp_gemv( + a, + b + n_start * ldb, + out + n_start, + true, + n_end - n_start, + K, + ldb, + alpha, + beta); + } + }); + } else if (n_threads > 1 && !b_transposed) { + // Split N into ranges. Each thread accumulates its own output slice while + // iterating over all K rows of B. + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (N + nth - 1) / nth; + size_t n_start = chunk * tid; + size_t n_end = std::min(n_start + chunk, N); + if (n_start >= n_end) { + return; + } + + constexpr int W = simd::max_size; + size_t n_len = n_end - n_start; + cpu::ScratchLease accum_scratch(lowp_gemm_buffer(), n_len); + float* accum = accum_scratch.data(); + if (beta != 0) { + for (size_t n = 0; n < n_len; n++) { + accum[n] = beta * static_cast(out[n_start + n]); + } + } else { + std::memset(accum, 0, n_len * sizeof(float)); + } + for (size_t k = 0; k < K; k++) { + float a_val = alpha * static_cast(a[k]); + auto a_broadcast = simd::Simd(a_val); + const T* b_row = b + k * ldb + n_start; + size_t n = 0; + for (; n + W <= n_len; n += W) { + auto bv = simd::Simd(simd::load(b_row + n)); + auto cv = simd::load(accum + n); + simd::store(accum + n, cv + a_broadcast * bv); + } + for (; n < n_len; n++) { + accum[n] += a_val * static_cast(b_row[n]); + } + } + for (size_t n = 0; n < n_len; n++) { + out[n_start + n] = static_cast(accum[n]); + } + }); + } else { + lowp_gemv(a, b, out, b_transposed, N, K, ldb, alpha, beta); + } +} + +template +void matmul_lowp( + const T* a, + const T* b, + T* out, + bool a_transposed, + bool b_transposed, + size_t lda, + size_t ldb, + size_t ldc, + float alpha, + float beta, + size_t batch_size, + const Shape& a_shape, + const Strides& a_strides, + const Shape& b_shape, + const Strides& b_strides) { + auto ndim = a_shape.size(); + size_t M = a_shape[ndim - 2]; + size_t N = b_shape[ndim - 1]; + size_t K = a_shape[ndim - 1]; + + // A segmented operand can start inside a physical row. The last row + // ends at its last element, without the source row stride's trailing gap. + const size_t a_rows = a_transposed ? K : M; + const size_t a_columns = a_transposed ? M : K; + const size_t b_rows = b_transposed ? N : K; + const size_t b_columns = b_transposed ? K : N; + const size_t a_elems = (a_rows - 1) * lda + a_columns; + const size_t b_elems = (b_rows - 1) * ldb + b_columns; + const size_t out_elems = M * ldc; + + if (batch_size > 1) { + auto run_batches = [&](size_t start, + size_t end, + float* a_f32, + float* b_f32, + float* out_f32) { + for (size_t i = start; i < end; ++i) { + const auto* a_ptr = a + elem_to_loc(M * K * i, a_shape, a_strides); + const auto* b_ptr = b + elem_to_loc(K * N * i, b_shape, b_strides); + auto* out_ptr = out + M * N * i; + + lowp_to_f32(a_ptr, a_f32, a_elems); + lowp_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + lowp_to_f32(out_ptr, out_f32, out_elems); + } + + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a_f32, + lda, + b_f32, + ldb, + beta, + out_f32, + ldc); + + f32_to_lowp(out_f32, out_ptr, out_elems); + } + }; + + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / LOWP_MIN_BATCHES_PER_THREAD)); + + if (n_threads > 1) { + size_t buf_size = a_elems + b_elems + out_elems; + + pool.parallel_for(n_threads, [&](int tid, int nth) { + cpu::ScratchLease batch_scratch(lowp_gemm_buffer(), buf_size); + float* base = batch_scratch.data(); + float* a_f32 = base; + float* b_f32 = base + a_elems; + float* out_f32 = base + a_elems + b_elems; + + size_t chunk = (batch_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, batch_size); + run_batches(start, end, a_f32, b_f32, out_f32); + }); + } else { + cpu::ScratchLease batch_scratch( + lowp_gemm_buffer(), a_elems + b_elems + out_elems); + float* scratch = batch_scratch.data(); + run_batches( + 0, + batch_size, + scratch, + scratch + a_elems, + scratch + a_elems + b_elems); + } + } else { + for (size_t i = 0; i < batch_size; ++i) { + const auto* a_ptr = a + elem_to_loc(M * K * i, a_shape, a_strides); + const auto* b_ptr = b + elem_to_loc(K * N * i, b_shape, b_strides); + auto* out_ptr = out + M * N * i; + + if (M == 1 && (!a_transposed || lda == 1) && N * K >= 65536) { + lowp_gemv_threaded( + a_ptr, b_ptr, out_ptr, b_transposed, N, K, ldb, alpha, beta); + } else if (M * N * K >= 65536) { + cpu::ScratchLease gemm_scratch( + lowp_gemm_buffer(), a_elems + b_elems + out_elems); + float* a_f32 = gemm_scratch.data(); + float* b_f32 = a_f32 + a_elems; + float* out_f32 = b_f32 + b_elems; + + lowp_to_f32(a_ptr, a_f32, a_elems); + lowp_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + lowp_to_f32(out_ptr, out_f32, out_elems); + } + + auto& pool = cpu::ThreadPool::instance(); + int m_threads = 1; + if (M >= 16) { + m_threads = std::min( + pool.max_threads(), std::max(1, static_cast(M / 8))); + } + + if (m_threads > 1) { + pool.parallel_for(m_threads, [&](int tid, int nth) { + size_t m_chunk = (M + nth - 1) / nth; + size_t m_start = m_chunk * tid; + size_t m_end = std::min(m_start + m_chunk, M); + if (m_start < m_end) { + size_t a_offset = a_transposed ? m_start : m_start * lda; + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + alpha, + a_f32 + a_offset, + lda, + b_f32, + ldb, + beta, + out_f32 + m_start * ldc, + ldc); + } + }); + } else { + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + M, + N, + K, + alpha, + a_f32, + lda, + b_f32, + ldb, + beta, + out_f32, + ldc); + } + + f32_to_lowp(out_f32, out_ptr, out_elems); + } else { + simd_gemm( + a_ptr, + b_ptr, + out_ptr, + a_transposed, + b_transposed, + M, + N, + K, + lda, + ldb, + alpha, + beta); + } + } + } +} + +} // namespace mlx::core::detail diff --git a/mlx/backend/cpu/highway_info.cpp b/mlx/backend/cpu/highway_info.cpp new file mode 100644 index 0000000000..92615ff983 --- /dev/null +++ b/mlx/backend/cpu/highway_info.cpp @@ -0,0 +1,90 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/highway_info.h" + +#include + +#include "hwy/highway.h" +#include "hwy/targets.h" + +namespace mlx::core::cpu::highway_info { + +namespace { +constexpr int kFamilies = static_cast(Family::Count); +// A cache line per family: the kernels of different families run at once. +struct alignas(64) Counters { + std::atomic executed{0}; + std::atomic highway_calls{0}; + std::atomic fallback_calls{0}; +}; +Counters counters[kFamilies]; +std::atomic column_splits{0}; +} // namespace + +// HWY_TARGETS is what foreach_target.h compiles in every dispatched file of +// this build: they share one set of compiler flags and defines. +int64_t compiled_targets() { + return HWY_TARGETS; +} + +int64_t supported_targets() { + return hwy::SupportedTargets(); +} + +void set_targets_for_test(int64_t targets) { + hwy::SetSupportedTargetsForTest(targets); +} + +const char* target_name(int64_t target) { + return hwy::TargetName(target); +} + +FamilyStats stats(Family family) { + auto& c = counters[static_cast(family)]; + return { + c.executed.load(std::memory_order_relaxed), + c.highway_calls.load(std::memory_order_relaxed), + c.fallback_calls.load(std::memory_order_relaxed)}; +} + +void reset_stats() { + for (auto& c : counters) { + c.executed.store(0, std::memory_order_relaxed); + c.highway_calls.store(0, std::memory_order_relaxed); + c.fallback_calls.store(0, std::memory_order_relaxed); + } + column_splits.store(0, std::memory_order_relaxed); +} + +// Loads first: after the first call per target, both are reads. +void record(Family family, int64_t target) { + auto& c = counters[static_cast(family)]; + if ((c.executed.load(std::memory_order_relaxed) & target) != target) { + c.executed.fetch_or(target, std::memory_order_relaxed); + } + if (c.highway_calls.load(std::memory_order_relaxed) == 0) { + c.highway_calls.store(1, std::memory_order_relaxed); + } +} + +void record_fallback(Family family) { + auto& c = counters[static_cast(family)]; + if (c.fallback_calls.load(std::memory_order_relaxed) == 0) { + c.fallback_calls.store(1, std::memory_order_relaxed); + } +} + +uint64_t sgemm_column_splits() { + return column_splits.load(std::memory_order_relaxed); +} + +void record_sgemm_column_split() { + column_splits.fetch_add(1, std::memory_order_relaxed); +} + +} // namespace mlx::core::cpu::highway_info + +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/highway_info.h b/mlx/backend/cpu/highway_info.h new file mode 100644 index 0000000000..d3cce930a6 --- /dev/null +++ b/mlx/backend/cpu/highway_info.h @@ -0,0 +1,62 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "mlx/api.h" + +namespace mlx::core::cpu::highway_info { + +// Kernel families with dynamically dispatched Highway kernels. +enum class Family : int { + QmmAffineDequant = 0, + QmmAffineInt8, + QmmFp, + RmsNorm, + LayerNorm, + Rope, + Sdpa, + Count +}; + +// Highway targets compiled into this build's dispatched kernels (HWY_* bits). +MLX_API int64_t compiled_targets(); +// Highway targets this CPU supports, as dispatch sees them (after a test mask). +MLX_API int64_t supported_targets(); +// Restricts dispatch to `targets`, which must be supported; 0 restores the +// CPU's own set. For tests: process-wide, and not safe while kernels run. +MLX_API void set_targets_for_test(int64_t targets); +// Highway's name for one target bit, such as "AVX2"; "Unknown" for a bit it +// does not know. +MLX_API const char* target_name(int64_t target); + +// Since the last reset_stats(): `executed` ORs the targets whose kernels ran; +// the calls count dispatched kernels and undispatched fallbacks, up to 1. +struct FamilyStats { + int64_t executed; + uint64_t highway_calls; + uint64_t fallback_calls; +}; +MLX_API FamilyStats stats(Family family); +MLX_API void reset_stats(); + +MLX_API void record(Family family, int64_t target); +MLX_API void record_fallback(Family family); + +// fp32 GEMMs split by columns across the pool (gemms/cblas.cpp), since the +// last reset_stats(). +MLX_API uint64_t sgemm_column_splits(); +MLX_API void record_sgemm_column_split(); + +} // namespace mlx::core::cpu::highway_info + +// For the kernels, in HWY_NAMESPACE code, where HWY_TARGET is its target. Fully +// qualified: the kernels' own namespaces hold an unrelated `highway`. +#define MLX_HIGHWAY_RECORD(family) \ + ::mlx::core::cpu::highway_info::record( \ + ::mlx::core::cpu::highway_info::Family::family, HWY_TARGET) +#define MLX_HIGHWAY_RECORD_FALLBACK(family) \ + ::mlx::core::cpu::highway_info::record_fallback( \ + ::mlx::core::cpu::highway_info::Family::family) diff --git a/mlx/backend/cpu/highway_utils.h b/mlx/backend/cpu/highway_utils.h new file mode 100644 index 0000000000..40a6d53218 --- /dev/null +++ b/mlx/backend/cpu/highway_utils.h @@ -0,0 +1,157 @@ +// Copyright © 2026 Apple Inc. + +// This header is included once per Highway target by foreach_target.h; do not +// add an include guard. + +#include +#include + +#include "hwy/highway.h" +#include "mlx/types/half_types.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::highway { +namespace HWY_NAMESPACE { + +namespace hn = hwy::HWY_NAMESPACE; + +// Highway's emulated float16 -> float32 decodes exponent 31 as finite (inf as +// 65536); return inf or quiet NaN there. Same as simd/highway_simd.h's copy. +template +hn::Vec promote_f16(DF df, hn::Vec> v) { + const hn::RebindToUnsigned du; + const hn::Rebind du16; + const auto bits = hn::PromoteTo(du, hn::BitCast(du16, v)); + const auto mantissa = hn::And(bits, hn::Set(du, 0x3FFu)); + const auto special = + hn::Eq(hn::And(bits, hn::Set(du, 0x7C00u)), hn::Set(du, 0x7C00u)); + const auto quiet = hn::IfThenElseZero( + hn::Ne(mantissa, hn::Zero(du)), hn::Set(du, 0x400000u)); + const auto inf_nan = hn::Or( + hn::Or( + hn::ShiftLeft<16>(hn::And(bits, hn::Set(du, 0x8000u))), + hn::Set(du, 0x7F800000u)), + hn::Or(hn::ShiftLeft<13>(mantissa), quiet)); + return hn::IfThenElse( + hn::RebindMask(df, special), + hn::BitCast(df, inf_nan), + hn::PromoteTo(df, v)); +} + +template +hn::Vec load_typed_as_f32(DF df, const T* HWY_RESTRICT ptr, size_t idx) { + if constexpr (std::is_same_v) { + return hn::LoadU(df, ptr + idx); + } else if constexpr (std::is_same_v) { + const hn::Rebind df16; + return promote_f16( + df, + hn::LoadU(df16, reinterpret_cast(ptr) + idx)); + } else { +#if HWY_TARGET == HWY_SCALAR + const hn::Rebind dbf16; +#else + const hn::Repartition dbf16; +#endif + const hn::Half dbf16_half; + return hn::PromoteTo( + df, + hn::LoadU( + dbf16_half, reinterpret_cast(ptr) + idx)); + } +} + +template +void store_f32_as_typed(DF df, hn::Vec v, T* HWY_RESTRICT ptr, size_t idx) { + if constexpr (std::is_same_v) { + hn::StoreU(v, df, ptr + idx); + } else if constexpr (std::is_same_v) { + const hn::Rebind df16; + hn::StoreU( + hn::DemoteTo(df16, v), + df16, + reinterpret_cast(ptr) + idx); + } else { +#if HWY_TARGET == HWY_SCALAR + const hn::Rebind dbf16; +#else + const hn::Repartition dbf16; +#endif + const hn::Half dbf16_half; + hn::StoreU( + hn::DemoteTo(dbf16_half, v), + dbf16_half, + reinterpret_cast(ptr) + idx); + } +} + +template +void load_interleaved_typed_as_f32( + DF df, + const T* HWY_RESTRICT ptr, + size_t idx, + hn::Vec& x0, + hn::Vec& x1) { + if constexpr (std::is_same_v) { + hn::LoadInterleaved2(df, ptr + idx, x0, x1); + } else if constexpr (std::is_same_v) { + const hn::Rebind df16; + hn::Vec x0h; + hn::Vec x1h; + hn::LoadInterleaved2( + df16, reinterpret_cast(ptr) + idx, x0h, x1h); + x0 = promote_f16(df, x0h); + x1 = promote_f16(df, x1h); + } else { +#if HWY_TARGET == HWY_SCALAR + const hn::Rebind dbf16; +#else + const hn::Repartition dbf16; +#endif + const hn::Half dbf16_half; + hn::Vec x0h; + hn::Vec x1h; + hn::LoadInterleaved2( + dbf16_half, + reinterpret_cast(ptr) + idx, + x0h, + x1h); + x0 = hn::PromoteTo(df, x0h); + x1 = hn::PromoteTo(df, x1h); + } +} + +template +void store_interleaved_f32_as_typed( + DF df, + hn::Vec out0, + hn::Vec out1, + T* HWY_RESTRICT ptr, + size_t idx) { + if constexpr (std::is_same_v) { + hn::StoreInterleaved2(out0, out1, df, ptr + idx); + } else if constexpr (std::is_same_v) { + const hn::Rebind df16; + hn::StoreInterleaved2( + hn::DemoteTo(df16, out0), + hn::DemoteTo(df16, out1), + df16, + reinterpret_cast(ptr) + idx); + } else { +#if HWY_TARGET == HWY_SCALAR + const hn::Rebind dbf16; +#else + const hn::Repartition dbf16; +#endif + const hn::Half dbf16_half; + hn::StoreInterleaved2( + hn::DemoteTo(dbf16_half, out0), + hn::DemoteTo(dbf16_half, out1), + dbf16_half, + reinterpret_cast(ptr) + idx); + } +} + +} // namespace HWY_NAMESPACE +} // namespace mlx::core::highway +HWY_AFTER_NAMESPACE(); diff --git a/mlx/backend/cpu/indexing.cpp b/mlx/backend/cpu/indexing.cpp index 37d4aaac80..8f12714fb8 100644 --- a/mlx/backend/cpu/indexing.cpp +++ b/mlx/backend/cpu/indexing.cpp @@ -10,6 +10,9 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/slicing.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/dtype_utils.h" #include "mlx/primitives.h" @@ -89,12 +92,18 @@ void gather( const T* src_ptr = src.data(); T* dst_ptr = out.data(); +#if !defined(MLX_USE_HIGHWAY_KERNELS) std::vector its(inds.begin(), inds.end()); ContiguousIterator src_it; if (!can_copy && src.ndim() > 0) { src_it = ContiguousIterator(slice_sizes, src.strides(), src.ndim()); } +#else + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(out.size(), pool.max_threads()); +#endif // MLX_USE_HIGHWAY_KERNELS +#if !defined(MLX_USE_HIGHWAY_KERNELS) size_t out_idx = 0; for (int idx = 0; idx < ind_size; idx++) { size_t src_idx = 0; @@ -105,8 +114,65 @@ void gather( auto idx_val = offset_neg_idx(inds[ii].data()[idx_loc], src.shape(ax)); src_idx += (idx_val * src.strides()[ax]); +#else + if (n_threads > 1 && ind_size >= static_cast(n_threads)) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (ind_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, ind_size); + if (start >= end) + return; + + // Each thread creates its own iterators and advances to start position + std::vector my_its(inds.begin(), inds.end()); + for (size_t s = 0; s < start; s++) { + for (auto& it : my_its) + it.step(); + } + ContiguousIterator my_src_it; + if (!can_copy && src.ndim() > 0) { + my_src_it = ContiguousIterator(slice_sizes, src.strides(), src.ndim()); + } + + size_t out_idx = start * slice_size; + for (size_t idx = start; idx < end; idx++) { + size_t src_idx = 0; + for (int ii = 0; ii < inds.size(); ++ii) { + auto ax = axes[ii]; + auto idx_loc = my_its[ii].loc; + my_its[ii].step(); + auto idx_val = + offset_neg_idx(inds[ii].data()[idx_loc], src.shape(ax)); + src_idx += (idx_val * src.strides()[ax]); + } + + if (slice_size == 1) { + dst_ptr[out_idx++] = src_ptr[src_idx]; + } else if (can_copy) { + std::copy( + src_ptr + src_idx, + src_ptr + src_idx + slice_size, + dst_ptr + out_idx); + out_idx += slice_size; + } else { + for (int jj = 0; jj < slice_size; jj++) { + dst_ptr[out_idx++] = src_ptr[src_idx + my_src_it.loc]; + my_src_it.step(); + } + my_src_it.reset(); + } + } + }); + } else { + // Sequential path + std::vector its(inds.begin(), inds.end()); + ContiguousIterator src_it; + if (!can_copy && src.ndim() > 0) { + src_it = ContiguousIterator(slice_sizes, src.strides(), src.ndim()); +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) if (slice_size == 1) { dst_ptr[out_idx++] = src_ptr[src_idx]; } else if (can_copy) { @@ -117,8 +183,39 @@ void gather( for (int jj = 0; jj < slice_size; jj++) { dst_ptr[out_idx++] = src_ptr[src_idx + src_it.loc]; src_it.step(); +#else + size_t out_idx = 0; + for (size_t idx = 0; idx < ind_size; idx++) { + size_t src_idx = 0; + for (int ii = 0; ii < inds.size(); ++ii) { + auto ax = axes[ii]; + auto idx_loc = its[ii].loc; + its[ii].step(); + auto idx_val = + offset_neg_idx(inds[ii].data()[idx_loc], src.shape(ax)); + src_idx += (idx_val * src.strides()[ax]); +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) src_it.reset(); +#else + + if (slice_size == 1) { + dst_ptr[out_idx++] = src_ptr[src_idx]; + } else if (can_copy) { + std::copy( + src_ptr + src_idx, + src_ptr + src_idx + slice_size, + dst_ptr + out_idx); + out_idx += slice_size; + } else { + for (int jj = 0; jj < slice_size; jj++) { + dst_ptr[out_idx++] = src_ptr[src_idx + src_it.loc]; + src_it.step(); + } + src_it.reset(); + } +#endif // MLX_USE_HIGHWAY_KERNELS } } } @@ -198,10 +295,15 @@ void gather_axis( array& out, const int axis) { auto shape = remove_index(ind.shape(), axis); +#if !defined(MLX_USE_HIGHWAY_KERNELS) ContiguousIterator ind_it( shape, remove_index(ind.strides(), axis), src.ndim() - 1); ContiguousIterator src_it( shape, remove_index(src.strides(), axis), src.ndim() - 1); +#else + auto ind_strides_no_ax = remove_index(ind.strides(), axis); + auto src_strides_no_ax = remove_index(src.strides(), axis); +#endif // MLX_USE_HIGHWAY_KERNELS auto ind_ptr = ind.data(); auto src_ptr = src.data(); @@ -222,6 +324,7 @@ void gather_axis( } size_t stride_pre = size_post * ind_ax_size; +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (size_t i = 0; i < size_pre; i++) { for (size_t k = 0; k < size_post; k++) { for (int j = 0; j < ind_ax_size; ++j) { @@ -229,11 +332,73 @@ void gather_axis( ind_ptr[ind_it.loc + j * ind_ax_stride], src_ax_size); dst_ptr[k + j * dst_ax_stride] = src_ptr[src_it.loc + ind_val * src_ax_stride]; +#else + int ndim_minus_1 = src.ndim() - 1; + + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(out.size(), pool.max_threads()); + + if (n_threads > 1 && size_pre >= static_cast(n_threads)) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size_pre + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size_pre); + if (start >= end) + return; + + // Each thread creates its own iterators and advances to start position + ContiguousIterator my_ind_it(shape, ind_strides_no_ax, ndim_minus_1); + ContiguousIterator my_src_it(shape, src_strides_no_ax, ndim_minus_1); + // Advance iterators to start position + size_t advance = start * size_post; + for (size_t s = 0; s < advance; s++) { + my_ind_it.step(); + my_src_it.step(); +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) ind_it.step(); src_it.step(); +#else + + T* my_dst = dst_ptr + start * stride_pre; + for (size_t i = start; i < end; i++) { + for (size_t k = 0; k < size_post; k++) { + for (int j = 0; j < ind_ax_size; ++j) { + auto ind_val = offset_neg_idx( + ind_ptr[my_ind_it.loc + j * ind_ax_stride], src_ax_size); + my_dst[k + j * dst_ax_stride] = + src_ptr[my_src_it.loc + ind_val * src_ax_stride]; + } + my_ind_it.step(); + my_src_it.step(); + } + my_dst += stride_pre; + } + }); + } else { + // Sequential path + ContiguousIterator ind_it(shape, ind_strides_no_ax, ndim_minus_1); + ContiguousIterator src_it(shape, src_strides_no_ax, ndim_minus_1); + + T* dst = dst_ptr; + for (size_t i = 0; i < size_pre; i++) { + for (size_t k = 0; k < size_post; k++) { + for (int j = 0; j < ind_ax_size; ++j) { + auto ind_val = offset_neg_idx( + ind_ptr[ind_it.loc + j * ind_ax_stride], src_ax_size); + dst[k + j * dst_ax_stride] = + src_ptr[src_it.loc + ind_val * src_ax_stride]; + } + ind_it.step(); + src_it.step(); + } + dst += stride_pre; +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) dst_ptr += stride_pre; +#endif // MLX_USE_HIGHWAY_KERNELS } } diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp new file mode 100644 index 0000000000..04343d1111 --- /dev/null +++ b/mlx/backend/cpu/norms.cpp @@ -0,0 +1,850 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include +#include +#include + +#include "mlx/allocator.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/fast_primitives.h" +#include "mlx/transforms.h" +#include "mlx/utils.h" + +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/norms_highway.h" +#endif + +namespace mlx::core::fast { + +namespace { + +using namespace mlx::core::simd; + +// RMS Norm for a single row (float32): out = x * rsqrt(mean(x^2) + eps) * +// weight +void rms_norm_row_f32( + const float* x, + const float* weight, + float* out, + int width, + float eps, + bool has_weight) { + constexpr int N = max_size; + + // Step 1: Compute sum of squares + Simd vsum_sq(0.0f); + const float* ptr = x; + int s = width; + + while (s >= N) { + Simd vals = load(ptr); + vsum_sq = vsum_sq + vals * vals; + ptr += N; + s -= N; + } + + float sum_sq = sum(vsum_sq); + while (s-- > 0) { + float val = *ptr++; + sum_sq += val * val; + } + + // Step 2: Compute scale = rsqrt(mean + eps) + float mean_sq = sum_sq / width; + float scale = 1.0f / std::sqrt(mean_sq + eps); + + // Step 3: Apply scale and weight + ptr = x; + float* optr = out; + s = width; + + Simd vscale(scale); + if (has_weight) { + const float* wptr = weight; + while (s >= N) { + Simd vals = load(ptr); + Simd weights = load(wptr); + Simd result = vals * vscale * weights; + store(optr, result); + ptr += N; + wptr += N; + optr += N; + s -= N; + } + while (s-- > 0) { + *optr++ = *ptr++ * scale * *wptr++; + } + } else { + while (s >= N) { + Simd vals = load(ptr); + Simd result = vals * vscale; + store(optr, result); + ptr += N; + optr += N; + s -= N; + } + while (s-- > 0) { + *optr++ = *ptr++ * scale; + } + } +} + +// RMS Norm for fp16/bf16 - load as float via SIMD, compute in float32, and +// convert back. +template +void rms_norm_row_half( + const T* x, + const T* weight, + T* out, + int width, + float eps, + bool has_weight) { + constexpr int N = max_size; + + // Step 1: Compute sum of squares in float32 + Simd vsum_sq(0.0f); + const T* ptr = x; + int s = width; + + while (s >= N) { + Simd vals(load(ptr)); + vsum_sq = vsum_sq + vals * vals; + ptr += N; + s -= N; + } + + float sum_sq = sum(vsum_sq); + while (s-- > 0) { + float val = static_cast(*ptr++); + sum_sq += val * val; + } + + // Step 2: Compute scale = rsqrt(mean + eps) + float mean_sq = sum_sq / width; + float scale = 1.0f / std::sqrt(mean_sq + eps); + + // Step 3: Apply scale and weight + ptr = x; + T* optr = out; + s = width; + + Simd vscale(scale); + if (has_weight) { + const T* wptr = weight; + while (s >= N) { + Simd vals(load(ptr)); + Simd weights(load(wptr)); + Simd result = vals * vscale * weights; + store(optr, Simd(result)); + ptr += N; + wptr += N; + optr += N; + s -= N; + } + while (s-- > 0) { + float val = static_cast(*ptr++); + float w = static_cast(*wptr++); + *optr++ = static_cast(val * scale * w); + } + } else { + while (s >= N) { + Simd vals(load(ptr)); + Simd result = vals * vscale; + store(optr, Simd(result)); + ptr += N; + optr += N; + s -= N; + } + while (s-- > 0) { + float val = static_cast(*ptr++); + *optr++ = static_cast(val * scale); + } + } +} + +// Layer Norm for a single row (float32) +void layer_norm_row_f32( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + float eps, + bool has_weight, + bool has_bias) { + constexpr int N = max_size; + + // Step 1: Compute mean + Simd vsum(0.0f); + const float* ptr = x; + int s = width; + + while (s >= N) { + Simd vals = load(ptr); + vsum = vsum + vals; + ptr += N; + s -= N; + } + + float total = sum(vsum); + while (s-- > 0) { + total += *ptr++; + } + float mean = total / width; + + // Step 2: Compute variance + Simd vvar(0.0f); + Simd vmean(mean); + ptr = x; + s = width; + + while (s >= N) { + Simd vals = load(ptr); + Simd diff = vals - vmean; + vvar = vvar + diff * diff; + ptr += N; + s -= N; + } + + float variance = sum(vvar); + while (s-- > 0) { + float diff = *ptr++ - mean; + variance += diff * diff; + } + variance /= width; + + // Step 3: Compute scale = 1 / sqrt(var + eps) + float scale = 1.0f / std::sqrt(variance + eps); + + // Step 4: Apply normalization, weight, and bias + ptr = x; + float* optr = out; + s = width; + + Simd vscale(scale); + int i = 0; + while (s >= N) { + Simd vals = load(ptr); + Simd result = (vals - vmean) * vscale; + + if (has_weight) { + Simd weights = load(weight + i); + result = result * weights; + } + if (has_bias) { + Simd biases = load(bias + i); + result = result + biases; + } + + store(optr, result); + ptr += N; + optr += N; + s -= N; + i += N; + } + + while (s-- > 0) { + float val = *ptr++; + float result = (val - mean) * scale; + if (has_weight) { + result *= weight[i]; + } + if (has_bias) { + result += bias[i]; + } + *optr++ = result; + i++; + } +} + +// Layer Norm for fp16/bf16 - load as float via SIMD, compute in float32, and +// convert back. +template +void layer_norm_row_half( + const T* x, + const T* weight, + const T* bias, + T* out, + int width, + float eps, + bool has_weight, + bool has_bias) { + constexpr int N = max_size; + + // Step 1: Compute mean + Simd vsum(0.0f); + const T* ptr = x; + int s = width; + + while (s >= N) { + Simd vals(load(ptr)); + vsum = vsum + vals; + ptr += N; + s -= N; + } + + float total = sum(vsum); + while (s-- > 0) { + total += static_cast(*ptr++); + } + float mean = total / width; + + // Step 2: Compute variance + Simd vvar(0.0f); + Simd vmean(mean); + ptr = x; + s = width; + + while (s >= N) { + Simd vals(load(ptr)); + Simd diff = vals - vmean; + vvar = vvar + diff * diff; + ptr += N; + s -= N; + } + + float variance = sum(vvar); + while (s-- > 0) { + float diff = static_cast(*ptr++) - mean; + variance += diff * diff; + } + variance /= width; + + // Step 3: Compute scale = 1 / sqrt(var + eps) + float scale = 1.0f / std::sqrt(variance + eps); + + // Step 4: Apply normalization, weight, and bias + ptr = x; + T* optr = out; + s = width; + + Simd vscale(scale); + int i = 0; + while (s >= N) { + Simd vals(load(ptr)); + Simd result = (vals - vmean) * vscale; + + if (has_weight) { + Simd weights(load(weight + i)); + result = result * weights; + } + if (has_bias) { + Simd biases(load(bias + i)); + result = result + biases; + } + + store(optr, Simd(result)); + ptr += N; + optr += N; + s -= N; + i += N; + } + + while (s-- > 0) { + float val = static_cast(*ptr++); + float result = (val - mean) * scale; + if (has_weight) { + result *= static_cast(weight[i]); + } + if (has_bias) { + result += static_cast(bias[i]); + } + *optr++ = static_cast(result); + i++; + } +} + +void rms_norm_float( + const float* x, + const float* weight, + float* out, + int width, + int rows, + float eps, + bool has_weight) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + rms_norm_highway_float(x, weight, out, width, rows, eps, has_weight); +#else + for (int row = 0; row < rows; row++) { + rms_norm_row_f32( + x + row * width, weight, out + row * width, width, eps, has_weight); + } +#endif +} + +void layer_norm_float( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + layer_norm_highway_float( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); +#else + for (int row = 0; row < rows; row++) { + layer_norm_row_f32( + x + row * width, + weight, + bias, + out + row * width, + width, + eps, + has_weight, + has_bias); + } +#endif +} + +template +void rms_norm_half( + const T* x, + const T* weight, + T* out, + int width, + int rows, + float eps, + bool has_weight) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (std::is_same_v) { + rms_norm_highway_float16(x, weight, out, width, rows, eps, has_weight); + } else { + rms_norm_highway_bfloat16(x, weight, out, width, rows, eps, has_weight); + } +#else + for (int row = 0; row < rows; row++) { + rms_norm_row_half( + x + row * width, weight, out + row * width, width, eps, has_weight); + } +#endif +} + +template +void layer_norm_half( + const T* x, + const T* weight, + const T* bias, + T* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (std::is_same_v) { + layer_norm_highway_float16( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); + } else { + layer_norm_highway_bfloat16( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); + } +#else + for (int row = 0; row < rows; row++) { + layer_norm_row_half( + x + row * width, + weight, + bias, + out + row * width, + width, + eps, + has_weight, + has_bias); + } +#endif +} + +} // namespace + +void RMSNorm::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + // Types without a Highway kernel, such as float64, compose MLX's fallback. + if (inputs[0].dtype() != float32 && inputs[0].dtype() != float16 && + inputs[0].dtype() != bfloat16) { + MLX_HIGHWAY_RECORD_FALLBACK(RmsNorm); + auto results = fallback_(inputs); + eval(results); + for (size_t i = 0; i < outputs.size(); i++) { + outputs[i].copy_shared_buffer(results[i]); + } + return; + } + auto& in_x = inputs[0]; + array weight = inputs[1]; + auto& out = outputs[0]; + + // Non-contiguous inputs are copied to contiguous layout + array x = in_x; + if (!in_x.flags().contiguous || in_x.strides()[in_x.ndim() - 1] != 1) { + x = contiguous_copy_cpu(in_x, stream()); + cpu::get_command_encoder(stream()).add_temporary(x); + } + + // Allocate output with same layout as (contiguous) input + out.set_data( + allocator::malloc(x.data_size() * x.itemsize()), + x.data_size(), + x.strides(), + x.flags()); + + if (x.size() == 0) { + return; + } + int width = x.shape(-1); + int num_rows = x.data_size() / width; + bool has_weight = weight.ndim() > 0; + + auto& encoder = cpu::get_command_encoder(stream()); + // The kernels read the weight with stride 1. + if (has_weight && weight.strides()[0] != 1) { + weight = contiguous_copy_cpu(weight, stream()); + encoder.add_temporary(weight); + } + encoder.set_input_array(x); + if (has_weight) { + encoder.set_input_array(weight); + } + encoder.set_output_array(out); + + // Determine threading + auto& pool = cpu::ThreadPool::instance(); + int nth = std::min(pool.max_threads(), num_rows); + size_t total_elements = static_cast(num_rows) * width; + if (total_elements < cpu::MIN_TOTAL_ELEMENTS) { + nth = 1; + } + + float eps = eps_; + + switch (x.dtype()) { + case float32: { + const float* x_ptr = x.data(); + const float* w_ptr = has_weight ? weight.data() : nullptr; + float* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + rms_norm_float( + x_ptr + row_start * width, + w_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight); + }); + }); + } else { + encoder.dispatch([=]() { + rms_norm_float( + x_ptr, w_ptr, out_ptr, width, num_rows, eps, has_weight); + }); + } + break; + } + case float16: { + const float16_t* x_ptr = x.data(); + const float16_t* w_ptr = has_weight ? weight.data() : nullptr; + float16_t* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + rms_norm_half( + x_ptr + row_start * width, + w_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight); + }); + }); + } else { + encoder.dispatch([=]() { + rms_norm_half( + x_ptr, w_ptr, out_ptr, width, num_rows, eps, has_weight); + }); + } + break; + } + case bfloat16: { + const bfloat16_t* x_ptr = x.data(); + const bfloat16_t* w_ptr = + has_weight ? weight.data() : nullptr; + bfloat16_t* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + rms_norm_half( + x_ptr + row_start * width, + w_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight); + }); + }); + } else { + encoder.dispatch([=]() { + rms_norm_half( + x_ptr, w_ptr, out_ptr, width, num_rows, eps, has_weight); + }); + } + break; + } + default: + throw std::runtime_error("[RMSNorm::eval_cpu] Unsupported type"); + } +} + +void RMSNormVJP::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + // Use fallback for VJP - it's less performance critical + // The fallback returns unevaluated arrays, need to eval them + auto results = fallback_(inputs); + eval(results); + for (size_t i = 0; i < outputs.size(); i++) { + outputs[i].copy_shared_buffer(results[i]); + } +} + +void LayerNorm::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + // Types without a Highway kernel, such as float64, compose MLX's fallback. + if (inputs[0].dtype() != float32 && inputs[0].dtype() != float16 && + inputs[0].dtype() != bfloat16) { + MLX_HIGHWAY_RECORD_FALLBACK(LayerNorm); + auto results = fallback_(inputs); + eval(results); + for (size_t i = 0; i < outputs.size(); i++) { + outputs[i].copy_shared_buffer(results[i]); + } + return; + } + auto& in_x = inputs[0]; + array weight = inputs[1]; + array bias = inputs[2]; + auto& out = outputs[0]; + + // Non-contiguous inputs are copied to contiguous layout + array x = in_x; + if (!in_x.flags().contiguous || in_x.strides()[in_x.ndim() - 1] != 1) { + x = contiguous_copy_cpu(in_x, stream()); + cpu::get_command_encoder(stream()).add_temporary(x); + } + + // Allocate output with same layout as (contiguous) input + out.set_data( + allocator::malloc(x.data_size() * x.itemsize()), + x.data_size(), + x.strides(), + x.flags()); + + if (x.size() == 0) { + return; + } + int width = x.shape(-1); + int num_rows = x.data_size() / width; + bool has_weight = weight.ndim() > 0; + bool has_bias = bias.ndim() > 0; + + auto& encoder = cpu::get_command_encoder(stream()); + // The kernels read weight and bias with stride 1. + if (has_weight && weight.strides()[0] != 1) { + weight = contiguous_copy_cpu(weight, stream()); + encoder.add_temporary(weight); + } + if (has_bias && bias.strides()[0] != 1) { + bias = contiguous_copy_cpu(bias, stream()); + encoder.add_temporary(bias); + } + encoder.set_input_array(x); + if (has_weight) { + encoder.set_input_array(weight); + } + if (has_bias) { + encoder.set_input_array(bias); + } + encoder.set_output_array(out); + + // Determine threading + auto& pool = cpu::ThreadPool::instance(); + int nth = std::min(pool.max_threads(), num_rows); + size_t total_elements = static_cast(num_rows) * width; + if (total_elements < cpu::MIN_TOTAL_ELEMENTS) { + nth = 1; + } + + float eps = eps_; + + switch (x.dtype()) { + case float32: { + const float* x_ptr = x.data(); + const float* w_ptr = has_weight ? weight.data() : nullptr; + const float* b_ptr = has_bias ? bias.data() : nullptr; + float* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + layer_norm_float( + x_ptr + row_start * width, + w_ptr, + b_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight, + has_bias); + }); + }); + } else { + encoder.dispatch([=]() { + layer_norm_float( + x_ptr, + w_ptr, + b_ptr, + out_ptr, + width, + num_rows, + eps, + has_weight, + has_bias); + }); + } + break; + } + case float16: { + const float16_t* x_ptr = x.data(); + const float16_t* w_ptr = has_weight ? weight.data() : nullptr; + const float16_t* b_ptr = has_bias ? bias.data() : nullptr; + float16_t* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + layer_norm_half( + x_ptr + row_start * width, + w_ptr, + b_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight, + has_bias); + }); + }); + } else { + encoder.dispatch([=]() { + layer_norm_half( + x_ptr, + w_ptr, + b_ptr, + out_ptr, + width, + num_rows, + eps, + has_weight, + has_bias); + }); + } + break; + } + case bfloat16: { + const bfloat16_t* x_ptr = x.data(); + const bfloat16_t* w_ptr = + has_weight ? weight.data() : nullptr; + const bfloat16_t* b_ptr = has_bias ? bias.data() : nullptr; + bfloat16_t* out_ptr = out.data(); + + if (nth > 1) { + encoder.dispatch([=, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + int rows_per_thread = (num_rows + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, num_rows); + + layer_norm_half( + x_ptr + row_start * width, + w_ptr, + b_ptr, + out_ptr + row_start * width, + width, + row_end - row_start, + eps, + has_weight, + has_bias); + }); + }); + } else { + encoder.dispatch([=]() { + layer_norm_half( + x_ptr, + w_ptr, + b_ptr, + out_ptr, + width, + num_rows, + eps, + has_weight, + has_bias); + }); + } + break; + } + default: + throw std::runtime_error("[LayerNorm::eval_cpu] Unsupported type"); + } +} + +void LayerNormVJP::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + // Use fallback for VJP - it's less performance critical + // The fallback returns unevaluated arrays, need to eval them + auto results = fallback_(inputs); + eval(results); + for (size_t i = 0; i < outputs.size(); i++) { + outputs[i].copy_shared_buffer(results[i]); + } +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/norms_highway.cpp b/mlx/backend/cpu/norms_highway.cpp new file mode 100644 index 0000000000..d9809a6236 --- /dev/null +++ b/mlx/backend/cpu/norms_highway.cpp @@ -0,0 +1,727 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +// Normally this file is compiled directly and Highway emits its runtime +// dispatch targets. Native MSVC builds compile this file once per target with +// MLX_HIGHWAY_MANUAL_TARGET and MLX_HIGHWAY_TARGET_SUFFIX so the same kernels +// are emitted as one manually suffixed specialization. + +#include +#include + +#include "mlx/backend/cpu/highway_info.h" + +#if !defined(MLX_HIGHWAY_MANUAL_TARGET) +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/norms_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep +#endif + +#include "hwy/highway.h" +#include "mlx/backend/cpu/highway_utils.h" +#include "mlx/types/half_types.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::fast { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; +namespace hu = mlx::core::highway::HWY_NAMESPACE; +using hu::load_typed_as_f32; +using hu::store_f32_as_typed; + +// Float sums are made in blocks of sum_block elements, as in reduce.cpp. +constexpr int sum_block = 4096; + +void rms_norm_row_f32( + const float* HWY_RESTRICT x, + const float* HWY_RESTRICT weight, + float* HWY_RESTRICT out, + int width, + float eps, + int has_weight) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + float total = 0.0f; + int i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V sum_sq0 = hn::Zero(d); + V sum_sq1 = hn::Zero(d); + V sum_sq2 = hn::Zero(d); + V sum_sq3 = hn::Zero(d); + + for (; i + 4 * lanes <= end; i += 4 * lanes) { + const V vals0 = hn::LoadU(d, x + i); + const V vals1 = hn::LoadU(d, x + i + lanes); + const V vals2 = hn::LoadU(d, x + i + 2 * lanes); + const V vals3 = hn::LoadU(d, x + i + 3 * lanes); + sum_sq0 = hn::MulAdd(vals0, vals0, sum_sq0); + sum_sq1 = hn::MulAdd(vals1, vals1, sum_sq1); + sum_sq2 = hn::MulAdd(vals2, vals2, sum_sq2); + sum_sq3 = hn::MulAdd(vals3, vals3, sum_sq3); + } + V sum_sq = hn::Add(hn::Add(sum_sq0, sum_sq1), hn::Add(sum_sq2, sum_sq3)); + for (; i + lanes <= end; i += lanes) { + const V vals = hn::LoadU(d, x + i); + sum_sq = hn::MulAdd(vals, vals, sum_sq); + } + + float block = hn::ReduceSum(d, sum_sq); + for (; i < end; ++i) { + block += x[i] * x[i]; + } + total += block; + } + + const float scale = 1.0f / std::sqrt(total / width + eps); + const V vscale = hn::Set(d, scale); + + i = 0; + if (has_weight) { + for (; i + lanes <= width; i += lanes) { + const V vals = hn::LoadU(d, x + i); + const V weights = hn::LoadU(d, weight + i); + hn::StoreU(hn::Mul(hn::Mul(vals, vscale), weights), d, out + i); + } + for (; i < width; ++i) { + out[i] = x[i] * scale * weight[i]; + } + } else { + for (; i + lanes <= width; i += lanes) { + const V vals = hn::LoadU(d, x + i); + hn::StoreU(hn::Mul(vals, vscale), d, out + i); + } + for (; i < width; ++i) { + out[i] = x[i] * scale; + } + } +} + +template +void rms_norm_row_half( + const T* HWY_RESTRICT x, + const T* HWY_RESTRICT weight, + T* HWY_RESTRICT out, + int width, + float eps, + int has_weight) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + float total = 0.0f; + int i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V sum_sq0 = hn::Zero(d); + V sum_sq1 = hn::Zero(d); + V sum_sq2 = hn::Zero(d); + V sum_sq3 = hn::Zero(d); + + for (; i + 4 * lanes <= end; i += 4 * lanes) { + const V vals0 = load_typed_as_f32(d, x, i); + const V vals1 = load_typed_as_f32(d, x, i + lanes); + const V vals2 = load_typed_as_f32(d, x, i + 2 * lanes); + const V vals3 = load_typed_as_f32(d, x, i + 3 * lanes); + sum_sq0 = hn::MulAdd(vals0, vals0, sum_sq0); + sum_sq1 = hn::MulAdd(vals1, vals1, sum_sq1); + sum_sq2 = hn::MulAdd(vals2, vals2, sum_sq2); + sum_sq3 = hn::MulAdd(vals3, vals3, sum_sq3); + } + V sum_sq = hn::Add(hn::Add(sum_sq0, sum_sq1), hn::Add(sum_sq2, sum_sq3)); + for (; i + lanes <= end; i += lanes) { + const V vals = load_typed_as_f32(d, x, i); + sum_sq = hn::MulAdd(vals, vals, sum_sq); + } + + float block = hn::ReduceSum(d, sum_sq); + for (; i < end; ++i) { + const float val = static_cast(x[i]); + block += val * val; + } + total += block; + } + + const float scale = 1.0f / std::sqrt(total / width + eps); + const V vscale = hn::Set(d, scale); + + i = 0; + if (has_weight) { + for (; i + lanes <= width; i += lanes) { + const V vals = load_typed_as_f32(d, x, i); + const V weights = load_typed_as_f32(d, weight, i); + store_f32_as_typed(d, hn::Mul(hn::Mul(vals, vscale), weights), out, i); + } + for (; i < width; ++i) { + out[i] = static_cast( + static_cast(x[i]) * scale * static_cast(weight[i])); + } + } else { + for (; i + lanes <= width; i += lanes) { + const V vals = load_typed_as_f32(d, x, i); + store_f32_as_typed(d, hn::Mul(vals, vscale), out, i); + } + for (; i < width; ++i) { + out[i] = static_cast(static_cast(x[i]) * scale); + } + } +} + +void layer_norm_row_f32( + const float* HWY_RESTRICT x, + const float* HWY_RESTRICT weight, + const float* HWY_RESTRICT bias, + float* HWY_RESTRICT out, + int width, + float eps, + int has_weight, + int has_bias) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + float total = 0.0f; + int i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V sum0 = hn::Zero(d); + V sum1 = hn::Zero(d); + for (; i + 2 * lanes <= end; i += 2 * lanes) { + sum0 = hn::Add(sum0, hn::LoadU(d, x + i)); + sum1 = hn::Add(sum1, hn::LoadU(d, x + i + lanes)); + } + V sum = hn::Add(sum0, sum1); + for (; i + lanes <= end; i += lanes) { + sum = hn::Add(sum, hn::LoadU(d, x + i)); + } + + float block = hn::ReduceSum(d, sum); + for (; i < end; ++i) { + block += x[i]; + } + total += block; + } + const float mean = total / width; + + const V vmean = hn::Set(d, mean); + float variance = 0.0f; + i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V variance_sum0 = hn::Zero(d); + V variance_sum1 = hn::Zero(d); + for (; i + 2 * lanes <= end; i += 2 * lanes) { + const V diff0 = hn::Sub(hn::LoadU(d, x + i), vmean); + const V diff1 = hn::Sub(hn::LoadU(d, x + i + lanes), vmean); + variance_sum0 = hn::MulAdd(diff0, diff0, variance_sum0); + variance_sum1 = hn::MulAdd(diff1, diff1, variance_sum1); + } + V variance_sum = hn::Add(variance_sum0, variance_sum1); + for (; i + lanes <= end; i += lanes) { + const V diff = hn::Sub(hn::LoadU(d, x + i), vmean); + variance_sum = hn::MulAdd(diff, diff, variance_sum); + } + + float block = hn::ReduceSum(d, variance_sum); + for (; i < end; ++i) { + const float diff = x[i] - mean; + block += diff * diff; + } + variance += block; + } + variance /= width; + + const float scale = 1.0f / std::sqrt(variance + eps); + const V vscale = hn::Set(d, scale); + + i = 0; + for (; i + lanes <= width; i += lanes) { + V result = hn::Mul(hn::Sub(hn::LoadU(d, x + i), vmean), vscale); + if (has_weight) { + result = hn::Mul(result, hn::LoadU(d, weight + i)); + } + if (has_bias) { + result = hn::Add(result, hn::LoadU(d, bias + i)); + } + hn::StoreU(result, d, out + i); + } + + for (; i < width; ++i) { + float result = (x[i] - mean) * scale; + if (has_weight) { + result *= weight[i]; + } + if (has_bias) { + result += bias[i]; + } + out[i] = result; + } +} + +template +void layer_norm_row_half( + const T* HWY_RESTRICT x, + const T* HWY_RESTRICT weight, + const T* HWY_RESTRICT bias, + T* HWY_RESTRICT out, + int width, + float eps, + int has_weight, + int has_bias) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + float total = 0.0f; + int i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V sum0 = hn::Zero(d); + V sum1 = hn::Zero(d); + for (; i + 2 * lanes <= end; i += 2 * lanes) { + sum0 = hn::Add(sum0, load_typed_as_f32(d, x, i)); + sum1 = hn::Add(sum1, load_typed_as_f32(d, x, i + lanes)); + } + V sum = hn::Add(sum0, sum1); + for (; i + lanes <= end; i += lanes) { + sum = hn::Add(sum, load_typed_as_f32(d, x, i)); + } + + float block = hn::ReduceSum(d, sum); + for (; i < end; ++i) { + block += static_cast(x[i]); + } + total += block; + } + const float mean = total / width; + + const V vmean = hn::Set(d, mean); + float variance = 0.0f; + i = 0; + while (i < width) { + const int end = std::min(width, i + sum_block); + V variance_sum0 = hn::Zero(d); + V variance_sum1 = hn::Zero(d); + for (; i + 2 * lanes <= end; i += 2 * lanes) { + const V diff0 = hn::Sub(load_typed_as_f32(d, x, i), vmean); + const V diff1 = hn::Sub(load_typed_as_f32(d, x, i + lanes), vmean); + variance_sum0 = hn::MulAdd(diff0, diff0, variance_sum0); + variance_sum1 = hn::MulAdd(diff1, diff1, variance_sum1); + } + V variance_sum = hn::Add(variance_sum0, variance_sum1); + for (; i + lanes <= end; i += lanes) { + const V diff = hn::Sub(load_typed_as_f32(d, x, i), vmean); + variance_sum = hn::MulAdd(diff, diff, variance_sum); + } + + float block = hn::ReduceSum(d, variance_sum); + for (; i < end; ++i) { + const float diff = static_cast(x[i]) - mean; + block += diff * diff; + } + variance += block; + } + variance /= width; + + const float scale = 1.0f / std::sqrt(variance + eps); + const V vscale = hn::Set(d, scale); + + i = 0; + for (; i + lanes <= width; i += lanes) { + V result = hn::Mul(hn::Sub(load_typed_as_f32(d, x, i), vmean), vscale); + if (has_weight) { + result = hn::Mul(result, load_typed_as_f32(d, weight, i)); + } + if (has_bias) { + result = hn::Add(result, load_typed_as_f32(d, bias, i)); + } + store_f32_as_typed(d, result, out, i); + } + + for (; i < width; ++i) { + float result = (static_cast(x[i]) - mean) * scale; + if (has_weight) { + result *= static_cast(weight[i]); + } + if (has_bias) { + result += static_cast(bias[i]); + } + out[i] = static_cast(result); + } +} + +void RmsNormF32( + const float* HWY_RESTRICT x, + const float* HWY_RESTRICT weight, + float* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight) { + MLX_HIGHWAY_RECORD(RmsNorm); + for (int row = 0; row < rows; ++row) { + rms_norm_row_f32( + x + row * width, weight, out + row * width, width, eps, has_weight); + } +} + +template +void RmsNormHalf( + const T* HWY_RESTRICT x, + const T* HWY_RESTRICT weight, + T* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight) { + for (int row = 0; row < rows; ++row) { + rms_norm_row_half( + x + row * width, weight, out + row * width, width, eps, has_weight); + } +} + +void RmsNormF16( + const float16_t* HWY_RESTRICT x, + const float16_t* HWY_RESTRICT weight, + float16_t* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight) { + MLX_HIGHWAY_RECORD(RmsNorm); + RmsNormHalf(x, weight, out, width, rows, eps, has_weight); +} + +void RmsNormBF16( + const bfloat16_t* HWY_RESTRICT x, + const bfloat16_t* HWY_RESTRICT weight, + bfloat16_t* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight) { + MLX_HIGHWAY_RECORD(RmsNorm); + RmsNormHalf(x, weight, out, width, rows, eps, has_weight); +} + +void LayerNormF32( + const float* HWY_RESTRICT x, + const float* HWY_RESTRICT weight, + const float* HWY_RESTRICT bias, + float* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight, + int has_bias) { + MLX_HIGHWAY_RECORD(LayerNorm); + for (int row = 0; row < rows; ++row) { + layer_norm_row_f32( + x + row * width, + weight, + bias, + out + row * width, + width, + eps, + has_weight, + has_bias); + } +} + +template +void LayerNormHalf( + const T* HWY_RESTRICT x, + const T* HWY_RESTRICT weight, + const T* HWY_RESTRICT bias, + T* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight, + int has_bias) { + for (int row = 0; row < rows; ++row) { + layer_norm_row_half( + x + row * width, + weight, + bias, + out + row * width, + width, + eps, + has_weight, + has_bias); + } +} + +void LayerNormF16( + const float16_t* HWY_RESTRICT x, + const float16_t* HWY_RESTRICT weight, + const float16_t* HWY_RESTRICT bias, + float16_t* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight, + int has_bias) { + MLX_HIGHWAY_RECORD(LayerNorm); + LayerNormHalf(x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + +void LayerNormBF16( + const bfloat16_t* HWY_RESTRICT x, + const bfloat16_t* HWY_RESTRICT weight, + const bfloat16_t* HWY_RESTRICT bias, + bfloat16_t* HWY_RESTRICT out, + int width, + int rows, + float eps, + int has_weight, + int has_bias) { + MLX_HIGHWAY_RECORD(LayerNorm); + LayerNormHalf(x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + +} // namespace +} // namespace HWY_NAMESPACE +} // namespace mlx::core::fast +HWY_AFTER_NAMESPACE(); + +#if HWY_ONCE +namespace mlx::core::fast { + +#if defined(MLX_HIGHWAY_MANUAL_TARGET) + +#ifndef MLX_HIGHWAY_TARGET_SUFFIX +#error "MLX_HIGHWAY_TARGET_SUFFIX must be defined for manual Highway targets" +#endif + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) +#define MLX_HIGHWAY_TARGET_FUNC(name) \ + MLX_HIGHWAY_CONCAT(name, MLX_HIGHWAY_TARGET_SUFFIX) + +void MLX_HIGHWAY_TARGET_FUNC(rms_norm_highway_float)( + const float* x, + const float* weight, + float* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_STATIC_DISPATCH(RmsNormF32) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void MLX_HIGHWAY_TARGET_FUNC(rms_norm_highway_float16)( + const float16_t* x, + const float16_t* weight, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_STATIC_DISPATCH(RmsNormF16) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void MLX_HIGHWAY_TARGET_FUNC(rms_norm_highway_bfloat16)( + const bfloat16_t* x, + const bfloat16_t* weight, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_STATIC_DISPATCH(RmsNormBF16) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void MLX_HIGHWAY_TARGET_FUNC(layer_norm_highway_float)( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_STATIC_DISPATCH(LayerNormF32) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +void MLX_HIGHWAY_TARGET_FUNC(layer_norm_highway_float16)( + const float16_t* x, + const float16_t* weight, + const float16_t* bias, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_STATIC_DISPATCH(LayerNormF16) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +void MLX_HIGHWAY_TARGET_FUNC(layer_norm_highway_bfloat16)( + const bfloat16_t* x, + const bfloat16_t* weight, + const bfloat16_t* bias, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_STATIC_DISPATCH(LayerNormBF16) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +#undef MLX_HIGHWAY_TARGET_FUNC +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +#else + +HWY_EXPORT(RmsNormF32); +HWY_EXPORT(RmsNormF16); +HWY_EXPORT(RmsNormBF16); +HWY_EXPORT(LayerNormF32); +HWY_EXPORT(LayerNormF16); +HWY_EXPORT(LayerNormBF16); + +void rms_norm_highway_float( + const float* x, + const float* weight, + float* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_DYNAMIC_DISPATCH(RmsNormF32) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void rms_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_DYNAMIC_DISPATCH(RmsNormF16) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void rms_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + HWY_DYNAMIC_DISPATCH(RmsNormBF16) + (x, weight, out, width, rows, eps, has_weight ? 1 : 0); +} + +void layer_norm_highway_float( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_DYNAMIC_DISPATCH(LayerNormF32) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +void layer_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + const float16_t* bias, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_DYNAMIC_DISPATCH(LayerNormF16) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +void layer_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + const bfloat16_t* bias, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + HWY_DYNAMIC_DISPATCH(LayerNormBF16) + (x, + weight, + bias, + out, + width, + rows, + eps, + has_weight ? 1 : 0, + has_bias ? 1 : 0); +} + +#endif + +} // namespace mlx::core::fast +#endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/norms_highway.h b/mlx/backend/cpu/norms_highway.h new file mode 100644 index 0000000000..8e0cf4745b --- /dev/null +++ b/mlx/backend/cpu/norms_highway.h @@ -0,0 +1,69 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/types/half_types.h" + +namespace mlx::core::fast { + +void rms_norm_highway_float( + const float* x, + const float* weight, + float* out, + int width, + int rows, + float eps, + bool has_weight); + +void rms_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight); + +void rms_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight); + +void layer_norm_highway_float( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias); + +void layer_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + const float16_t* bias, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias); + +void layer_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + const bfloat16_t* bias, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias); + +} // namespace mlx::core::fast diff --git a/mlx/backend/cpu/norms_highway_dispatch.cpp b/mlx/backend/cpu/norms_highway_dispatch.cpp new file mode 100644 index 0000000000..5cb59d916d --- /dev/null +++ b/mlx/backend/cpu/norms_highway_dispatch.cpp @@ -0,0 +1,232 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/norms_highway.h" + +#include "hwy/highway.h" + +namespace mlx::core::fast { + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) + +using RmsNormFn = + void (*)(const float*, const float*, float*, int, int, float, bool); +using RmsNormF16Fn = void (*)( + const float16_t*, + const float16_t*, + float16_t*, + int, + int, + float, + bool); +using RmsNormBF16Fn = void (*)( + const bfloat16_t*, + const bfloat16_t*, + bfloat16_t*, + int, + int, + float, + bool); +using LayerNormFn = void (*)( + const float*, + const float*, + const float*, + float*, + int, + int, + float, + bool, + bool); +using LayerNormF16Fn = void (*)( + const float16_t*, + const float16_t*, + const float16_t*, + float16_t*, + int, + int, + float, + bool, + bool); +using LayerNormBF16Fn = void (*)( + const bfloat16_t*, + const bfloat16_t*, + const bfloat16_t*, + bfloat16_t*, + int, + int, + float, + bool, + bool); +#define MLX_DECLARE_NORMS_TARGET(suffix) \ + void MLX_HIGHWAY_CONCAT(rms_norm_highway_float, suffix)( \ + const float*, const float*, float*, int, int, float, bool); \ + void MLX_HIGHWAY_CONCAT(rms_norm_highway_float16, suffix)( \ + const float16_t*, const float16_t*, float16_t*, int, int, float, bool); \ + void MLX_HIGHWAY_CONCAT(rms_norm_highway_bfloat16, suffix)( \ + const bfloat16_t*, \ + const bfloat16_t*, \ + bfloat16_t*, \ + int, \ + int, \ + float, \ + bool); \ + void MLX_HIGHWAY_CONCAT(layer_norm_highway_float, suffix)( \ + const float*, \ + const float*, \ + const float*, \ + float*, \ + int, \ + int, \ + float, \ + bool, \ + bool); \ + void MLX_HIGHWAY_CONCAT(layer_norm_highway_float16, suffix)( \ + const float16_t*, \ + const float16_t*, \ + const float16_t*, \ + float16_t*, \ + int, \ + int, \ + float, \ + bool, \ + bool); \ + void MLX_HIGHWAY_CONCAT(layer_norm_highway_bfloat16, suffix)( \ + const bfloat16_t*, \ + const bfloat16_t*, \ + const bfloat16_t*, \ + bfloat16_t*, \ + int, \ + int, \ + float, \ + bool, \ + bool) + +MLX_DECLARE_NORMS_TARGET(_avx2); +MLX_DECLARE_NORMS_TARGET(_sse4); +MLX_DECLARE_NORMS_TARGET(_ssse3); +MLX_DECLARE_NORMS_TARGET(_sse2); + +#undef MLX_DECLARE_NORMS_TARGET + +namespace { + +struct NormsHighwayDispatch { + RmsNormFn rms_norm; + RmsNormF16Fn rms_norm_f16; + RmsNormBF16Fn rms_norm_bf16; + LayerNormFn layer_norm; + LayerNormF16Fn layer_norm_f16; + LayerNormBF16Fn layer_norm_bf16; +}; + +#define MLX_NORMS_DISPATCH(suffix) \ + NormsHighwayDispatch { \ + MLX_HIGHWAY_CONCAT(rms_norm_highway_float, suffix), \ + MLX_HIGHWAY_CONCAT(rms_norm_highway_float16, suffix), \ + MLX_HIGHWAY_CONCAT(rms_norm_highway_bfloat16, suffix), \ + MLX_HIGHWAY_CONCAT(layer_norm_highway_float, suffix), \ + MLX_HIGHWAY_CONCAT(layer_norm_highway_float16, suffix), \ + MLX_HIGHWAY_CONCAT(layer_norm_highway_bfloat16, suffix) \ + } + +const NormsHighwayDispatch& norms_dispatch() { + static const NormsHighwayDispatch dispatch = [] { + const int64_t targets = hwy::SupportedTargets(); + if (targets & HWY_AVX2) { + return MLX_NORMS_DISPATCH(_avx2); + } + if (targets & HWY_SSE4) { + return MLX_NORMS_DISPATCH(_sse4); + } + if (targets & HWY_SSSE3) { + return MLX_NORMS_DISPATCH(_ssse3); + } + return MLX_NORMS_DISPATCH(_sse2); + }(); + return dispatch; +} + +#undef MLX_NORMS_DISPATCH +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +} // namespace + +void rms_norm_highway_float( + const float* x, + const float* weight, + float* out, + int width, + int rows, + float eps, + bool has_weight) { + norms_dispatch().rms_norm(x, weight, out, width, rows, eps, has_weight); +} + +void rms_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + norms_dispatch().rms_norm_f16(x, weight, out, width, rows, eps, has_weight); +} + +void rms_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight) { + norms_dispatch().rms_norm_bf16(x, weight, out, width, rows, eps, has_weight); +} + +void layer_norm_highway_float( + const float* x, + const float* weight, + const float* bias, + float* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + norms_dispatch().layer_norm( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + +void layer_norm_highway_float16( + const float16_t* x, + const float16_t* weight, + const float16_t* bias, + float16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + norms_dispatch().layer_norm_f16( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + +void layer_norm_highway_bfloat16( + const bfloat16_t* x, + const bfloat16_t* weight, + const bfloat16_t* bias, + bfloat16_t* out, + int width, + int rows, + float eps, + bool has_weight, + bool has_bias) { + norms_dispatch().layer_norm_bf16( + x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/precision.cpp b/mlx/backend/cpu/precision.cpp new file mode 100644 index 0000000000..790e622087 --- /dev/null +++ b/mlx/backend/cpu/precision.cpp @@ -0,0 +1,49 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "mlx/backend/cpu/precision.h" + +#include +#include + +namespace mlx::core::cpu { + +namespace detail { +bool parse_quantized_int8(const char* value) { + return value != nullptr && std::atoi(value) != 0; +} + +bool quantized_float32_accumulation() { +#if defined(MLX_USE_HIGHWAY_KERNELS) + return true; +#else + return false; +#endif +} +} // namespace detail + +namespace { +std::atomic& int8_switch() { + static std::atomic enabled{ + detail::parse_quantized_int8(std::getenv("MLX_CPU_QUANTIZED_INT8"))}; + return enabled; +} +} // namespace + +bool quantized_int8() { + return int8_switch().load(std::memory_order_relaxed); +} + +void set_quantized_int8(bool enabled) { + int8_switch().store(enabled, std::memory_order_relaxed); +} + +bool quantized_int8_available() { +#if defined(MLX_USE_HIGHWAY_KERNELS) + return true; +#else + return false; +#endif +} + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/precision.h b/mlx/backend/cpu/precision.h new file mode 100644 index 0000000000..0a2ae248c3 --- /dev/null +++ b/mlx/backend/cpu/precision.h @@ -0,0 +1,43 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include "mlx/api.h" + +namespace mlx::core::cpu { + +// Whether affine quantized matmul may round activations to int8 (#3019's fast +// path). Off unless MLX_CPU_QUANTIZED_INT8 is a nonzero integer at first use. +MLX_API bool quantized_int8(); +// Process-wide. Set it only while no quantized matmul runs. +MLX_API void set_quantized_int8(bool enabled); + +// Whether this build has the int8 path at all (builds with Highway kernels). +// Where it does not, the switch changes nothing. +MLX_API bool quantized_int8_available(); + +namespace detail { +// As env::get_var reads MLX's variables: an integer, and nonzero is on. +MLX_API bool parse_quantized_int8(const char* value); +// For a test: whether transposed affine 2-, 4- and 8-bit quantized matmul sums +// bf16 and fp16 in float32, as it does with Highway. Other paths may not. +MLX_API bool quantized_float32_accumulation(); +// For tests: sets the int8 switch for a scope, and restores it at the end. +class QuantizedInt8Scope { + public: + explicit QuantizedInt8Scope(bool enabled) : saved_(quantized_int8()) { + set_quantized_int8(enabled); + } + ~QuantizedInt8Scope() { + set_quantized_int8(saved_); + } + QuantizedInt8Scope(const QuantizedInt8Scope&) = delete; + QuantizedInt8Scope& operator=(const QuantizedInt8Scope&) = delete; + + private: + bool saved_; +}; +} // namespace detail + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 023bb7b619..0147b3335a 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -6,6 +6,9 @@ #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/quantized_highway.h" +#endif #include "mlx/backend/cpu/simd/simd.h" #include "mlx/backend/cpu/unary.h" #include "mlx/backend/cpu/unary_ops.h" @@ -988,6 +991,10 @@ void fp_bs_qmm_dispatch( } } +} // namespace + +namespace cpu { + // An empty output has no work, and K = 0 gives an empty sum, which is 0. // Return true when this has set out. bool empty_qmm_cpu(const array& x, array& out, Stream stream) { @@ -1007,12 +1014,21 @@ bool empty_qmm_cpu(const array& x, array& out, Stream stream) { return true; } -} // namespace +} // namespace cpu void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { - if (empty_qmm_cpu(inputs[0], out, stream())) { + if (cpu::empty_qmm_cpu(inputs[0], out, stream())) { + return; + } +#if defined(MLX_USE_HIGHWAY_KERNELS) + // Keep the one-bit and mixed-scale contracts from the generic CPU kernels. + const bool use_generic = mode_ == QuantizationMode::Affine && + (bits_ == 1 || inputs[0].dtype() != inputs[2].dtype()); + if (!use_generic) { + cpu::quantized_matmul_highway(inputs, out, stream(), mode_, group_size_, bits_, transpose_); return; } +#endif auto& x_pre = inputs[0]; auto& w_pre = inputs[1]; auto& scales_pre = inputs[2]; @@ -1055,9 +1071,18 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { } void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { - if (empty_qmm_cpu(inputs[0], out, stream())) { + if (cpu::empty_qmm_cpu(inputs[0], out, stream())) { return; } +#if defined(MLX_USE_HIGHWAY_KERNELS) + // Keep the one-bit and mixed-scale contracts from the generic CPU kernels. + const bool use_generic = mode_ == QuantizationMode::Affine && + (bits_ == 1 || inputs[0].dtype() != inputs[2].dtype()); + if (!use_generic) { + cpu::gather_qmm_highway(inputs, out, stream(), mode_, group_size_, bits_, transpose_); + return; + } +#endif auto& x_pre = inputs[0]; auto& w_pre = inputs[1]; auto& scales_pre = inputs[2]; @@ -1347,6 +1372,12 @@ void dispatch_quantize( void fast::Quantize::eval_cpu( const std::vector& inputs, std::vector& outputs) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if (bits_ != 1) { + cpu::quantize_affine_highway(inputs, outputs, stream(), group_size_, bits_); + return; + } +#endif auto& encoder = cpu::get_command_encoder(stream()); auto w = ensure_row_contiguous(inputs[0], encoder, stream()); auto& out = outputs[0]; @@ -1397,6 +1428,7 @@ void fast::Quantize::eval_cpu( }); } +#if !defined(MLX_USE_HIGHWAY_KERNELS) void fast::ConvertFP8::eval_cpu( const std::vector& inputs, std::vector& outputs) { @@ -1438,7 +1470,7 @@ void fast::ConvertFP8::eval_cpu( } void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { - if (empty_qmm_cpu(inputs[0], out, stream())) { + if (cpu::empty_qmm_cpu(inputs[0], out, stream())) { return; } auto& encoder = cpu::get_command_encoder(stream()); @@ -1500,4 +1532,6 @@ void GatherQQMM::eval_cpu(const std::vector& inputs, array& out) { throw std::runtime_error("[GatherQQMM] NYI"); } +#endif // !defined(MLX_USE_HIGHWAY_KERNELS) + } // namespace mlx::core diff --git a/mlx/backend/cpu/quantized.h b/mlx/backend/cpu/quantized.h new file mode 100644 index 0000000000..97263426b4 --- /dev/null +++ b/mlx/backend/cpu/quantized.h @@ -0,0 +1,64 @@ +// Copyright © 2026 Apple Inc. +// +// Shared declarations for quantized matmul and implementation-specific helpers. + +#pragma once + +#include +#include + +#include "mlx/backend/cpu/simd/simd.h" + +namespace mlx::core { + +// Load S elements of type T from memory and return as Simd. +// For float, this is a direct SIMD load. For float16/bfloat16, implementation +// headers can specialize this for faster typed loads. +// +// Uses a helper struct to allow partial specialization by ISA without +// issues with if-constexpr instantiating non-existent Simd types. +template +struct LoadAsFloat { + static inline simd::Simd apply(const T* ptr) { + if constexpr (std::is_same_v) { + return simd::load(ptr); + } else { + alignas(64) float tmp[S]; + for (int i = 0; i < S; i++) { + tmp[i] = static_cast(ptr[i]); + } + return simd::load(tmp); + } + } +}; + +// Convenience wrapper: load S elements of T and convert to Simd. +// SIMD specializations are provided by implementation headers such as +// quantized_highway.h. +template +inline simd::Simd load_as_float(const T* ptr) { + return LoadAsFloat::apply(ptr); +} + +// Pre-quantized activation data, shared across threads for M==1 optimization. +// When passed to _qmm_t_simd_row, skips per-thread redundant quantization. +struct PreqAct { + const void* x_q; // int8_t* + const float* x_scales; + const float* x_group_sums; +}; + +// Forward declaration -- defined in quantized.cpp. +template +void _qmm_t_simd_row( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int n_start, + int n_end, + int K, + const PreqAct* preq = nullptr); + +} // namespace mlx::core diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp new file mode 100644 index 0000000000..a08225bae8 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -0,0 +1,1682 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +// Normally this file is compiled directly and Highway emits its runtime +// dispatch targets. Native MSVC builds compile this file once per target with +// MLX_HIGHWAY_MANUAL_TARGET and MLX_HIGHWAY_TARGET_SUFFIX so the same kernels +// are emitted as one manually suffixed specialization. + +#include +#include + +#include "mlx/backend/cpu/highway_info.h" + +#if !defined(MLX_HIGHWAY_MANUAL_TARGET) +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/quantized_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep +#endif + +#include "hwy/highway.h" +#include "mlx/backend/cpu/highway_utils.h" +#include "mlx/backend/cpu/quantized_highway.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; +namespace hu = mlx::core::highway::HWY_NAMESPACE; +using hu::load_typed_as_f32; + +// Highway's AVX3-family x86 targets use 512-bit vectors. +#if HWY_TARGET == HWY_AVX3 || HWY_TARGET == HWY_AVX3_DL || \ + HWY_TARGET == HWY_AVX3_ZEN4 || HWY_TARGET == HWY_AVX3_SPR || \ + HWY_TARGET == HWY_AVX10_2 +constexpr bool kHas512BitX86Vectors = true; +#else +constexpr bool kHas512BitX86Vectors = false; +#endif + +template +hn::Vec unpack_4bit_lanes(DU8 du8, const uint32_t* words) { +#if HWY_TARGET == HWY_AVX2 + const auto packed = + hn::LoadDup128(du8, reinterpret_cast(words)); +#else + const auto packed = hn::LoadN( + du8, reinterpret_cast(words), hn::Lanes(du8) / 2); +#endif + const auto mask = hn::Set(du8, uint8_t{0x0F}); + const auto lo = hn::And(packed, mask); + const auto hi = hn::And(hn::ShiftRight<4>(packed), mask); +#if HWY_MAX_BYTES == 16 + return hn::InterleaveLower(lo, hi); +#else + return hn::ConcatLowerLower( + du8, hn::InterleaveUpper(du8, lo, hi), hn::InterleaveLower(lo, hi)); +#endif +} + +template +hn::Vec unpack_packed_words(DU32 du32, const uint32_t* words) { + static_assert(bits == 4 || bits == 8); + constexpr int pack_factor = 32 / bits; + const auto lanes = hn::Lanes(du32); + const auto lane_idx = hn::Iota(du32, uint32_t{0}); + const auto elem_idx = + hn::And(lane_idx, hn::Set(du32, uint32_t{pack_factor - 1})); + const auto shifts = hn::Mul(elem_idx, hn::Set(du32, uint32_t{bits})); + const auto mask = hn::Set(du32, uint32_t{(1u << bits) - 1}); + + if (lanes == pack_factor) { + return hn::And(hn::Shr(hn::Set(du32, *words), shifts), mask); + } + + const int words_per_vec = static_cast(lanes) / pack_factor; + const auto packed = hn::LoadN(du32, words, words_per_vec); + auto word_idx = hn::Zero(du32); + if constexpr (bits == 4) { + word_idx = hn::ShiftRight<3>(lane_idx); + } else { + word_idx = hn::ShiftRight<2>(lane_idx); + } + const auto packed_for_lane = + hn::TableLookupLanes(packed, hn::IndicesFromVec(du32, word_idx)); + return hn::And(hn::Shr(packed_for_lane, shifts), mask); +} + +template +void qmm_t_int8_cols( + OutT* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int n, + int K) { + static_assert(bits == 4 || bits == 8); + + constexpr int pack_factor = 32 / bits; + const int groups_per_col = K / group_size; + const int packs_in_group = group_size / pack_factor; + const int packs_per_col = groups_per_col * packs_in_group; + + constexpr int lane_cap = + (kHas512BitX86Vectors && bits == 8 && group_size >= 64) ? 64 : 32; + const hn::CappedTag di8; + const hn::RebindToUnsigned du8; + const hn::Repartition di16; + const hn::Repartition di32; + const hn::Rebind df; + const size_t lanes = hn::Lanes(di8); + const int words_per_vec = static_cast(lanes) / pack_factor; + const auto ones16 = hn::Set(di16, int16_t{1}); + + hn::Vec accum_vec[NC]; + for (int c = 0; c < NC; ++c) { + accum_vec[c] = hn::Zero(df); + } + float bias_accum[NC] = {}; + + for (int g = 0; g < groups_per_col; ++g) { + // On some targets (EMU128, NEON) ReorderWidenMulAccumulate puts part of + // the sum in its sum1 argument. RearrangeToOddPlusEven adds the two parts. + hn::Vec dot_acc[NC]; + hn::Vec dot_acc1[NC]; + for (int c = 0; c < NC; ++c) { + dot_acc[c] = hn::Zero(di32); + dot_acc1[c] = hn::Zero(di32); + } + + const int8_t* x_group = x_q + g * group_size; + const uint32_t* w_group[NC]; + for (int c = 0; c < NC; ++c) { + w_group[c] = w + (n + c) * packs_per_col + g * packs_in_group; + } + for (int elem = 0; elem < group_size; elem += static_cast(lanes)) { + const auto x_vec = hn::Load(di8, x_group + elem); + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + hn::Vec w_vec; + if constexpr (bits == 4) { + w_vec = unpack_4bit_lanes(du8, w_group[c]); + w_group[c] += words_per_vec; + const auto prod16 = hn::SatWidenMulPairwiseAdd(di16, w_vec, x_vec); + dot_acc[c] = hn::ReorderWidenMulAccumulate( + di32, prod16, ones16, dot_acc[c], dot_acc1[c]); + } else { + const auto* w_bytes = reinterpret_cast(w_group[c]); + w_group[c] += words_per_vec; + w_vec = hn::LoadU(du8, w_bytes); + dot_acc[c] = + hn::SumOfMulQuadAccumulate(di32, w_vec, x_vec, dot_acc[c]); + } + } + } + + const float xs = x_scales[g]; + const float xgs = x_group_sums[g]; + for (int c = 0; c < NC; ++c) { + const size_t param_idx = static_cast(n + c) * groups_per_col + g; + const float scale_f = static_cast(scales[param_idx]); + const float bias_f = static_cast(biases[param_idx]); + const auto dot = hn::RearrangeToOddPlusEven(dot_acc[c], dot_acc1[c]); + accum_vec[c] = hn::MulAdd( + hn::Set(df, scale_f * xs), hn::ConvertTo(df, dot), accum_vec[c]); + bias_accum[c] += bias_f * xgs; + } + } + + for (int c = 0; c < NC; ++c) { + result[c] = + static_cast(hn::ReduceSum(df, accum_vec[c]) + bias_accum[c]); + } +} + +template +void dequant_row( + const uint32_t* HWY_RESTRICT w_row, + const float* HWY_RESTRICT scales_row, + const float* HWY_RESTRICT biases_row, + float* HWY_RESTRICT out, + int group_size, + int K) { + static_assert(bits == 4 || bits == 8); + constexpr int pack_factor = 32 / bits; + constexpr int lane_cap = kHas512BitX86Vectors ? 16 : (bits == 4 ? 8 : 4); + + const hn::CappedTag du; + const hn::Rebind df; + using VU = hn::Vec; + using VF = hn::Vec; + + const int lanes = static_cast(hn::Lanes(du)); + const VU bit_mask = hn::Set(du, (1u << bits) - 1); + const VU bit_width = hn::Set(du, bits); + + int k = 0; + const uint32_t* w_ptr = w_row; + for (int g = 0; g < K / group_size; ++g) { + const VF scale = hn::Set(df, scales_row[g]); + const VF bias = hn::Set(df, biases_row[g]); + + if (lanes >= pack_factor) { + const int words_per_vec = lanes / pack_factor; + for (int j = 0; j < group_size; j += lanes) { + const VU values = unpack_packed_words(du, w_ptr); + w_ptr += words_per_vec; + hn::StoreU( + hn::MulAdd(hn::ConvertTo(df, values), scale, bias), df, out + k); + k += lanes; + } + } else { + for (int j = 0; j < group_size; j += pack_factor) { + const VU packed = hn::Set(du, *w_ptr++); + for (int elem = 0; elem < pack_factor; elem += lanes) { + const VU shifts = hn::Mul(hn::Iota(du, elem), bit_width); + const VU values = hn::And(hn::Shr(packed, shifts), bit_mask); + hn::StoreU( + hn::MulAdd(hn::ConvertTo(df, values), scale, bias), + df, + out + k + elem); + } + k += pack_factor; + } + } + } +} + +template +void QuantizeActivationInt8Typed( + const T* HWY_RESTRICT x, + int K, + int group_size, + int8_t* HWY_RESTRICT x_q, + float* HWY_RESTRICT x_scales, + float* HWY_RESTRICT x_group_sums) { + const hn::ScalableTag df; + const hn::RebindToSigned di32; + const hn::Repartition di16; + const hn::Repartition di8; + using VF = hn::Vec; + + const size_t lanes = hn::Lanes(df); + alignas(64) int32_t q_tmp[16]; + const int groups = K / group_size; + for (int g = 0; g < groups; ++g) { + const size_t group_offset = static_cast(g) * group_size; + VF sum = hn::Zero(df); + VF amax = hn::Zero(df); + + for (int e = 0; e < group_size; e += static_cast(lanes)) { + const VF v = load_typed_as_f32(df, x, group_offset + e); + sum = hn::Add(sum, v); + amax = hn::Max(amax, hn::Abs(v)); + } + + x_group_sums[g] = hn::ReduceSum(df, sum); + const float max_value = hn::ReduceMax(df, amax); + const float inv_scale = max_value > 0.0f ? 127.0f / max_value : 0.0f; + x_scales[g] = max_value / 127.0f; + const VF inv = hn::Set(df, inv_scale); + + if (lanes == 16 && group_size % 64 == 0) { + for (int e = 0; e < group_size; e += 64) { + const auto q0 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e), inv)); + const auto q1 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 16), inv)); + const auto q2 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 32), inv)); + const auto q3 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 48), inv)); + hn::Store( + hn::OrderedDemote2To( + di8, + hn::OrderedDemote2To(di16, q0, q1), + hn::OrderedDemote2To(di16, q2, q3)), + di8, + x_q + group_offset + e); + } + } else if (lanes == 16) { + const hn::Half di8_half; + for (int e = 0; e < group_size; e += 32) { + const auto q0 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e), inv)); + const auto q1 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 16), inv)); + hn::Store( + hn::DemoteTo(di8_half, hn::OrderedDemote2To(di16, q0, q1)), + di8_half, + x_q + group_offset + e); + } + } else if (lanes == 8) { + for (int e = 0; e < group_size; e += 32) { + const auto q0 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e), inv)); + const auto q1 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 8), inv)); + const auto q2 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 16), inv)); + const auto q3 = hn::NearestInt( + hn::Mul(load_typed_as_f32(df, x, group_offset + e + 24), inv)); + hn::Store( + hn::OrderedDemote2To( + di8, + hn::OrderedDemote2To(di16, q0, q1), + hn::OrderedDemote2To(di16, q2, q3)), + di8, + x_q + group_offset + e); + } + } else { + for (int e = 0; e < group_size; e += static_cast(lanes)) { + const VF v = load_typed_as_f32(df, x, group_offset + e); + const auto q = hn::NearestInt(hn::Mul(v, inv)); + hn::StoreU(q, di32, q_tmp); + for (size_t lane = 0; lane < lanes; ++lane) { + const int32_t clamped = + std::min(127, std::max(-127, q_tmp[lane])); + x_q[group_offset + e + lane] = static_cast(clamped); + } + } + } + } +} + +void QuantizeActivationInt8( + const void* HWY_RESTRICT x, + QuantizedHighwayDType dtype, + int K, + int group_size, + int8_t* HWY_RESTRICT x_q, + float* HWY_RESTRICT x_scales, + float* HWY_RESTRICT x_group_sums) { + MLX_HIGHWAY_RECORD(QmmAffineInt8); + switch (dtype) { + case QuantizedHighwayDType::Float32: + QuantizeActivationInt8Typed( + static_cast(x), + K, + group_size, + x_q, + x_scales, + x_group_sums); + break; + case QuantizedHighwayDType::Float16: + QuantizeActivationInt8Typed( + static_cast(x), + K, + group_size, + x_q, + x_scales, + x_group_sums); + break; + case QuantizedHighwayDType::BFloat16: + QuantizeActivationInt8Typed( + static_cast(x), + K, + group_size, + x_q, + x_scales, + x_group_sums); + break; + } +} + +template +void QmmTInt8RowTyped( + float* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int n_start, + int n_end, + int K) { + int out = 0; + int n = n_start; + if constexpr (!kHas512BitX86Vectors) { + for (; n + 8 <= n_end; n += 8, out += 8) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } + } + for (; n + 4 <= n_end; n += 4, out += 4) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } + for (; n < n_end; ++n, ++out) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } +} + +template +void QmmTInt8RowForBits( + float* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int group_size, + int n_start, + int n_end, + int K) { + switch (group_size) { + case 32: + QmmTInt8RowTyped( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + n_start, + n_end, + K); + break; + case 64: + QmmTInt8RowTyped( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + n_start, + n_end, + K); + break; + case 128: + QmmTInt8RowTyped( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + n_start, + n_end, + K); + break; + default: + throw std::invalid_argument( + "Quantization group size must be 32, 64 or 128."); + } +} + +template +void QmmTInt8RowForDType( + float* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int bits, + int group_size, + int n_start, + int n_end, + int K) { + switch (bits) { + case 4: + QmmTInt8RowForBits( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n_start, + n_end, + K); + break; + case 8: + QmmTInt8RowForBits( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n_start, + n_end, + K); + break; + default: + throw std::invalid_argument("Quantization bits must be 4 or 8."); + } +} + +void QmmTInt8Row( + float* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const void* HWY_RESTRICT scales, + const void* HWY_RESTRICT biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K) { + MLX_HIGHWAY_RECORD(QmmAffineInt8); + switch (dtype) { + case QuantizedHighwayDType::Float32: + QmmTInt8RowForDType( + result, + x_q, + x_scales, + x_group_sums, + w, + static_cast(scales), + static_cast(biases), + bits, + group_size, + n_start, + n_end, + K); + break; + case QuantizedHighwayDType::Float16: + QmmTInt8RowForDType( + result, + x_q, + x_scales, + x_group_sums, + w, + static_cast(scales), + static_cast(biases), + bits, + group_size, + n_start, + n_end, + K); + break; + case QuantizedHighwayDType::BFloat16: + QmmTInt8RowForDType( + result, + x_q, + x_scales, + x_group_sums, + w, + static_cast(scales), + static_cast(biases), + bits, + group_size, + n_start, + n_end, + K); + break; + } +} + +struct QmmTInt8Prequantized { + const int8_t* x_q; + const float* x_scales; + const float* x_group_sums; +}; + +template +void QmmTInt8RowConverted( + T* HWY_RESTRICT result, + const int8_t* HWY_RESTRICT x_q, + const float* HWY_RESTRICT x_scales, + const float* HWY_RESTRICT x_group_sums, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int n_start, + int n_end, + int K) { + int out = 0; + int n = n_start; + if constexpr (!kHas512BitX86Vectors) { + for (; n + 8 <= n_end; n += 8, out += 8) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } + } + for (; n + 4 <= n_end; n += 4, out += 4) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } + for (; n < n_end; ++n, ++out) { + qmm_t_int8_cols( + result + out, x_q, x_scales, x_group_sums, w, scales, biases, n, K); + } +} + +template +void QmmTInt8RowFromActivation( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int n_start, + int n_end, + int K, + const QmmTInt8Prequantized* preq) { + constexpr int INT8_MAX_K = 16384; + constexpr int STACK_GROUPS = 128; + + const int groups_per_col = K / group_size; + alignas(64) int8_t x_q_stack[INT8_MAX_K]; + float x_scales_stack[STACK_GROUPS]; + float x_group_sums_stack[STACK_GROUPS]; + std::unique_ptr x_scales_heap; + std::unique_ptr x_group_sums_heap; + + const int8_t* x_q = nullptr; + const float* x_scales = nullptr; + const float* x_group_sums = nullptr; + if (preq) { + x_q = preq->x_q; + x_scales = preq->x_scales; + x_group_sums = preq->x_group_sums; + } else { + float* x_scales_w = x_scales_stack; + float* x_group_sums_w = x_group_sums_stack; + if (groups_per_col > STACK_GROUPS) { + x_scales_heap.reset(new float[groups_per_col]); + x_group_sums_heap.reset(new float[groups_per_col]); + x_scales_w = x_scales_heap.get(); + x_group_sums_w = x_group_sums_heap.get(); + } + QuantizeActivationInt8Typed( + x, K, group_size, x_q_stack, x_scales_w, x_group_sums_w); + x_q = x_q_stack; + x_scales = x_scales_w; + x_group_sums = x_group_sums_w; + } + + QmmTInt8RowConverted( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + n_start, + n_end, + K); +} + +template +bool QmmTInt8HighwayTyped( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const T* HWY_RESTRICT scales, + const T* HWY_RESTRICT biases, + int M, + int N, + int K) { + constexpr int INT8_MAX_K = 16384; + constexpr int STACK_GROUPS = 128; + if (!cpu::quantized_int8() || K > INT8_MAX_K) { + return false; + } + MLX_HIGHWAY_RECORD(QmmAffineInt8); + + auto& pool = cpu::ThreadPool::instance(); + const int min_cols_per_thread = (M == 1) ? 128 : 64; + const int n_threads = + std::min(pool.max_threads(), std::max(1, N / min_cols_per_thread)); + constexpr int CHUNK_COLS = 64; + const int n_chunks = (N + CHUNK_COLS - 1) / CHUNK_COLS; + alignas(64) std::atomic steal_counter{0}; + + if (n_threads > 1 && M == 1) { + const int groups_per_col = K / group_size; + alignas(64) int8_t x_q[INT8_MAX_K]; + float x_scales_stack[STACK_GROUPS]; + float x_group_sums_stack[STACK_GROUPS]; + std::unique_ptr x_scales_heap; + std::unique_ptr x_group_sums_heap; + float* x_scales = x_scales_stack; + float* x_group_sums = x_group_sums_stack; + if (groups_per_col > STACK_GROUPS) { + x_scales_heap.reset(new float[groups_per_col]); + x_group_sums_heap.reset(new float[groups_per_col]); + x_scales = x_scales_heap.get(); + x_group_sums = x_group_sums_heap.get(); + } + + QuantizeActivationInt8Typed( + x, K, group_size, x_q, x_scales, x_group_sums); + QmmTInt8Prequantized preq{x_q, x_scales, x_group_sums}; + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + const int n_start = std::min(my_chunk * CHUNK_COLS, N); + const int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + QmmTInt8RowFromActivation( + result + n_start, x, w, scales, biases, n_start, n_end, K, &preq); + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + return true; + } + + if (n_threads > 1) { + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + const int n_start = std::min(my_chunk * CHUNK_COLS, N); + const int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + for (int m = 0; m < M; ++m) { + QmmTInt8RowFromActivation( + result + m * N + n_start, + x + m * K, + w, + scales, + biases, + n_start, + n_end, + K, + nullptr); + } + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + } else { + for (int m = 0; m < M; ++m) { + QmmTInt8RowFromActivation( + result + m * N, x + m * K, w, scales, biases, 0, N, K, nullptr); + } + } + return true; +} + +template +bool QmmTInt8HighwayForDType( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const void* HWY_RESTRICT scales, + const void* HWY_RESTRICT biases, + int bits, + int group_size, + int M, + int N, + int K) { + auto* result_t = static_cast(result); + const auto* x_t = static_cast(x); + const auto* scales_t = static_cast(scales); + const auto* biases_t = static_cast(biases); + if (bits == 4) { + if (group_size == 32) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + if (group_size == 64) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + if (group_size == 128) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + } else if (bits == 8) { + if (group_size == 32) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + if (group_size == 64) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + if (group_size == 128) { + return QmmTInt8HighwayTyped( + result_t, x_t, w, scales_t, biases_t, M, N, K); + } + } + throw std::invalid_argument( + "Quantization bits must be 4 or 8 and group size must be 32, 64 or 128."); +} + +bool QmmTInt8( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const void* HWY_RESTRICT scales, + const void* HWY_RESTRICT biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K) { + switch (dtype) { + case QuantizedHighwayDType::Float32: + return QmmTInt8HighwayForDType( + result, x, w, scales, biases, bits, group_size, M, N, K); + case QuantizedHighwayDType::Float16: + return QmmTInt8HighwayForDType( + result, x, w, scales, biases, bits, group_size, M, N, K); + case QuantizedHighwayDType::BFloat16: + return QmmTInt8HighwayForDType( + result, x, w, scales, biases, bits, group_size, M, N, K); + } + return false; +} + +template +hn::Vec load_fp4_weight_values( + DF df, + const uint32_t* w, + int elem_off, + const float* fp4_lut) { + constexpr int pack_factor = 8; + const size_t lanes = hn::Lanes(df); + + if constexpr (hn::MaxLanes(DF{}) == 16) { + const hn::Half df_half; + const uint32_t* words = w + elem_off * 2; + const auto lo = load_fp4_weight_values(df_half, words, 0, fp4_lut); + const auto hi = load_fp4_weight_values(df_half, words + 1, 0, fp4_lut); + return hn::Combine(df, hi, lo); + } else if constexpr (hn::MaxLanes(DF{}) == 8) { + const hn::Rebind du32; + const auto packed = hn::Set(du32, *w); + const auto shifts = hn::Mul( + hn::Iota(du32, static_cast(elem_off * lanes)), + hn::Set(du32, uint32_t{4})); + const auto idx = + hn::And(hn::Shr(packed, shifts), hn::Set(du32, uint32_t{0x0F})); + const auto idx_lo = hn::And(idx, hn::Set(du32, uint32_t{0x07})); + const auto low = hn::TableLookupLanes( + hn::LoadU(df, fp4_lut), hn::IndicesFromVec(df, idx_lo)); + const auto high = hn::TableLookupLanes( + hn::LoadU(df, fp4_lut + 8), hn::IndicesFromVec(df, idx_lo)); + const auto high_mask = + hn::RebindMask(df, hn::Gt(idx, hn::Set(du32, uint32_t{7}))); + return hn::IfThenElse(high_mask, high, low); + } + + alignas(64) float tmp[pack_factor]; + const uint32_t word = *w; + const int base = elem_off * static_cast(lanes); + for (size_t lane = 0; lane < lanes; ++lane) { + tmp[lane] = fp4_lut[(word >> ((base + static_cast(lane)) * 4)) & 0xF]; + } + return hn::LoadU(df, tmp); +} + +template +hn::Vec load_fp8_weight_values( + DF df, + const uint32_t* w, + int elem_off, + const float* fp8_lut) { + const hn::Rebind du8; + const hn::Rebind du16; + const hn::Rebind du32; + const hn::Rebind df16; + const size_t lanes = hn::Lanes(df); + const auto* bytes = reinterpret_cast(w); + const int base = elem_off * static_cast(lanes); + const auto encoded = hn::LoadU(du8, bytes + base); + const auto encoded16 = hn::PromoteTo(du16, encoded); + const auto payload = + hn::ShiftLeft<7>(hn::And(encoded16, hn::Set(du16, 0x7F))); + const auto sign = hn::ShiftLeft<8>(hn::And(encoded16, hn::Set(du16, 0x80))); + const auto decoded = hn::Mul( + hn::PromoteTo(df, hn::BitCast(df16, hn::Or(payload, sign))), + hn::Set(df, 256.0f)); + // 0x7F and 0xFF are NaN, not ±480; a select avoids a per-lane table gather. + const auto low = hn::And(hn::PromoteTo(du32, encoded), hn::Set(du32, 0x7F)); + const auto is_nan = hn::RebindMask(df, hn::Eq(low, hn::Set(du32, 0x7F))); + return hn::IfThenElse(is_nan, hn::NaN(df), decoded); +} + +template +float dequantize_fp_scale( + uint8_t encoded, + float scale_factor, + const float* fp8_lut) { + if constexpr (group_size == 16) { + return fp8_lut[encoded] * scale_factor; + } else { + union FOrI { + bfloat16_t f; + uint16_t i; + } out; + out.i = encoded == 0 + ? 0x40 + : (encoded == 0xFF ? 0x7FC0 : (static_cast(encoded) << 7)); + return static_cast(out.f) * scale_factor; + } +} + +template +void fp_qmm_t_highway_cols( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* w_ptrs[NC], + const uint8_t* scales_ptrs[NC], + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + static_assert(bits == 4 || bits == 8); + static_assert(group_size == 16 || group_size == 32); + + constexpr int lane_cap = kHas512BitX86Vectors ? 16 : 8; + const hn::CappedTag df; + using VF = hn::Vec; + const int lanes = static_cast(hn::Lanes(df)); + constexpr int pack_factor = 32 / bits; + const int iters_per_word = (lanes >= pack_factor) ? 1 : pack_factor / lanes; + const int words_per_iter = (lanes >= pack_factor) ? lanes / pack_factor : 0; + + VF acc[NC]; + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + acc[c] = hn::Zero(df); + } + + for (int g = 0; g < K / group_size; ++g) { + float scale_f[NC]; + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + scale_f[c] = dequantize_fp_scale( + *scales_ptrs[c]++, scale_factor, fp8_lut); + } + + VF group_acc[NC]; + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + group_acc[c] = hn::Zero(df); + } + + const size_t group_offset = static_cast(g) * group_size; + HWY_UNROLL(4) + for (int elem = 0; elem < group_size; elem += lanes) { + const VF x_vec = load_typed_as_f32(df, x, group_offset + elem); + const int elem_off = + (lanes >= pack_factor) ? 0 : (elem / lanes) % iters_per_word; + + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + VF w_vec; + if constexpr (bits == 4) { + w_vec = load_fp4_weight_values(df, w_ptrs[c], elem_off, fp4_lut); + } else { + w_vec = load_fp8_weight_values(df, w_ptrs[c], elem_off, fp8_lut); + } + group_acc[c] = hn::MulAdd(x_vec, w_vec, group_acc[c]); + if (lanes >= pack_factor) { + w_ptrs[c] += words_per_iter; + } else if (elem_off == iters_per_word - 1) { + w_ptrs[c] += 1; + } + } + } + + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + acc[c] = hn::MulAdd(hn::Set(df, scale_f[c]), group_acc[c], acc[c]); + } + } + + HWY_UNROLL(4) + for (int c = 0; c < NC; ++c) { + result[c] = static_cast(hn::ReduceSum(df, acc[c])); + } +} + +template +void fp_qmm_t_highway_cols_dispatch( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* w_ptrs[4], + const uint8_t* scales_ptrs[4], + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + fp_qmm_t_highway_cols( + result, x, w_ptrs, scales_ptrs, K, scale_factor, fp4_lut, fp8_lut); +} + +template +void fp_qmm_t_highway_col_dispatch( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* w_ptrs[1], + const uint8_t* scales_ptrs[1], + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + fp_qmm_t_highway_cols( + result, x, w_ptrs, scales_ptrs, K, scale_factor, fp4_lut, fp8_lut); +} + +template +void FpQmmTHighwayRowTyped( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + const int pack_factor = 32 / bits; + const int groups_per_col = K / group_size; + const int packs_per_col = groups_per_col * (group_size / pack_factor); + + const uint32_t* w_base = w + n_start * packs_per_col; + const uint8_t* scales_base = scales + n_start * groups_per_col; + + int out = 0; + int n = n_start; + for (; n + 4 <= n_end; n += 4, out += 4) { + const uint32_t* wp[4]; + const uint8_t* sp[4]; + HWY_UNROLL(4) + for (int c = 0; c < 4; ++c) { + wp[c] = w_base + c * packs_per_col; + sp[c] = scales_base + c * groups_per_col; + } + fp_qmm_t_highway_cols_dispatch( + result + out, x, wp, sp, K, scale_factor, fp4_lut, fp8_lut); + w_base += 4 * packs_per_col; + scales_base += 4 * groups_per_col; + } + + for (; n < n_end; ++n, ++out) { + const uint32_t* wp[1] = {w_base}; + const uint8_t* sp[1] = {scales_base}; + fp_qmm_t_highway_col_dispatch( + result + out, x, wp, sp, K, scale_factor, fp4_lut, fp8_lut); + w_base += packs_per_col; + scales_base += groups_per_col; + } +} + +template +void FpQmmTHighwayTyped( + T* HWY_RESTRICT result, + const T* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + auto& pool = cpu::ThreadPool::instance(); + + const int min_cols_per_thread = (M == 1) ? 128 : 64; + const int n_threads = + std::min(pool.max_threads(), std::max(1, N / min_cols_per_thread)); + + if (n_threads > 1) { + constexpr int CHUNK_COLS = 64; + const int n_chunks = (N + CHUNK_COLS - 1) / CHUNK_COLS; + alignas(64) std::atomic steal_counter{0}; + steal_counter.store(n_threads, std::memory_order_relaxed); + + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + const int n_start = std::min(my_chunk * CHUNK_COLS, N); + const int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + for (int m = 0; m < M; ++m) { + FpQmmTHighwayRowTyped( + result + m * N + n_start, + x + m * K, + w, + scales, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + } + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + } else { + for (int m = 0; m < M; ++m) { + FpQmmTHighwayRowTyped( + result + m * N, + x + m * K, + w, + scales, + 0, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); + } + } +} + +template +void FpQmmTHighwayRowForDType( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + auto* result_t = static_cast(result); + const auto* x_t = static_cast(x); + if (bits == 8) { + FpQmmTHighwayRowTyped( + result_t, + x_t, + w, + scales, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + } else if (group_size == 16) { + FpQmmTHighwayRowTyped( + result_t, + x_t, + w, + scales, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + } else { + FpQmmTHighwayRowTyped( + result_t, + x_t, + w, + scales, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + } +} + +template +void FpQmmTHighwayForDType( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + auto* result_t = static_cast(result); + const auto* x_t = static_cast(x); + if (bits == 8) { + FpQmmTHighwayTyped( + result_t, x_t, w, scales, M, N, K, scale_factor, fp4_lut, fp8_lut); + } else if (group_size == 16) { + FpQmmTHighwayTyped( + result_t, x_t, w, scales, M, N, K, scale_factor, fp4_lut, fp8_lut); + } else { + FpQmmTHighwayTyped( + result_t, x_t, w, scales, M, N, K, scale_factor, fp4_lut, fp8_lut); + } +} + +void FpQmmTHighwayRow( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + MLX_HIGHWAY_RECORD(QmmFp); + switch (dtype) { + case QuantizedHighwayDType::Float32: + FpQmmTHighwayRowForDType( + result, + x, + w, + scales, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + case QuantizedHighwayDType::Float16: + FpQmmTHighwayRowForDType( + result, + x, + w, + scales, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + case QuantizedHighwayDType::BFloat16: + FpQmmTHighwayRowForDType( + result, + x, + w, + scales, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + } +} + +void FpQmmTHighway( + void* HWY_RESTRICT result, + const void* HWY_RESTRICT x, + const uint32_t* HWY_RESTRICT w, + const uint8_t* HWY_RESTRICT scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + MLX_HIGHWAY_RECORD(QmmFp); + switch (dtype) { + case QuantizedHighwayDType::Float32: + FpQmmTHighwayForDType( + result, + x, + w, + scales, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + case QuantizedHighwayDType::Float16: + FpQmmTHighwayForDType( + result, + x, + w, + scales, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + case QuantizedHighwayDType::BFloat16: + FpQmmTHighwayForDType( + result, + x, + w, + scales, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); + break; + } +} + +void DequantRow4Bit( + const uint32_t* HWY_RESTRICT w_row, + const float* HWY_RESTRICT scales_row, + const float* HWY_RESTRICT biases_row, + float* HWY_RESTRICT out, + int group_size, + int K) { + MLX_HIGHWAY_RECORD(QmmAffineDequant); + dequant_row<4>(w_row, scales_row, biases_row, out, group_size, K); +} + +void DequantRow8Bit( + const uint32_t* HWY_RESTRICT w_row, + const float* HWY_RESTRICT scales_row, + const float* HWY_RESTRICT biases_row, + float* HWY_RESTRICT out, + int group_size, + int K) { + MLX_HIGHWAY_RECORD(QmmAffineDequant); + dequant_row<8>(w_row, scales_row, biases_row, out, group_size, K); +} + +} // namespace +} // namespace HWY_NAMESPACE +} // namespace mlx::core +HWY_AFTER_NAMESPACE(); + +#if HWY_ONCE +namespace mlx::core { + +#if defined(MLX_HIGHWAY_MANUAL_TARGET) + +#ifndef MLX_HIGHWAY_TARGET_SUFFIX +#error "MLX_HIGHWAY_TARGET_SUFFIX must be defined for manual Highway targets" +#endif + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) +#define MLX_HIGHWAY_TARGET_FUNC(name) \ + MLX_HIGHWAY_CONCAT(name, MLX_HIGHWAY_TARGET_SUFFIX) + +void MLX_HIGHWAY_TARGET_FUNC(dequant_row_highway_4bit)( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + HWY_STATIC_DISPATCH(DequantRow4Bit) + (w_row, scales_row, biases_row, out, group_size, K); +} + +void MLX_HIGHWAY_TARGET_FUNC(dequant_row_highway_8bit)( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + HWY_STATIC_DISPATCH(DequantRow8Bit) + (w_row, scales_row, biases_row, out, group_size, K); +} + +void MLX_HIGHWAY_TARGET_FUNC(quantize_activation_int8_highway)( + const void* x, + QuantizedHighwayDType dtype, + int K, + int group_size, + int8_t* x_q, + float* x_scales, + float* x_group_sums) { + HWY_STATIC_DISPATCH(QuantizeActivationInt8) + (x, dtype, K, group_size, x_q, x_scales, x_group_sums); +} + +void MLX_HIGHWAY_TARGET_FUNC(qmm_t_int8_highway_row)( + float* result, + const int8_t* x_q, + const float* x_scales, + const float* x_group_sums, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K) { + HWY_STATIC_DISPATCH(QmmTInt8Row) + (result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + dtype, + bits, + group_size, + n_start, + n_end, + K); +} + +bool MLX_HIGHWAY_TARGET_FUNC(qmm_t_int8_highway)( + void* result, + const void* x, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K) { + return HWY_STATIC_DISPATCH(QmmTInt8)( + result, x, w, scales, biases, dtype, bits, group_size, M, N, K); +} + +void MLX_HIGHWAY_TARGET_FUNC(fp_qmm_t_highway_row)( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + HWY_STATIC_DISPATCH(FpQmmTHighwayRow) + (result, + x, + w, + scales, + dtype, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +void MLX_HIGHWAY_TARGET_FUNC(fp_qmm_t_highway)( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + HWY_STATIC_DISPATCH(FpQmmTHighway) + (result, + x, + w, + scales, + dtype, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +#undef MLX_HIGHWAY_TARGET_FUNC +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +#else + +HWY_EXPORT(DequantRow4Bit); +HWY_EXPORT(DequantRow8Bit); +HWY_EXPORT(QuantizeActivationInt8); +HWY_EXPORT(QmmTInt8Row); +HWY_EXPORT(QmmTInt8); +HWY_EXPORT(FpQmmTHighwayRow); +HWY_EXPORT(FpQmmTHighway); + +void dequant_row_highway_4bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + HWY_DYNAMIC_DISPATCH(DequantRow4Bit) + (w_row, scales_row, biases_row, out, group_size, K); +} + +void dequant_row_highway_8bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + HWY_DYNAMIC_DISPATCH(DequantRow8Bit) + (w_row, scales_row, biases_row, out, group_size, K); +} + +void quantize_activation_int8_highway( + const void* x, + QuantizedHighwayDType dtype, + int K, + int group_size, + int8_t* x_q, + float* x_scales, + float* x_group_sums) { + HWY_DYNAMIC_DISPATCH(QuantizeActivationInt8) + (x, dtype, K, group_size, x_q, x_scales, x_group_sums); +} + +void qmm_t_int8_highway_row( + float* result, + const int8_t* x_q, + const float* x_scales, + const float* x_group_sums, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K) { + HWY_DYNAMIC_DISPATCH(QmmTInt8Row) + (result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + dtype, + bits, + group_size, + n_start, + n_end, + K); +} + +bool qmm_t_int8_highway( + void* result, + const void* x, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K) { + return HWY_DYNAMIC_DISPATCH(QmmTInt8)( + result, x, w, scales, biases, dtype, bits, group_size, M, N, K); +} + +void fp_qmm_t_highway_row( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + HWY_DYNAMIC_DISPATCH(FpQmmTHighwayRow) + (result, + x, + w, + scales, + dtype, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +void fp_qmm_t_highway( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + HWY_DYNAMIC_DISPATCH(FpQmmTHighway) + (result, + x, + w, + scales, + dtype, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +#endif + +} // namespace mlx::core +#endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/quantized_highway.h b/mlx/backend/cpu/quantized_highway.h new file mode 100644 index 0000000000..a4d6e6ccf5 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway.h @@ -0,0 +1,339 @@ +// Copyright © 2026 Apple Inc. +// +// Highway implementations for quantized CPU helpers. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "mlx/backend/cpu/precision.h" +#include "mlx/backend/cpu/quantized.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/types/half_types.h" +#include "mlx/utils.h" + +namespace mlx::core { + +enum class QuantizationMode; + +namespace cpu { + +bool empty_qmm_cpu(const array& x, array& out, Stream stream); +void quantized_matmul_highway( + const std::vector& inputs, + array& out, + Stream stream, + QuantizationMode mode, + int group_size, + int bits, + bool transpose); +void gather_qmm_highway( + const std::vector& inputs, + array& out, + Stream stream, + QuantizationMode mode, + int group_size, + int bits, + bool transpose); +void quantize_affine_highway( + const std::vector& inputs, + std::vector& outputs, + Stream stream, + int group_size, + int bits); + +} // namespace cpu + +enum class QuantizedHighwayDType : uint8_t { + Float32, + Float16, + BFloat16, +}; + +template +constexpr QuantizedHighwayDType quantized_highway_dtype() { + if constexpr (std::is_same_v) { + return QuantizedHighwayDType::Float32; + } else if constexpr (std::is_same_v) { + return QuantizedHighwayDType::Float16; + } else if constexpr (std::is_same_v) { + return QuantizedHighwayDType::BFloat16; + } else { + static_assert( + std::is_same_v || std::is_same_v || + std::is_same_v, + "Unsupported Highway quantized dtype"); + } +} + +void dequant_row_highway_4bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K); + +void dequant_row_highway_8bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K); + +void quantize_activation_int8_highway( + const void* x, + QuantizedHighwayDType dtype, + int K, + int group_size, + int8_t* x_q, + float* x_scales, + float* x_group_sums); + +void qmm_t_int8_highway_row( + float* result, + const int8_t* x_q, + const float* x_scales, + const float* x_group_sums, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K); + +bool qmm_t_int8_highway( + void* result, + const void* x, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K); + +void fp_qmm_t_highway_row( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut); + +void fp_qmm_t_highway( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut); + +template +void _dequant_row_highway( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int K) { + if constexpr (bits == 4) { + dequant_row_highway_4bit(w_row, scales_row, biases_row, out, group_size, K); + } else if constexpr (bits == 8) { + dequant_row_highway_8bit(w_row, scales_row, biases_row, out, group_size, K); + } +} + +template +int try_batch_extract_multi_col( + const T*&, + const uint32_t* [NC], + simd::Simd>[NC], + int) { + return 0; +} + +template +bool try_int8_simd_row( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int n_start, + int n_end, + int K, + int groups_per_col, + int, + float* x_group_sums, + const PreqAct* preq) { + constexpr int INT8_MAX_K = 16384; + constexpr int STACK_GROUPS = 128; + + if constexpr (!((bits == 4 || bits == 8) && group_size >= 32)) { + return false; + } else { + if (!cpu::quantized_int8()) { + return false; + } + if (K > INT8_MAX_K) { + return false; + } + + const int n_cols = n_end - n_start; + if (!preq && n_cols < K) { + return false; + } + + alignas(64) int8_t x_q_local[INT8_MAX_K]; + float x_scales_stack[STACK_GROUPS]; + std::unique_ptr x_scales_heap; + + const int8_t* x_q = nullptr; + const float* x_scales = nullptr; + if (preq) { + x_q = static_cast(preq->x_q); + x_scales = preq->x_scales; + } else { + float* x_scales_w = x_scales_stack; + if (groups_per_col > STACK_GROUPS) { + x_scales_heap.reset(new float[groups_per_col]); + x_scales_w = x_scales_heap.get(); + } + quantize_activation_int8_highway( + x, + quantized_highway_dtype(), + K, + group_size, + x_q_local, + x_scales_w, + x_group_sums); + x_q = x_q_local; + x_scales = x_scales_w; + } + + constexpr int STACK_COLS = 128; + float result_stack[STACK_COLS]; + std::unique_ptr result_heap; + float* result_f32 = result_stack; + if (n_cols > STACK_COLS) { + result_heap.reset(new float[n_cols]); + result_f32 = result_heap.get(); + } + + qmm_t_int8_highway_row( + result_f32, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + quantized_highway_dtype(), + bits, + group_size, + n_start, + n_end, + K); + + for (int n = 0; n < n_cols; ++n) { + result[n] = static_cast(result_f32[n]); + } + return true; + } +} + +template +bool try_int8_preq_parallel( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int N, + int K, + int n_threads, + int n_chunks, + std::atomic& steal_counter, + int CHUNK_COLS) { + constexpr int INT8_MAX_K = 16384; + constexpr int STACK_GROUPS = 128; + + if constexpr (!((bits == 4 || bits == 8) && group_size >= 32)) { + return false; + } else { + if (!cpu::quantized_int8()) { + return false; + } + if (K > INT8_MAX_K) { + return false; + } + + const int groups_per_col = K / group_size; + alignas(64) int8_t x_q[INT8_MAX_K]; + float x_scales_stack[STACK_GROUPS]; + float x_group_sums_stack[STACK_GROUPS]; + std::unique_ptr x_scales_heap; + std::unique_ptr x_group_sums_heap; + float* x_scales = x_scales_stack; + float* x_group_sums = x_group_sums_stack; + if (groups_per_col > STACK_GROUPS) { + x_scales_heap.reset(new float[groups_per_col]); + x_group_sums_heap.reset(new float[groups_per_col]); + x_scales = x_scales_heap.get(); + x_group_sums = x_group_sums_heap.get(); + } + + quantize_activation_int8_highway( + x, + quantized_highway_dtype(), + K, + group_size, + x_q, + x_scales, + x_group_sums); + + auto& pool = cpu::ThreadPool::instance(); + PreqAct preq{x_q, x_scales, x_group_sums}; + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + int n_start = std::min(my_chunk * CHUNK_COLS, N); + int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + _qmm_t_simd_row( + result + n_start, x, w, scales, biases, n_start, n_end, K, &preq); + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + return true; + } +} + +} // namespace mlx::core diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp new file mode 100644 index 0000000000..37d3fccdb1 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -0,0 +1,2813 @@ +// Copyright © 2023-2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) +// #3019's quantized.cpp: builds without Highway compile quantized.cpp instead. + +#include +#include +#include +#include +#include "mlx/backend/common/quantized.h" +#include "mlx/backend/common/unary.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/lapack.h" +#include "mlx/backend/cpu/scratch.h" +#include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/backend/cpu/unary.h" +#include "mlx/backend/cpu/unary_ops.h" +#include "mlx/fast_primitives.h" +#include "mlx/primitives.h" +#include "mlx/utils.h" + +// ISA-specific SIMD implementations (int8 kernels, dequant, LUT lookups). +// Highway kernels are compiled as runtime-dispatched translation units when x86 +// CPU SIMD is enabled. +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/quantized_highway.h" +#else +// No ISA-specific SIMD available. Provide no-op stubs to fall through to the +// generic SIMD paths in quantized.cpp which work on any platform via the +// portable Simd layer. +#include "mlx/backend/cpu/quantized.h" +namespace mlx::core { + +template +int try_batch_extract_multi_col( + const T*& x_local, + const uint32_t* w_ptrs[NC], + simd::Simd> g_acc[NC], + int group_size_val) { + return 0; +} + +template +bool try_int8_simd_row( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int n_start, + int n_end, + int K, + int groups_per_col, + int packs_per_col, + float* x_group_sums, + const PreqAct* preq) { + return false; +} + +template +bool try_int8_preq_parallel( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int N, + int K, + int n_threads, + int n_chunks, + std::atomic& steal_counter, + int CHUNK_COLS) { + return false; +} + +template +simd::Simd fp4_lut_lookup_simd( + const simd::Simd& wi, + const float* FP4_LUT_ptr) { + alignas(32) float tmp[S]; + for (int i = 0; i < S; ++i) { + tmp[i] = FP4_LUT_ptr[wi[i]]; + } + return simd::load(tmp); +} + +template +simd::Simd fp8_lut_gather_simd( + const uint32_t* w, + const float* FP8_LUT_ptr) { + const uint8_t* bytes = reinterpret_cast(w); + alignas(32) float tmp[S]; + for (int i = 0; i < S; ++i) { + tmp[i] = FP8_LUT_ptr[bytes[i]]; + } + return simd::load(tmp); +} + +} // namespace mlx::core +#endif // ISA dispatch + +namespace mlx::core { + +namespace { + +const static float FP4_LUT[16] = { + +0.0f, + +0.5f, + +1.0f, + +1.5f, + +2.0f, + +3.0f, + +4.0f, + +6.0f, + -0.0f, + -0.5f, + -1.0f, + -1.5f, + -2.0f, + -3.0f, + -4.0f, + -6.0f}; + +// FP8 E4M3 -> float32 lookup table (256 entries, 1KB). +// The values MLX's FromFP8 gives (#4376): 0x7F and 0xFF are NaN. +// Read by the non-transposed fp_qmm path and for nvfp4 scales. +// clang-format off +const static float FP8_LUT[256] = { + 0.0f, 0.001953125f, 0.00390625f, 0.005859375f, 0.0078125f, 0.009765625f, 0.01171875f, 0.013671875f, + 0.015625f, 0.017578125f, 0.01953125f, 0.021484375f, 0.0234375f, 0.025390625f, 0.02734375f, 0.029296875f, + 0.03125f, 0.03515625f, 0.0390625f, 0.04296875f, 0.046875f, 0.05078125f, 0.0546875f, 0.05859375f, + 0.0625f, 0.0703125f, 0.078125f, 0.0859375f, 0.09375f, 0.1015625f, 0.109375f, 0.1171875f, + 0.125f, 0.140625f, 0.15625f, 0.171875f, 0.1875f, 0.203125f, 0.21875f, 0.234375f, + 0.25f, 0.28125f, 0.3125f, 0.34375f, 0.375f, 0.40625f, 0.4375f, 0.46875f, + 0.5f, 0.5625f, 0.625f, 0.6875f, 0.75f, 0.8125f, 0.875f, 0.9375f, + 1.0f, 1.125f, 1.25f, 1.375f, 1.5f, 1.625f, 1.75f, 1.875f, + 2.0f, 2.25f, 2.5f, 2.75f, 3.0f, 3.25f, 3.5f, 3.75f, + 4.0f, 4.5f, 5.0f, 5.5f, 6.0f, 6.5f, 7.0f, 7.5f, + 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, + 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 28.0f, 30.0f, + 32.0f, 36.0f, 40.0f, 44.0f, 48.0f, 52.0f, 56.0f, 60.0f, + 64.0f, 72.0f, 80.0f, 88.0f, 96.0f, 104.0f, 112.0f, 120.0f, + 128.0f, 144.0f, 160.0f, 176.0f, 192.0f, 208.0f, 224.0f, 240.0f, + 256.0f, 288.0f, 320.0f, 352.0f, 384.0f, 416.0f, 448.0f, NAN, + -0.0f,-0.001953125f,-0.00390625f,-0.005859375f,-0.0078125f,-0.009765625f,-0.01171875f,-0.013671875f, + -0.015625f,-0.017578125f,-0.01953125f,-0.021484375f,-0.0234375f,-0.025390625f,-0.02734375f,-0.029296875f, + -0.03125f, -0.03515625f, -0.0390625f, -0.04296875f, -0.046875f, -0.05078125f, -0.0546875f, -0.05859375f, + -0.0625f, -0.0703125f, -0.078125f, -0.0859375f, -0.09375f, -0.1015625f, -0.109375f, -0.1171875f, + -0.125f, -0.140625f, -0.15625f, -0.171875f, -0.1875f, -0.203125f, -0.21875f, -0.234375f, + -0.25f, -0.28125f, -0.3125f, -0.34375f, -0.375f, -0.40625f, -0.4375f, -0.46875f, + -0.5f, -0.5625f, -0.625f, -0.6875f, -0.75f, -0.8125f, -0.875f, -0.9375f, + -1.0f, -1.125f, -1.25f, -1.375f, -1.5f, -1.625f, -1.75f, -1.875f, + -2.0f, -2.25f, -2.5f, -2.75f, -3.0f, -3.25f, -3.5f, -3.75f, + -4.0f, -4.5f, -5.0f, -5.5f, -6.0f, -6.5f, -7.0f, -7.5f, + -8.0f, -9.0f, -10.0f, -11.0f, -12.0f, -13.0f, -14.0f, -15.0f, + -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -28.0f, -30.0f, + -32.0f, -36.0f, -40.0f, -44.0f, -48.0f, -52.0f, -56.0f, -60.0f, + -64.0f, -72.0f, -80.0f, -88.0f, -96.0f, -104.0f, -112.0f, -120.0f, + -128.0f, -144.0f, -160.0f, -176.0f, -192.0f, -208.0f, -224.0f, -240.0f, + -256.0f, -288.0f, -320.0f, -352.0f, -384.0f, -416.0f, -448.0f, -NAN, +}; +// clang-format on + +template +static inline T dequantize_scale(uint8_t s) { + if constexpr (group_size == 16) { + return static_cast(FP8_LUT[s]); + } else { + using FOrI = union { + bfloat16_t f; + uint16_t i; + }; + FOrI out; + out.i = (s == 0) ? 0x40 + : (s == 0xFF ? 0x7FC0 : (static_cast(s) << 7)); + return static_cast(out.f); + } +} + +template +void extract_bits(const uint8_t* w_in, T* w_out) { + static_assert(bits == 3 || bits == 5 || bits == 6); + if (bits == 3) { + w_out[0] = static_cast(w_in[0] & 0x7); + w_out[1] = static_cast((w_in[0] & 0x38) >> 3); + w_out[2] = static_cast(((w_in[0] & 0xc0) >> 6) + ((w_in[1] & 0x1) << 2)); + w_out[3] = static_cast((w_in[1] & 0xe) >> 1); + w_out[4] = static_cast((w_in[1] & 0x70) >> 4); + w_out[5] = static_cast(((w_in[1] & 0x80) >> 7) + ((w_in[2] & 0x3) << 1)); + w_out[6] = static_cast((w_in[2] & 0x1c) >> 2); + w_out[7] = static_cast((w_in[2] & 0xe0) >> 5); + } else if (bits == 5) { + w_out[0] = static_cast(w_in[0] & 0x1f); + w_out[1] = static_cast(((w_in[0] & 0xe0) >> 5) + ((w_in[1] & 0x3) << 3)); + w_out[2] = static_cast((w_in[1] & 0x7c) >> 2); + w_out[3] = static_cast(((w_in[1] & 0x80) >> 7) + ((w_in[2] & 0xf) << 1)); + w_out[4] = static_cast(((w_in[2] & 0xf0) >> 4) + ((w_in[3] & 0x1) << 4)); + w_out[5] = static_cast((w_in[3] & 0x3e) >> 1); + w_out[6] = static_cast(((w_in[3] & 0xc0) >> 6) + ((w_in[4] & 0x7) << 2)); + w_out[7] = static_cast((w_in[4] & 0xf8) >> 3); + + } else if (bits == 6) { + w_out[0] = static_cast(w_in[0] & 0x3f); + w_out[1] = + static_cast(((w_in[0] >> 6) & 0x03) + ((w_in[1] & 0x0f) << 2)); + w_out[2] = + static_cast(((w_in[1] >> 4) & 0x0f) + ((w_in[2] & 0x03) << 4)); + w_out[3] = static_cast((w_in[2] >> 2) & 0x3f); + } +} + +template +void _qmm( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K) { + constexpr int bitmask = (1 << bits) - 1; + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int bytes_per_pack = get_bytes_per_pack(bits); + constexpr int packs_in_group = group_size / pack_factor; + + // Accumulate in float32, as quantized.cpp does since ml-explore/mlx#4803. + std::vector acc(N); + for (int m = 0; m < M; m++) { + const uint8_t* w_local = (const uint8_t*)w; + const T* scales_local = scales; + const T* biases_local = biases; + + std::fill(acc.begin(), acc.end(), 0.0f); + + for (int k = 0; k < K; k++) { + float* result_local = acc.data(); + float xi = *x++; + + for (int n = 0; n < N; n += group_size) { + float scale = *scales_local++; + float bias = *biases_local++; + for (int ng = 0; ng < packs_in_group; ng++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + float wl[pack_factor]; + extract_bits(w_local, wl); +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + (*result_local++) += xi * (scale * wl[p] + bias); + } + w_local += bytes_per_pack; + + } else { + uint8_t wi = *w_local++; +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + (*result_local++) += + xi * (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; + } + } + } + } + } + } + + std::copy(acc.begin(), acc.end(), result); + result += N; + } +} + +// Helper for computing a range of output columns in _qmm_t (used by threaded +// version) +template +void _qmm_t_cols( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int n_start, + int n_end, + int K) { + constexpr int bitmask = (1 << bits) - 1; + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int bytes_per_pack = get_bytes_per_pack(bits); + constexpr int packs_in_group = group_size / pack_factor; + + // Compute strides for navigating to different output columns + int groups_per_col = K / group_size; + int bytes_per_col = groups_per_col * packs_in_group * bytes_per_pack; + + // Advance to starting column + const uint8_t* w_base = (const uint8_t*)w + n_start * bytes_per_col; + const T* scales_base = scales + n_start * groups_per_col; + const T* biases_base = biases + n_start * groups_per_col; + + for (int n = n_start; n < n_end; n++) { + const uint8_t* w_local = w_base; + const T* scales_local = scales_base; + const T* biases_local = biases_base; + const T* x_local = x; + float sum = 0; // float32, as quantized.cpp since ml-explore/mlx#4803 + + for (int k = 0; k < K; k += group_size) { + float scale = *scales_local++; + float bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + float wl[pack_factor]; + extract_bits(w_local, wl); +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += static_cast(x_local[p]) * (scale * wl[p] + bias); + } + w_local += bytes_per_pack; + x_local += pack_factor; + } else { + uint8_t wi = *w_local++; +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += static_cast(*x_local++) * (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; + } + } + } + } + } + result[n - n_start] = sum; + + // Move to next column + w_base += bytes_per_col; + scales_base += groups_per_col; + biases_base += groups_per_col; + } +} + +template +void _qmm_t( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K) { + auto& pool = cpu::ThreadPool::instance(); + + // Adaptive threshold for M-parallelization based on work size (N*K). + // Larger work per row justifies parallelization overhead. + // Formula: threshold = max(8, N * K / 1000000) for faster parallelization + // on typical prompt sizes (7-15 tokens) with reasonable N (e.g., 2048+). + constexpr int64_t WORK_PER_PIXEL_THRESHOLD = 1000000; + int m_parallel_threshold = + std::max(8, static_cast(N * K / WORK_PER_PIXEL_THRESHOLD)); + if (M >= m_parallel_threshold && pool.max_threads() > 1) { + int m_threads = std::min(pool.max_threads(), M); + pool.parallel_for(m_threads, [&](int tid, int nth) { + int m_chunk = (M + nth - 1) / nth; + int m_start = m_chunk * tid; + int m_end = std::min(m_start + m_chunk, M); + for (int m = m_start; m < m_end; m++) { + _qmm_t_cols( + result + m * N, x + m * K, w, scales, biases, 0, N, K); + } + }); + return; + } + + // Single row (M=1) or small M: parallelize over N if beneficial + int n_threads = std::min(pool.max_threads(), std::max(1, N / 64)); + + for (int m = 0; m < M; m++) { + if (n_threads > 1) { + // Parallel path: parallelize over output columns N + pool.parallel_for(n_threads, [&](int tid, int nth) { + int chunk = (N + nth - 1) / nth; + int n_start = chunk * tid; + int n_end = std::min(n_start + chunk, N); + if (n_start < n_end) { + _qmm_t_cols( + result + n_start, x, w, scales, biases, n_start, n_end, K); + } + }); + result += N; + } else { + // Sequential path (original implementation) + constexpr int bitmask = (1 << bits) - 1; + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int bytes_per_pack = get_bytes_per_pack(bits); + constexpr int packs_in_group = group_size / pack_factor; + + const uint8_t* w_local = (const uint8_t*)w; + const T* scales_local = scales; + const T* biases_local = biases; + + for (int n = 0; n < N; n++) { + const T* x_local = x; + float sum = 0; // float32, as quantized.cpp since ml-explore/mlx#4803 + for (int k = 0; k < K; k += group_size) { + float scale = *scales_local++; + float bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + float wl[pack_factor]; + extract_bits(w_local, wl); +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += static_cast(x_local[p]) * (scale * wl[p] + bias); + } + w_local += bytes_per_pack; + x_local += pack_factor; + } else { + uint8_t wi = *w_local++; +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += static_cast(*x_local++) * + (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; + } + } + } + } + } + *result = sum; + result++; + } + } + x += K; + } +} + +// Extract S elements starting at element offset `elem_off` within packed words. +// For S >= pack_factor, elem_off must be 0 and this degenerates to the standard +// version. For S < pack_factor (e.g., S=4, pack_factor=8), elem_off +// selects which S-element chunk within the word to extract. +template +simd::Simd extract_bits_simd(const uint32_t* w, int elem_off = 0) { + constexpr int bitmask = (1 << bits) - 1; + simd::Simd wi; + if constexpr (S == 1) { + // Scalar: extract single value from packed word + wi = simd::Simd((*w >> (elem_off * bits)) & bitmask); + } else if constexpr (bits == 4 && S == 4) { + // 4-lane path: extract 4 4-bit values from part of one uint32_t word. + // elem_off selects which group of 4 nibbles: 0=lower, 1=upper + uint32_t word = *w; + if (elem_off == 1) { + word >>= 16; // shift to get upper 4 nibbles + } + alignas(16) constexpr uint32_t shifts_[] = {0, 4, 8, 12}; + auto shifts = simd::load(shifts_); + wi = simd::Simd(word); + wi = wi >> shifts; + wi = wi & bitmask; + } else if constexpr (bits == 2 && S == 4) { + // 4-lane path: extract 4 2-bit values from part of one uint32_t word. + // Each uint32 has 16 2-bit values. We extract 4 at a time. + uint32_t word = *w; + word >>= (elem_off * S * bits); + alignas(16) constexpr uint32_t shifts_[] = {0, 2, 4, 6}; + auto shifts = simd::load(shifts_); + wi = simd::Simd(word); + wi = wi >> shifts; + wi = wi & bitmask; + } else if constexpr (bits == 8 && S == 4) { + // 4-lane path: extract 4 8-bit values from one uint32_t word. + alignas(16) constexpr uint32_t shifts_[] = {0, 8, 16, 24}; + auto shifts = simd::load(shifts_); + wi = simd::Simd(*w); + wi = wi >> shifts; + wi = wi & bitmask; + } else if constexpr (bits == 2 && S == 8) { + // Highway SIMD: 8 2-bit values from one uint32_t word (half of 16 total) + // elem_off selects which half: 0=lower 8, 1=upper 8 + uint32_t word = *w; + if (elem_off == 1) { + word >>= 16; + } + constexpr std::array shifts_ = {{0, 2, 4, 6, 8, 10, 12, 14}}; + auto shifts(*(simd::Simd*)&shifts_); + wi = simd::Simd(word); + wi = wi >> shifts; + wi = wi & bitmask; + } else if constexpr (bits == 4 && S == 8) { + constexpr std::array shifts_ = {{0, 4, 8, 12, 16, 20, 24, 28}}; + auto shifts(*(simd::Simd*)&shifts_); + wi = simd::Simd(*w); + wi = wi >> shifts; + wi = wi & bitmask; + } else if constexpr (bits == 8 && S == 8) { + // 8 8-bit values from 2 uint32_t words + // Broadcast w[0] to lanes 0-3, w[1] to lanes 4-7, then shift and mask + constexpr std::array shifts_ = {{0, 8, 16, 24, 0, 8, 16, 24}}; + auto shifts(*(simd::Simd*)&shifts_); + alignas(32) + uint32_t words[8] = {w[0], w[0], w[0], w[0], w[1], w[1], w[1], w[1]}; + wi = simd::load(words); + wi = wi >> shifts; + wi = wi & bitmask; + } else { + // Appease compiler.. but should never get here + throw std::runtime_error("Unsupported combination for simd qmm."); + } + return wi; +} + +// Process NC output columns simultaneously, loading x once and reusing across +// all columns. This amortizes x load cost and improves register utilization. +template +void _qmm_t_simd_multi_col( + T* result, + const T* x, + const uint32_t* w_ptrs[NC], + const T* scales_ptrs[NC], + const T* biases_ptrs[NC], + const float* x_group_sums, + int K) { + constexpr int pack_factor = 32 / bits; + constexpr int S = simd::max_size; + constexpr int iters_per_word = (S >= pack_factor) ? 1 : (pack_factor / S); + constexpr int words_per_iter = (S >= pack_factor) ? (S / pack_factor) : 0; + + simd::Simd acc[NC]; + for (int c = 0; c < NC; c++) + acc[c] = simd::Simd(0); + + // Scalar accumulator for deferred bias contributions + float bias_acc[NC] = {}; + + auto x_local = x; + int groups = K / group_size; + for (int g = 0; g < groups; g++) { + // Load scale and bias for each column + float scale_f[NC], bias_f[NC]; + for (int c = 0; c < NC; c++) { + scale_f[c] = static_cast(*scales_ptrs[c]++); + bias_f[c] = static_cast(*biases_ptrs[c]++); + } + + // Per-group accumulator for raw (unscaled) dot product + simd::Simd g_acc[NC]; + for (int c = 0; c < NC; c++) + g_acc[c] = simd::Simd(0); + + // Try ISA-specific batch-extract fast path (no-op stub returns 0 when + // unavailable). + int elem = try_batch_extract_multi_col( + x_local, w_ptrs, g_acc, group_size); + + { + // Generic path: 2xS unrolled loop with extract_bits_simd + // (elem starts at 0 without Highway, or after batch-extracted elements) + for (; elem + S * 2 <= group_size; elem += S * 2) { + int elem_off_0 = 0, elem_off_1 = 0; + if constexpr (S < pack_factor) { + elem_off_0 = (elem / S) % iters_per_word; + elem_off_1 = ((elem + S) / S) % iters_per_word; + } + + simd::Simd x_simd_0 = load_as_float(x_local); + simd::Simd x_simd_1 = load_as_float(x_local + S); + x_local += S * 2; + +#pragma clang loop unroll(full) + for (int c = 0; c < NC; c++) { + auto w_raw_0 = simd::Simd( + extract_bits_simd(w_ptrs[c], elem_off_0)); + if constexpr (S >= pack_factor) { + w_ptrs[c] += words_per_iter; + } else { + if (elem_off_0 == iters_per_word - 1) { + w_ptrs[c] += 1; + } + } + g_acc[c] = simd::fma(x_simd_0, w_raw_0, g_acc[c]); + + auto w_raw_1 = simd::Simd( + extract_bits_simd(w_ptrs[c], elem_off_1)); + if constexpr (S >= pack_factor) { + w_ptrs[c] += words_per_iter; + } else { + if (elem_off_1 == iters_per_word - 1) { + w_ptrs[c] += 1; + } + } + g_acc[c] = simd::fma(x_simd_1, w_raw_1, g_acc[c]); + } + } + + // Handle remaining elements + for (; elem < group_size; elem += S) { + int elem_off = 0; + if constexpr (S < pack_factor) { + elem_off = (elem / S) % iters_per_word; + } + + simd::Simd x_simd = load_as_float(x_local); + x_local += S; + +#pragma clang loop unroll(full) + for (int c = 0; c < NC; c++) { + auto w_raw = simd::Simd( + extract_bits_simd(w_ptrs[c], elem_off)); + if constexpr (S >= pack_factor) { + w_ptrs[c] += words_per_iter; + } else { + if (elem_off == iters_per_word - 1) { + w_ptrs[c] += 1; + } + } + g_acc[c] = simd::fma(x_simd, w_raw, g_acc[c]); + } + } + } + + // Per-group fixup: acc += scale * g_acc, bias_acc += bias * x_group_sum + float xgs = x_group_sums[g]; +#pragma clang loop unroll(full) + for (int c = 0; c < NC; c++) { + acc[c] = simd::fma(simd::Simd(scale_f[c]), g_acc[c], acc[c]); + bias_acc[c] += bias_f[c] * xgs; + } + } + + for (int c = 0; c < NC; c++) { + result[c] = T(simd::sum(acc[c]) + bias_acc[c]); + } +} + +// Single column accumulator with bias deferral - helper for tiled version tail +template +float _qmm_t_simd_single_col( + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + const float* x_group_sums, + int K) { + constexpr int pack_factor = 32 / bits; + constexpr int packs_in_group = group_size / pack_factor; + constexpr int S = simd::max_size; + constexpr int iters_per_word = (S >= pack_factor) ? 1 : (pack_factor / S); + constexpr int words_per_iter = (S >= pack_factor) ? (S / pack_factor) : 0; + + int groups_per_col = K / group_size; + + simd::Simd acc(0); + float bias_acc = 0; + auto x_local = x; + + for (int g = 0; g < groups_per_col; g++) { + float scale_f = static_cast(scales[g]); + float bias_f = static_cast(biases[g]); + const uint32_t* w_local = w + g * packs_in_group; + + simd::Simd g_acc(0); + for (int elem = 0; elem < group_size; elem += S) { + int elem_off = 0; + if constexpr (S < pack_factor) { + elem_off = (elem / S) % iters_per_word; + } + + auto w_raw = + simd::Simd(extract_bits_simd(w_local, elem_off)); + if constexpr (S >= pack_factor) { + w_local += words_per_iter; + } else { + if (elem_off == iters_per_word - 1) { + w_local += 1; + } + } + + simd::Simd x_simd = load_as_float(x_local); + g_acc = simd::fma(x_simd, w_raw, g_acc); + x_local += S; + } + + acc = simd::fma(simd::Simd(scale_f), g_acc, acc); + bias_acc += bias_f * x_group_sums[g]; + } + + return simd::sum(acc) + bias_acc; +} + +} // namespace + +// Row processor: precomputes x_group_sums for bias deferral, then dispatches +// to multi-col kernel for main body and single-col for tail. +// If preq is non-null, uses pre-quantized activation data instead of +// quantizing locally (eliminates redundant quantization across threads). +template +void _qmm_t_simd_row( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int n_start, + int n_end, + int K, + const PreqAct* preq) { + constexpr int pack_factor = 32 / bits; + constexpr int packs_in_group = group_size / pack_factor; + constexpr int S = simd::max_size; + constexpr int NC = 8; + + int groups_per_col = K / group_size; + int packs_per_col = groups_per_col * packs_in_group; + + // Precompute group sums for x (once per row, reused for all N columns) + // Stack-allocate for typical sizes, heap for large K + constexpr int STACK_GROUPS = 128; // covers K up to 8192 with group_size=64 + float xgs_stack[STACK_GROUPS]; + std::unique_ptr xgs_heap; + float* x_group_sums; + if (preq) { + // Use pre-quantized group sums (already computed once by caller) + x_group_sums = const_cast(preq->x_group_sums); + } else if (groups_per_col <= STACK_GROUPS) { + x_group_sums = xgs_stack; + } else { + xgs_heap.reset(new float[groups_per_col]); + x_group_sums = xgs_heap.get(); + } + + // Try ISA-specific int8 dot-product path (no-op stub returns false when + // unavailable). + if (try_int8_simd_row( + result, + x, + w, + scales, + biases, + n_start, + n_end, + K, + groups_per_col, + packs_per_col, + x_group_sums, + preq)) + return; + + // Float path: compute x_group_sums only (no int8 quantization) + // Skip if using pre-quantized data (group_sums already set at top) + if (!preq) { + for (int g = 0; g < groups_per_col; g++) { + simd::Simd sum_acc(0); + const T* xg = x + g * group_size; + for (int e = 0; e < group_size; e += S) { + sum_acc = sum_acc + load_as_float(xg + e); + } + x_group_sums[g] = simd::sum(sum_acc); + } + } + + const uint32_t* w_base = w + n_start * packs_per_col; + const T* scales_base = scales + n_start * groups_per_col; + const T* biases_base = biases + n_start * groups_per_col; + + int n = n_start; + + // Process NC columns at a time (8 columns for better x-cache reuse) + for (; n + NC <= n_end; n += NC) { + const uint32_t* wp[NC]; + const T* sp[NC]; + const T* bp[NC]; + for (int c = 0; c < NC; c++) { + wp[c] = w_base + c * packs_per_col; + sp[c] = scales_base + c * groups_per_col; + bp[c] = biases_base + c * groups_per_col; + } + _qmm_t_simd_multi_col( + result + (n - n_start), x, wp, sp, bp, x_group_sums, K); + w_base += NC * packs_per_col; + scales_base += NC * groups_per_col; + biases_base += NC * groups_per_col; + } + + // Handle remaining columns with NC=4 (if >= 4 remaining) + constexpr int NC4 = 4; + for (; n + NC4 <= n_end; n += NC4) { + const uint32_t* wp[NC4]; + const T* sp[NC4]; + const T* bp[NC4]; + for (int c = 0; c < NC4; c++) { + wp[c] = w_base + c * packs_per_col; + sp[c] = scales_base + c * groups_per_col; + bp[c] = biases_base + c * groups_per_col; + } + _qmm_t_simd_multi_col( + result + (n - n_start), x, wp, sp, bp, x_group_sums, K); + w_base += NC4 * packs_per_col; + scales_base += NC4 * groups_per_col; + biases_base += NC4 * groups_per_col; + } + + // Handle remaining columns one at a time + for (; n < n_end; n++) { + result[n - n_start] = + T(_qmm_t_simd_single_col( + x, w_base, scales_base, biases_base, x_group_sums, K)); + w_base += packs_per_col; + scales_base += groups_per_col; + biases_base += groups_per_col; + } +} + +namespace { + +template +void _qmm_t_simd( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K) { + constexpr int pack_factor = 32 / bits; + constexpr int S = simd::max_size; + static_assert( + S % pack_factor == 0 || pack_factor % S == 0, + "SIMD size and pack factor must be divisible"); +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (bits == 4 || bits == 8) { + if (qmm_t_int8_highway( + result, + x, + w, + scales, + biases, + quantized_highway_dtype(), + bits, + group_size, + M, + N, + K)) { + return; + } + } +#endif + auto& pool = cpu::ThreadPool::instance(); + + // N-parallel threading: split columns across threads. + // Each thread processes ALL M rows for its column chunk. + // Weight data per thread fits in L2 cache for much better locality + // than M-parallel where every thread reads the entire weight matrix. + // + // For M=1 generation, use larger minimum columns per thread (128 vs 64). + // Fewer threads reduces sync overhead and improves L2 cache utilization + // per thread. For a small model (N=2048): 16 threads x 128 cols vs 32 x 64. + int min_cols_per_thread = (M == 1) ? 128 : 64; + int n_threads = + std::min(pool.max_threads(), std::max(1, N / min_cols_per_thread)); + + // Work-stealing chunk size: 64 columns (8 multi-col kernel invocations). + // Threads start at their assigned chunk and steal more via atomic counter. + // This dynamically balances load when threads have different cache warmth + // or the system has asymmetric load from background processes. + constexpr int CHUNK_COLS = 64; + int n_chunks = (N + CHUNK_COLS - 1) / CHUNK_COLS; + + // Local steal counter -- must NOT be a pool member because multiple CPU + // streams can call parallel_for concurrently (e.g., stream_generate uses + // a separate generation_stream). A shared counter would be corrupted. + alignas(64) std::atomic steal_counter{0}; + + if (n_threads > 1 && M == 1) { + // M==1 fast path (generation): pre-quantize activation vector ONCE + // and share across all threads. Eliminates redundant quantization + // (16 threads each quantizing the same x -> 1 quantization shared). + constexpr int STACK_GROUPS = 128; + int groups_per_col = K / group_size; + + // Try ISA-specific int8 pre-quantization path (no-op stub returns false). + if (try_int8_preq_parallel( + result, + x, + w, + scales, + biases, + N, + K, + n_threads, + n_chunks, + steal_counter, + CHUNK_COLS)) + return; + + // Float fallback: pre-compute group_sums only + { + float xgs_buf[STACK_GROUPS]; + std::unique_ptr xgs_heap; + float* x_group_sums = xgs_buf; + if (groups_per_col > STACK_GROUPS) { + xgs_heap.reset(new float[groups_per_col]); + x_group_sums = xgs_heap.get(); + } + for (int g = 0; g < groups_per_col; g++) { + simd::Simd sum_acc(0); + const T* xg = x + g * group_size; + for (int e = 0; e < group_size; e += S) { + sum_acc = sum_acc + load_as_float(xg + e); + } + x_group_sums[g] = simd::sum(sum_acc); + } + + PreqAct preq{nullptr, nullptr, x_group_sums}; + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + int n_start = std::min(my_chunk * CHUNK_COLS, N); + int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + _qmm_t_simd_row( + result + n_start, + x, + w, + scales, + biases, + n_start, + n_end, + K, + &preq); + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + return; + } + } + + if (n_threads > 1) { + // M>1: each thread processes all M rows for its column chunk. + // Threads quantize per-row independently (pre-quantization would + // require M parallel_for calls or large buffers). + // Work stealing: threads start at their assigned chunk, steal more. + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + int n_start = std::min(my_chunk * CHUNK_COLS, N); + int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + for (int m = 0; m < M; m++) { + _qmm_t_simd_row( + result + m * N + n_start, + x + m * K, + w, + scales, + biases, + n_start, + n_end, + K); + } + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + } else { + for (int m = 0; m < M; m++) { + _qmm_t_simd_row( + result + m * N, x + m * K, w, scales, biases, 0, N, K); + } + } +} + +// Thread-local scratch for the dequant+BLAS path, borrowed through +// ScratchLease. +std::vector& _qmm_scratch_buffer() { + thread_local std::vector buf; + return buf; +} + +// Dequantize a row of packed quantized weights to f32. +// W row layout: K/pack_factor uint32 words, each containing pack_factor values. +// Dequant: f32_val = scale * nibble + bias, with scale/bias per group. +template +void _dequant_row( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int K) { + constexpr int pack_factor = 32 / bits; + constexpr int bitmask = (1 << bits) - 1; + int k = 0; + for (int g = 0; g < K / group_size; g++) { + float scale = scales_row[g]; + float bias = biases_row[g]; + for (int j = 0; j < group_size; j++, k++) { + int word_idx = k / pack_factor; + int elem_idx = k % pack_factor; + uint32_t val = (w_row[word_idx] >> (elem_idx * bits)) & bitmask; + out[k] = scale * static_cast(val) + bias; + } + } +} + +template +void _dequant_row_for_blas( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int K) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (bits == 4 || bits == 8) { + _dequant_row_highway( + w_row, scales_row, biases_row, out, K); + return; + } +#endif + _dequant_row(w_row, scales_row, biases_row, out, K); +} + +// Dequantize + BLAS path for large-M quantized matmul (prompt processing). +// For large M, OpenBLAS SGEMM is ~2x faster than custom quantized kernel +// because BLAS has superior micro-kernels and cache tiling. +// The dequantization overhead is <2% of total time for M >= 32. +template +void _qmm_t_blas( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K) { + constexpr int pack_factor = 32 / bits; + const int w_row_words = K / pack_factor; + const int num_groups = K / group_size; + + auto& pool = cpu::ThreadPool::instance(); + + // Scratch: W_f32[N*K] + x_f32[M*K] + result_f32[M*N] + // Total for gate_proj (N=8192, K=2048, M=2048): 64+16+64 = 144MB + // Use thread-local for single-threaded path; for parallel dequant, + // W_f32 is shared (each thread writes disjoint rows). + size_t w_f32_size = (size_t)N * K; + size_t x_f32_size = (size_t)M * K; + size_t r_f32_size = (size_t)M * N; + cpu::ScratchLease scratch( + _qmm_scratch_buffer(), w_f32_size + x_f32_size + r_f32_size); + float* w_f32 = scratch.data(); + float* x_f32 = w_f32 + w_f32_size; + float* r_f32 = x_f32 + x_f32_size; + + // Step 1: Convert scales and biases to f32, then dequantize W in parallel + // Each thread dequantizes a range of N rows. + int n_threads = std::min(pool.max_threads(), std::max(1, N / 64)); + + // Pre-convert scales and biases to f32 (small: N * K/group_size each) + std::vector scales_f32(N * num_groups); + std::vector biases_f32(N * num_groups); + for (int i = 0; i < N * num_groups; i++) { + scales_f32[i] = static_cast(scales[i]); + biases_f32[i] = static_cast(biases[i]); + } + + if (n_threads > 1) { + pool.parallel_for(n_threads, [&](int tid, int nth) { + int chunk = (N + nth - 1) / nth; + int n_start = std::min(chunk * tid, N); + int n_end = std::min(n_start + chunk, N); + for (int n = n_start; n < n_end; n++) { + _dequant_row_for_blas( + w + n * w_row_words, + scales_f32.data() + n * num_groups, + biases_f32.data() + n * num_groups, + w_f32 + n * K, + K); + } + }); + } else { + for (int n = 0; n < N; n++) { + _dequant_row_for_blas( + w + n * w_row_words, + scales_f32.data() + n * num_groups, + biases_f32.data() + n * num_groups, + w_f32 + n * K, + K); + } + } + + // Step 2: Convert x to f32 + constexpr int SW = simd::max_size; + { + size_t total = (size_t)M * K; + size_t i = 0; + for (; i + SW <= total; i += SW) { + simd::store(x_f32 + i, simd::Simd(simd::load(x + i))); + } + for (; i < total; i++) { + x_f32[i] = static_cast(x[i]); + } + } + + // Step 3: SGEMM -- result = x_f32 @ W_f32^T + // Split M across threads, each thread calls single-threaded BLAS + int m_threads = std::min(pool.max_threads(), std::max(1, M / 8)); + + if (m_threads > 1) { + pool.parallel_for(m_threads, [&](int tid, int nth) { + size_t m_chunk = (M + nth - 1) / nth; + size_t m_start = m_chunk * tid; + size_t m_end = std::min(m_start + m_chunk, (size_t)M); + if (m_start < m_end) { + cblas_sgemm( + CblasRowMajor, + CblasNoTrans, + CblasTrans, + m_end - m_start, + N, + K, + 1.0f, + x_f32 + m_start * K, + K, + w_f32, + K, + 0.0f, + r_f32 + m_start * N, + N); + } + }); + } else { + cblas_sgemm( + CblasRowMajor, + CblasNoTrans, + CblasTrans, + M, + N, + K, + 1.0f, + x_f32, + K, + w_f32, + K, + 0.0f, + r_f32, + N); + } + + // Step 4: Convert result to T + { + size_t total = (size_t)M * N; + size_t i = 0; + for (; i + SW <= total; i += SW) { + simd::store( + result + i, simd::Simd(simd::load(r_f32 + i))); + } + for (; i < total; i++) { + result[i] = static_cast(r_f32[i]); + } + } +} + +// Minimum M for dequant+BLAS path (below this, custom kernel is faster) +constexpr int QMM_BLAS_M_THRESHOLD = 32; + +template +void _qmm_dispatch_transpose( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K, + bool transposed_w) { + if (transposed_w) { + // For large M (prompt), dequantize weights to f32 and use BLAS. + // OpenBLAS SGEMM has ~2x better throughput than custom quantized kernel + // due to superior micro-kernels and cache tiling. The dequantization + // overhead is <2% for large M. + // _qmm_t_blas reads 32 / bits values per word, right for 2, 4 and 8 bits; + // 3, 5 and 6 bits are a byte stream, so they take the rows below. + if constexpr (32 % bits == 0) { + if (M >= QMM_BLAS_M_THRESHOLD) { + _qmm_t_blas(result, x, w, scales, biases, M, N, K); + return; + } + } +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (bits == 4 || bits == 8) { + _qmm_t_simd(result, x, w, scales, biases, M, N, K); + return; + } +#endif + // SIMD path: S must be >= 4 and must divide pack_factor or vice versa + constexpr int pack_factor = 32 / bits; + constexpr int S = simd::max_size; + if constexpr ( + S >= 4 && 32 % bits == 0 && + (S % pack_factor == 0 || pack_factor % S == 0) && group_size % S == 0) { + _qmm_t_simd(result, x, w, scales, biases, M, N, K); + } else { + _qmm_t(result, x, w, scales, biases, M, N, K); + } + } else { + _qmm(result, x, w, scales, biases, M, N, K); + } +} + +template +void _qmm_dispatch_group( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K, + int group_size, + bool transposed_w) { + switch (group_size) { + case 32: + _qmm_dispatch_transpose( + result, x, w, scales, biases, M, N, K, transposed_w); + break; + case 64: + _qmm_dispatch_transpose( + result, x, w, scales, biases, M, N, K, transposed_w); + break; + case 128: + _qmm_dispatch_transpose( + result, x, w, scales, biases, M, N, K, transposed_w); + break; + default: + throw std::invalid_argument( + "Quantization group size must be 32, 64 or 128."); + } +} + +template +void _qmm_dispatch_typed( + T* result, + const T* x, + const uint32_t* w, + const T* scales, + const T* biases, + int M, + int N, + int K, + int group_size, + int bits, + bool transposed_w) { + switch (bits) { + case 2: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + case 3: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + case 4: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + case 5: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + case 6: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + case 8: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; + default: + throw std::invalid_argument("Quantization bits must be 2, 3, 4, 6 or 8."); + } +} + +template +void _qmm_dispatch_typed( + array& out, + const array& x, + const array& w, + const array& scales, + const array& biases, + int bits, + int group_size, + bool transposed_w) { + int K = x.shape(-1); + int M = x.ndim() > 1 ? x.shape(-2) : 1; + int N = out.shape(-1); + int w_els = w.ndim() > 2 ? w.shape(-1) * w.shape(-2) : 0; + int g_els = w.ndim() > 2 ? scales.shape(-1) * scales.shape(-2) : 0; + int batch_size = x.size() / (K * M); + + auto out_ptr = out.data(); + auto x_ptr = x.data(); + auto w_ptr = w.data(); + auto scales_ptr = scales.data(); + auto biases_ptr = biases.data(); + for (int i = 0; i < batch_size; i++) { + _qmm_dispatch_typed( + out_ptr + i * M * N, + x_ptr + elem_to_loc(i * M * K, x.shape(), x.strides()), + w_ptr + elem_to_loc(i * w_els, w.shape(), w.strides()), + scales_ptr + elem_to_loc(i * g_els, scales.shape(), scales.strides()), + biases_ptr + elem_to_loc(i * g_els, biases.shape(), biases.strides()), + M, + N, + K, + bits, + group_size, + transposed_w); + } +} + +void _qmm_dispatch( + array& out, + const array& x, + const array& w, + const array& scales, + const array& biases, + int bits, + int group_size, + bool transposed_w) { + switch (x.dtype()) { + case float32: + _qmm_dispatch_typed( + out, x, w, scales, biases, bits, group_size, transposed_w); + break; + case float16: + _qmm_dispatch_typed( + out, x, w, scales, biases, bits, group_size, transposed_w); + break; + case bfloat16: + _qmm_dispatch_typed( + out, x, w, scales, biases, bits, group_size, transposed_w); + break; + default: + throw std::invalid_argument( + "[quantized_matmul] only floating types are supported"); + } +} + +template +void fp_qmm( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int M, + int N, + int K, + float scale_factor) { + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int packs_in_group = group_size / pack_factor; + + for (int m = 0; m < M; m++) { + const uint8_t* w_local = (const uint8_t*)w; + const uint8_t* scales_local = scales; + + std::fill(result, result + N, 0); + + for (int k = 0; k < K; k++) { + T* result_local = result; + T xi = *x++; + + for (int n = 0; n < N; n += group_size) { + T scale = static_cast( + static_cast( + dequantize_scale(*scales_local++)) * + scale_factor); + for (int ng = 0; ng < packs_in_group; ng++) { + if constexpr (bits == 4) { + (*result_local++) += + xi * scale * static_cast(FP4_LUT[w_local[0] & 0xf]); + (*result_local++) += + xi * scale * static_cast(FP4_LUT[(w_local[0] >> 4) & 0xf]); + } else { + (*result_local++) += + xi * scale * static_cast(FP8_LUT[w_local[0]]); + } + w_local++; + } + } + } + result += N; + } +} + +// Helper for computing a range of output columns in fp_qmm_t (used by threaded +// version) +template +void fp_qmm_t_cols( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int n_start, + int n_end, + int K, + float scale_factor) { + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int packs_in_group = group_size / pack_factor; + + // Compute strides for navigating to different output columns + int groups_per_col = K / group_size; + int bytes_per_col = groups_per_col * packs_in_group; + + // Advance to starting column + const uint8_t* w_base = (const uint8_t*)w + n_start * bytes_per_col; + const uint8_t* scales_base = scales + n_start * groups_per_col; + + for (int n = n_start; n < n_end; n++) { + const uint8_t* w_local = w_base; + const uint8_t* scales_local = scales_base; + const T* x_local = x; + T sum = 0; + + for (int k = 0; k < K; k += group_size) { + T scale = static_cast( + static_cast(dequantize_scale(*scales_local++)) * + scale_factor); + + T gsum = 0; + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 4) { + gsum += (*x_local++) * static_cast(FP4_LUT[w_local[0] & 0xf]); + gsum += + (*x_local++) * static_cast(FP4_LUT[(w_local[0] >> 4) & 0xf]); + } else { + gsum += (*x_local++) * static_cast(FP8_LUT[w_local[0]]); + } + w_local++; + } + sum += scale * gsum; + } + result[n - n_start] = sum; + + // Move to next column + w_base += bytes_per_col; + scales_base += groups_per_col; + } +} + +template +void fp_qmm_t( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int M, + int N, + int K, + float scale_factor) { + // Check if parallelization over N is beneficial + auto& pool = cpu::ThreadPool::instance(); + // Each thread needs enough work to amortize wake-up overhead (~64 columns + // min) + int n_threads = std::min(pool.max_threads(), std::max(1, N / 64)); + + for (int m = 0; m < M; m++) { + if (n_threads > 1) { + // Parallel path: parallelize over output columns N + pool.parallel_for(n_threads, [&](int tid, int nth) { + int chunk = (N + nth - 1) / nth; + int n_start = chunk * tid; + int n_end = std::min(n_start + chunk, N); + if (n_start < n_end) { + fp_qmm_t_cols( + result + n_start, x, w, scales, n_start, n_end, K, scale_factor); + } + }); + result += N; + } else { + // Sequential path (original implementation) + constexpr int pack_factor = get_pack_factor(bits, 8); + constexpr int packs_in_group = group_size / pack_factor; + + const uint8_t* w_local = (const uint8_t*)w; + const uint8_t* scales_local = scales; + + for (int n = 0; n < N; n++) { + const T* x_local = x; + T sum = 0; + for (int k = 0; k < K; k += group_size) { + T scale = static_cast( + static_cast( + dequantize_scale(*scales_local++)) * + scale_factor); + + T gsum = 0; + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 4) { + gsum += (*x_local++) * static_cast(FP4_LUT[w_local[0] & 0xf]); + gsum += (*x_local++) * + static_cast(FP4_LUT[(w_local[0] >> 4) & 0xf]); + } else { + gsum += (*x_local++) * static_cast(FP8_LUT[w_local[0]]); + } + w_local++; + } + sum += scale * gsum; + } + *result = sum; + result++; + } + } + x += K; + } +} + +#if !defined(MLX_USE_HIGHWAY_KERNELS) +template +simd::Simd fp_extract_bits_simd(const uint32_t* w, int elem_off = 0) { + if constexpr (S == 1 && bits == 4) { + // Scalar: extract single 4-bit FP4 value + return simd::Simd(FP4_LUT[(*w >> (elem_off * 4)) & 0xf]); + } else if constexpr (S == 1 && bits == 8) { + // Scalar: extract single 8-bit FP8 value via LUT + const uint8_t* bytes = reinterpret_cast(w); + return simd::Simd(FP8_LUT[bytes[elem_off]]); + } else if constexpr (S == 4 && bits == 4) { + // 4-lane path: extract 4 FP4 values from part of one uint32_t word. + uint32_t word = *w; + if (elem_off == 1) { + word >>= 16; + } + alignas(16) constexpr uint32_t shifts_[] = {0, 4, 8, 12}; + auto shifts = simd::load(shifts_); + auto wi = simd::Simd(word); + wi = wi >> shifts; + wi = wi & 0xf; + // Scalar LUT lookup for this fallback path. + alignas(16) float tmp[S]; + for (int i = 0; i < S; ++i) { + tmp[i] = FP4_LUT[wi[i]]; + } + return simd::load(tmp); + } else if constexpr (S == 4 && bits == 8) { + // 4-lane path: load 4 FP8 values from one uint32_t word via LUT. + const uint8_t* bytes = reinterpret_cast(w); + alignas(16) float tmp[S]; + for (int i = 0; i < S; ++i) { + tmp[i] = FP8_LUT[bytes[i]]; + } + return simd::load(tmp); + } else if constexpr (S == 8 && bits == 4) { + // Extract 8 4-bit indices, then SIMD LUT lookup + constexpr std::array shifts_ = {{0, 4, 8, 12, 16, 20, 24, 28}}; + auto shifts(*(simd::Simd*)&shifts_); + auto wi = simd::Simd(*w); + wi = wi >> shifts; + wi = wi & 0xf; + return fp4_lut_lookup_simd(wi, FP4_LUT); + } else if constexpr (S == 8 && bits == 8) { + // 8 FP8 values via SIMD LUT gather + return fp8_lut_gather_simd(w, FP8_LUT); + } else { + // Appease compiler.. but should never get here + throw std::runtime_error("Unsupported combination for simd qmm."); + } +} + +// Process NC output columns simultaneously for FP quantized matmul. +// Loads x once per SIMD chunk and reuses across all columns. +template +void fp_qmm_t_simd_multi_col( + T* result, + const T* x, + const uint32_t* w_ptrs[NC], + const uint8_t* scales_ptrs[NC], + int K, + float scale_factor) { + constexpr int pack_factor = get_pack_factor(bits, 32); + constexpr int S = simd::max_size; + constexpr int iters_per_word = (S >= pack_factor) ? 1 : (pack_factor / S); + constexpr int words_per_iter = (S >= pack_factor) ? (S / pack_factor) : 0; + + simd::Simd acc[NC]; + for (int c = 0; c < NC; c++) + acc[c] = simd::Simd(0); + + auto x_local = x; + for (int k = 0; k < K; k += group_size) { + // Load and dequantize scale for each column + float scale_f[NC]; + for (int c = 0; c < NC; c++) { + scale_f[c] = static_cast( + dequantize_scale(*scales_ptrs[c]++)) * + scale_factor; + } + + simd::Simd g_acc[NC]; + for (int c = 0; c < NC; c++) + g_acc[c] = simd::Simd(0); + + for (int elem = 0; elem < group_size; elem += S) { + // Load x once, reuse for all NC columns + simd::Simd x_simd = load_as_float(x_local); + x_local += S; + + int elem_off = 0; + if constexpr (S < pack_factor) { + elem_off = (elem / S) % iters_per_word; + } + + // Process each column with the same x_simd +#pragma clang loop unroll(full) + for (int c = 0; c < NC; c++) { + auto wf = fp_extract_bits_simd(w_ptrs[c], elem_off); + if constexpr (S >= pack_factor) { + w_ptrs[c] += words_per_iter; + } else { + if (elem_off == iters_per_word - 1) { + w_ptrs[c] += 1; + } + } + g_acc[c] = simd::fma(x_simd, wf, g_acc[c]); + } + } + + // Accumulate group results: acc += scale * g_acc +#pragma clang loop unroll(full) + for (int c = 0; c < NC; c++) { + acc[c] = simd::fma(simd::Simd(scale_f[c]), g_acc[c], acc[c]); + } + } + + for (int c = 0; c < NC; c++) { + result[c] = T(simd::sum(acc[c])); + } +} +#endif + +// Helper for FP quantized matmul row processing (used by parallel version). +// Processes multiple output columns, using multi-column kernel where possible. +template +void fp_qmm_t_simd_row( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int n_start, + int n_end, + int K, + float scale_factor) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + fp_qmm_t_highway_row( + result, + x, + w, + scales, + quantized_highway_dtype(), + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + FP4_LUT, + FP8_LUT); + return; +#else + + constexpr int pack_factor = get_pack_factor(bits, 32); + constexpr int packs_in_group = group_size / pack_factor; + constexpr int S = simd::max_size; + constexpr int iters_per_word = (S >= pack_factor) ? 1 : (pack_factor / S); + constexpr int words_per_iter = (S >= pack_factor) ? (S / pack_factor) : 0; + constexpr int NC = 4; // Process 4 columns at once + + // Compute stride per output column + int groups_per_col = K / group_size; + int packs_per_col = groups_per_col * packs_in_group; + + // Advance pointers to starting column + const uint32_t* w_base = w + n_start * packs_per_col; + const uint8_t* scales_base = scales + n_start * groups_per_col; + + int n = n_start; + + // Process NC columns at a time + for (; n + NC <= n_end; n += NC) { + const uint32_t* wp[NC]; + const uint8_t* sp[NC]; + for (int c = 0; c < NC; c++) { + wp[c] = w_base + c * packs_per_col; + sp[c] = scales_base + c * groups_per_col; + } + fp_qmm_t_simd_multi_col( + result + (n - n_start), x, wp, sp, K, scale_factor); + w_base += NC * packs_per_col; + scales_base += NC * groups_per_col; + } + + // Handle remaining columns one at a time + for (; n < n_end; n++) { + const uint32_t* w_local = w_base; + const uint8_t* scales_local = scales_base; + + simd::Simd acc(0); + auto x_local = x; + for (int k = 0; k < K; k += group_size) { + T scale = static_cast( + static_cast(dequantize_scale(*scales_local++)) * + scale_factor); + + simd::Simd g_acc(0); + for (int elem = 0; elem < group_size; elem += S) { + int elem_off = 0; + if constexpr (S < pack_factor) { + elem_off = (elem / S) % iters_per_word; + } + auto wf = fp_extract_bits_simd(w_local, elem_off); + if constexpr (S >= pack_factor) { + w_local += words_per_iter; + } else { + if (elem_off == iters_per_word - 1) { + w_local += 1; + } + } + simd::Simd x_simd = load_as_float(x_local); + g_acc = simd::fma(x_simd, wf, g_acc); + x_local += S; + } + acc = simd::fma( + simd::Simd(static_cast(scale)), g_acc, acc); + } + + result[n - n_start] = T(simd::sum(acc)); + + // Move to next column + w_base += packs_per_col; + scales_base += groups_per_col; + } +#endif +} + +template +void fp_qmm_t_simd( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int M, + int N, + int K, + float scale_factor) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + fp_qmm_t_highway( + result, + x, + w, + scales, + quantized_highway_dtype(), + bits, + group_size, + M, + N, + K, + scale_factor, + FP4_LUT, + FP8_LUT); + return; +#else + constexpr int pack_factor = get_pack_factor(bits, 32); + constexpr int S = simd::max_size; + static_assert( + S % pack_factor == 0 || pack_factor % S == 0, + "SIMD size and pack factor must be divisible"); + constexpr int iters_per_word = (S >= pack_factor) ? 1 : (pack_factor / S); + constexpr int words_per_iter = (S >= pack_factor) ? (S / pack_factor) : 0; + + auto& pool = cpu::ThreadPool::instance(); + + // N-parallel threading: split columns across threads. + // Each thread processes ALL M rows for its column chunk. + // Weight data per thread fits in L2 cache for much better locality. + int min_cols_per_thread = (M == 1) ? 128 : 64; + int n_threads = + std::min(pool.max_threads(), std::max(1, N / min_cols_per_thread)); + + if (n_threads > 1) { + // Work stealing: 64-column chunks for dynamic load balancing. + // Local counter -- safe for concurrent parallel_for from multiple streams. + constexpr int CHUNK_COLS = 64; + int n_chunks = (N + CHUNK_COLS - 1) / CHUNK_COLS; + alignas(64) std::atomic steal_counter{0}; + steal_counter.store(n_threads, std::memory_order_relaxed); + pool.parallel_for(n_threads, [&](int tid, int /*nth*/) { + int my_chunk = tid; + while (my_chunk < n_chunks) { + int n_start = std::min(my_chunk * CHUNK_COLS, N); + int n_end = std::min(n_start + CHUNK_COLS, N); + if (n_start < n_end) { + for (int m = 0; m < M; m++) { + fp_qmm_t_simd_row( + result + m * N + n_start, + x + m * K, + w, + scales, + n_start, + n_end, + K, + scale_factor); + } + } + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + } + }); + } else { + for (int m = 0; m < M; m++) { + fp_qmm_t_simd_row( + result + m * N, x + m * K, w, scales, 0, N, K, scale_factor); + } + } +#endif +} + +template +void fp_qmm_dispatch_transpose( + T* result, + const T* x, + const uint32_t* w, + const uint8_t* scales, + int M, + int N, + int K, + bool transposed_w, + float scale_factor) { + if (transposed_w) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (bits == 4 || bits == 8) { + fp_qmm_t_simd( + result, x, w, scales, M, N, K, scale_factor); + return; + } +#endif + // SIMD path: S must be >= 4 and must divide pack_factor or vice versa + constexpr int fp_pack_factor = get_pack_factor(bits, 32); + constexpr int S = simd::max_size; + if constexpr ( + S >= 4 && (S % fp_pack_factor == 0 || fp_pack_factor % S == 0) && + group_size % S == 0) { + fp_qmm_t_simd( + result, x, w, scales, M, N, K, scale_factor); + } else { + fp_qmm_t( + result, x, w, scales, M, N, K, scale_factor); + } + } else { + MLX_HIGHWAY_RECORD_FALLBACK(QmmFp); + fp_qmm(result, x, w, scales, M, N, K, scale_factor); + } +} + +template +void fp_qmm_dispatch_mode( + array& out, + const array& x, + const array& w, + const array& scales, + bool transposed_w, + float scale_factor) { + int K = x.shape(-1); + int M = x.ndim() > 1 ? x.shape(-2) : 1; + int N = out.shape(-1); + int w_els = w.ndim() > 2 ? w.shape(-1) * w.shape(-2) : 0; + int g_els = w.ndim() > 2 ? scales.shape(-1) * scales.shape(-2) : 0; + int batch_size = x.size() / (K * M); + + auto out_ptr = out.data(); + auto x_ptr = x.data(); + auto w_ptr = w.data(); + auto scales_ptr = scales.data(); + for (int i = 0; i < batch_size; i++) { + fp_qmm_dispatch_transpose( + out_ptr + i * M * N, + x_ptr + elem_to_loc(i * M * K, x.shape(), x.strides()), + w_ptr + elem_to_loc(i * w_els, w.shape(), w.strides()), + scales_ptr + elem_to_loc(i * g_els, scales.shape(), scales.strides()), + M, + N, + K, + transposed_w, + scale_factor); + } +} + +template +void fp_qmm_dispatch_typed( + array& out, + const array& x, + const array& w, + const array& scales, + int group_size, + int bits, + bool transposed_w, + float scale_factor) { + if (bits == 8) { + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, scale_factor); + } else if (group_size == 32) { + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, scale_factor); + } else { + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, scale_factor); + } +} + +void fp_qmm_dispatch( + array& out, + const array& x, + const array& w, + const array& scales, + int group_size, + int bits, + bool transposed_w, + float scale_factor = 1.0f) { + switch (x.dtype()) { + case bfloat16: + fp_qmm_dispatch_typed( + out, x, w, scales, group_size, bits, transposed_w, scale_factor); + break; + case float16: + fp_qmm_dispatch_typed( + out, x, w, scales, group_size, bits, transposed_w, scale_factor); + break; + case float32: + fp_qmm_dispatch_typed( + out, x, w, scales, group_size, bits, transposed_w, scale_factor); + break; + default: + throw std::invalid_argument( + "[quantized_matmul] only floating types are supported"); + } +} + +template +void _bs_qmm_dispatch_typed( + array& out, + const array& x, + const array& w, + const array& scales, + const array& biases, + const array& lhs_indices, + const array& rhs_indices, + int bits, + int group_size, + bool transposed_w) { + int K = x.shape(-1); + int M = x.shape(-2); + int N = out.shape(-1); + + int w_els = w.shape(-1) * w.shape(-2); + int g_els = scales.shape(-1) * scales.shape(-2); + + auto out_ptr = out.data(); + auto x_ptr = x.data(); + auto w_ptr = w.data(); + auto scales_ptr = scales.data(); + auto biases_ptr = biases.data(); + auto lhs_indices_ptr = lhs_indices.data(); + auto rhs_indices_ptr = rhs_indices.data(); + + // Precompute offsets for batching + int total = lhs_indices.size(); + std::vector x_offsets(total); + std::vector w_idxs(total); + for (int i = 0; i < total; i++) { + int x_idx = lhs_indices_ptr[elem_to_loc( + i, lhs_indices.shape(), lhs_indices.strides())]; + w_idxs[i] = rhs_indices_ptr[elem_to_loc( + i, rhs_indices.shape(), rhs_indices.strides())]; + x_offsets[i] = elem_to_loc(x_idx * M * K, x.shape(), x.strides()); + } + + // Batch consecutive same-expert entries with contiguous x data + int i = 0; + while (i < total) { + int batch_count = 1; + size_t x_stride = static_cast(M) * K; + while (i + batch_count < total && w_idxs[i + batch_count] == w_idxs[i] && + x_offsets[i + batch_count] == + x_offsets[i] + batch_count * x_stride) { + batch_count++; + } + int w_idx = w_idxs[i]; + _qmm_dispatch_typed( + out_ptr + i * M * N, + x_ptr + x_offsets[i], + w_ptr + elem_to_loc(w_idx * w_els, w.shape(), w.strides()), + scales_ptr + + elem_to_loc(w_idx * g_els, scales.shape(), scales.strides()), + biases_ptr + + elem_to_loc(w_idx * g_els, biases.shape(), biases.strides()), + M * batch_count, + N, + K, + bits, + group_size, + transposed_w); + i += batch_count; + } +} + +void _bs_qmm_dispatch( + array& out, + const array& x, + const array& w, + const array& scales, + const array& biases, + const array& lhs_indices, + const array& rhs_indices, + int bits, + int group_size, + bool transposed_w) { + switch (x.dtype()) { + case float32: + _bs_qmm_dispatch_typed( + out, + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + bits, + group_size, + transposed_w); + break; + case float16: + _bs_qmm_dispatch_typed( + out, + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + bits, + group_size, + transposed_w); + break; + case bfloat16: + _bs_qmm_dispatch_typed( + out, + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + bits, + group_size, + transposed_w); + break; + default: + throw std::invalid_argument( + "[quantized_matmul] only floating types are supported"); + } +} +template +void fp_bs_qmm_dispatch_mode( + array& out, + const array& x, + const array& w, + const array& scales, + const array& lhs_indices, + const array& rhs_indices, + bool transposed_w) { + int K = x.shape(-1); + int M = x.shape(-2); + int N = out.shape(-1); + + int w_els = w.shape(-1) * w.shape(-2); + int g_els = scales.shape(-1) * scales.shape(-2); + + auto out_ptr = out.data(); + auto x_ptr = x.data(); + auto w_ptr = w.data(); + auto scales_ptr = scales.data(); + auto lhs_indices_ptr = lhs_indices.data(); + auto rhs_indices_ptr = rhs_indices.data(); + + int total = lhs_indices.size(); + + // Precompute all offsets + std::vector x_offsets(total); + std::vector w_offsets(total); + std::vector s_offsets(total); + for (int i = 0; i < total; i++) { + int x_idx = lhs_indices_ptr[elem_to_loc( + i, lhs_indices.shape(), lhs_indices.strides())]; + int w_idx = rhs_indices_ptr[elem_to_loc( + i, rhs_indices.shape(), rhs_indices.strides())]; + x_offsets[i] = elem_to_loc(x_idx * M * K, x.shape(), x.strides()); + w_offsets[i] = elem_to_loc(w_idx * w_els, w.shape(), w.strides()); + s_offsets[i] = elem_to_loc(w_idx * g_els, scales.shape(), scales.strides()); + } + + // For MoE dispatch (many entries, M=1, transposed weights with SIMD support): + // Use outer-level parallelism -- distribute all entries across threads with + // a single parallel_for, instead of running nested parallel_for per entry. + constexpr int fp_pack_factor = get_pack_factor(bits, 32); + constexpr int S = simd::max_size; + auto& pool = cpu::ThreadPool::instance(); + + if (total > pool.max_threads() && M == 1 && transposed_w && S >= 4 && + (S % fp_pack_factor == 0 || fp_pack_factor % S == 0) && + group_size % S == 0) { + int n_threads = std::min(pool.max_threads(), total); + pool.parallel_for(n_threads, [&](int tid, int nth) { + int chunk = (total + nth - 1) / nth; + int start = chunk * tid; + int end = std::min(start + chunk, total); + for (int j = start; j < end; j++) { + fp_qmm_t_simd_row( + out_ptr + j * N, + x_ptr + x_offsets[j], + w_ptr + w_offsets[j], + scales_ptr + s_offsets[j], + 0, + N, + K, + 1.0f); + } + }); + return; + } + + // Fallback: sequential with batching for contiguous same-expert entries + for (int i = 0; i < total;) { + int batch_count = 1; + size_t x_stride = static_cast(M) * K; + while ( + i + batch_count < total && w_offsets[i + batch_count] == w_offsets[i] && + s_offsets[i + batch_count] == s_offsets[i] && + x_offsets[i + batch_count] == x_offsets[i] + batch_count * x_stride) { + batch_count++; + } + fp_qmm_dispatch_transpose( + out_ptr + i * M * N, + x_ptr + x_offsets[i], + w_ptr + w_offsets[i], + scales_ptr + s_offsets[i], + M * batch_count, + N, + K, + transposed_w, + 1.0f); + i += batch_count; + } +} + +template +void fp_bs_qmm_dispatch_typed( + array& out, + const array& x, + const array& w, + const array& scales, + const array& lhs_indices, + const array& rhs_indices, + int group_size, + int bits, + bool transposed_w) { + if (bits == 8) { + fp_bs_qmm_dispatch_mode( + out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + } else if (group_size == 32) { + fp_bs_qmm_dispatch_mode( + out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + } else { + fp_bs_qmm_dispatch_mode( + out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + } +} + +void fp_bs_qmm_dispatch( + array& out, + const array& x, + const array& w, + const array& scales, + const array& lhs_indices, + const array& rhs_indices, + int group_size, + int bits, + bool transposed_w) { + switch (x.dtype()) { + case float32: + fp_bs_qmm_dispatch_typed( + out, + x, + w, + scales, + lhs_indices, + rhs_indices, + group_size, + bits, + transposed_w); + break; + case float16: + fp_bs_qmm_dispatch_typed( + out, + x, + w, + scales, + lhs_indices, + rhs_indices, + group_size, + bits, + transposed_w); + break; + case bfloat16: + fp_bs_qmm_dispatch_typed( + out, + x, + w, + scales, + lhs_indices, + rhs_indices, + group_size, + bits, + transposed_w); + break; + default: + throw std::invalid_argument( + "[quantized_matmul] only floating types are supported"); + } +} + +uint8_t to_fp8_e8m0(float x) { + if (!std::isfinite(x)) { + return 0xFF; + } + if (x < 0.0f) { + return 0x00; + } + float le = std::log2(x); + int n = int(std::round(le)); + + n = n < -127 ? -127 : n; + n = n > 127 ? 127 : n; + return static_cast(n + 127); +} + +// Smallest E8M0 >= x, so a block's largest elements do not saturate. +uint8_t to_fp8_e8m0_round_up(float x) { + uint8_t bits = to_fp8_e8m0(x); + if (bits < 0xFE && dequantize_scale(bits) < x) { + bits += 1; + } + return bits; +} + +uint8_t to_fp4_e2m1(float x) { + if (std::isnan(x)) { + return 0x7; + } + + const uint8_t sign_bit = (std::signbit(x)) ? 0x8 : 0x0; + x = std::abs(x); + + uint8_t bits; + if (x > 5.0f) { + bits = 0x7; + } else if (x >= 3.5f) { + bits = 0x6; + } else if (x > 2.5f) { + bits = 0x5; + } else if (x >= 1.75f) { + bits = 0x4; + } else if (x > 1.25f) { + bits = 0x3; + } else if (x >= 0.75f) { + bits = 0x2; + } else if (x > 0.25f) { + bits = 0x1; + } else { + bits = 0x0; + } + return bits | sign_bit; +} + +// Quantize then dequantize x in-place, simulating quantization noise. +// For nvfp4 (group_size=16, bits=4): scale via fp8_e4m3, values via FP4 LUT. +// For mxfp8 (group_size=32, bits=8): scale via fp8_e8m0 (exponent-only), values +// via fp8_e4m3. +template +void quantize_dequantize_fp( + T* data, + int size, + int group_size, + int bits, + QuantizationMode mode, + float global_scale) { + detail::ToFP8 to_fp8; + detail::FromFP8 from_fp8; + + float maxval = (bits == 4) ? 6.0f : 448.0f; + int n_groups = size / group_size; + + for (int g = 0; g < n_groups; g++) { + T* gp = data + g * group_size; + + // Per-group absolute max + float amax = 0; + for (int i = 0; i < group_size; i++) { + amax = std::max(amax, std::abs(static_cast(gp[i]))); + } + float raw_scale = amax / maxval; + + float scale; + if (mode == QuantizationMode::Nvfp4) { + // fp8_e4m3 scale + float scale_encode = + global_scale > 0.0f ? (448.0f * 6.0f) / global_scale : 1.0f; + uint8_t scale_fp8 = to_fp8(raw_scale * scale_encode); + scale = from_fp8(scale_fp8) / scale_encode; + } else { + // The smallest E8M0 scale not below raw_scale, as upstream (#4353), so a + // block's largest elements do not saturate. + scale = raw_scale == 0.0f + ? 1.0f + : dequantize_scale(to_fp8_e8m0_round_up(raw_scale)); + } + + if (scale == 0.0f) { + for (int i = 0; i < group_size; i++) { + gp[i] = static_cast(0.0f); + } + continue; + } + + float inv_scale = 1.0f / scale; + + if (bits == 4) { + // Round to nearest FP4 LUT value, then multiply by scale + for (int i = 0; i < group_size; i++) { + float normalized = static_cast(gp[i]) * inv_scale; + // Round half to even on the e2m1 grid, as upstream's to_fp4_e2m1. + gp[i] = static_cast(FP4_LUT[to_fp4_e2m1(normalized)] * scale); + } + } else { + // Round-trip through fp8_e4m3 + for (int i = 0; i < group_size; i++) { + float normalized = static_cast(gp[i]) * inv_scale; + uint8_t fp8 = to_fp8(normalized); + gp[i] = static_cast(from_fp8(fp8) * scale); + } + } + } +} + +void quantize_dequantize_fp_dispatch( + array& x, + int group_size, + int bits, + QuantizationMode mode, + float global_scale = 0.0f) { + switch (x.dtype()) { + case float32: + quantize_dequantize_fp( + x.data(), x.size(), group_size, bits, mode, global_scale); + break; + case float16: + quantize_dequantize_fp( + x.data(), x.size(), group_size, bits, mode, global_scale); + break; + case bfloat16: + quantize_dequantize_fp( + x.data(), x.size(), group_size, bits, mode, global_scale); + break; + default: + throw std::runtime_error( + "[QQMatmul] Only floating point types are supported"); + } +} + + +} // namespace + +void cpu::quantized_matmul_highway( + const std::vector& inputs, + array& out, + Stream stream, + QuantizationMode mode_, + int group_size_, + int bits_, + bool transpose_) { + auto& x_pre = inputs[0]; + auto& w_pre = inputs[1]; + auto& scales_pre = inputs[2]; + + auto& encoder = cpu::get_command_encoder(stream); + auto ensure_row_contiguous = [s = stream, &encoder](const array& arr) { + if (arr.flags().row_contiguous) { + return arr; + } else { + auto arr_cpy = array(arr.shape(), arr.dtype(), nullptr, {}); + copy_cpu(arr, arr_cpy, CopyType::General, s); + encoder.add_temporary(arr_cpy); + return arr_cpy; + } + }; + + auto x = ensure_row_contiguous(x_pre); + auto w = ensure_row_contiguous(w_pre); + auto scales = ensure_row_contiguous(scales_pre); + + out.set_data(allocator::malloc(out.nbytes())); + + encoder.set_input_array(x); + encoder.set_input_array(w); + encoder.set_input_array(scales); + encoder.set_output_array(out); + if (mode_ == QuantizationMode::Affine) { + auto biases = ensure_row_contiguous(inputs[3]); + encoder.set_input_array(biases); + encoder.dispatch([out = array::unsafe_weak_copy(out), + x = array::unsafe_weak_copy(x), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + biases = array::unsafe_weak_copy(biases), + group_size_ = group_size_, + bits_ = bits_, + transpose_ = transpose_]() mutable { + _qmm_dispatch(out, x, w, scales, biases, group_size_, bits_, transpose_); + }); + } else { + encoder.dispatch([out = array::unsafe_weak_copy(out), + x = array::unsafe_weak_copy(x), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + group_size_ = group_size_, + bits_ = bits_, + transpose_ = transpose_]() mutable { + fp_qmm_dispatch(out, x, w, scales, group_size_, bits_, transpose_); + }); + } +} + +void cpu::gather_qmm_highway( + const std::vector& inputs, + array& out, + Stream stream, + QuantizationMode mode_, + int group_size_, + int bits_, + bool transpose_) { + auto& x_pre = inputs[0]; + auto& w_pre = inputs[1]; + auto& scales_pre = inputs[2]; + auto& lhs_indices = inputs[inputs.size() - 2]; + auto& rhs_indices = inputs[inputs.size() - 1]; + + auto& encoder = cpu::get_command_encoder(stream); + auto ensure_row_contiguous_last_dims = [s = stream, + &encoder](const array& arr) { + auto stride_0 = arr.strides()[arr.ndim() - 2]; + auto stride_1 = arr.strides()[arr.ndim() - 1]; + if (stride_0 == arr.shape(-1) && stride_1 == 1) { + return arr; + } else { + auto arr_cpy = array(arr.shape(), arr.dtype(), nullptr, {}); + copy_cpu(arr, arr_cpy, CopyType::General, s); + encoder.add_temporary(arr_cpy); + return arr_cpy; + } + }; + + auto x = ensure_row_contiguous_last_dims(x_pre); + auto w = ensure_row_contiguous_last_dims(w_pre); + auto scales = ensure_row_contiguous_last_dims(scales_pre); + + out.set_data(allocator::malloc(out.nbytes())); + + encoder.set_input_array(x); + encoder.set_input_array(w); + encoder.set_input_array(scales); + encoder.set_input_array(lhs_indices); + encoder.set_input_array(rhs_indices); + encoder.set_output_array(out); + if (mode_ == QuantizationMode::Affine) { + auto biases = ensure_row_contiguous_last_dims(inputs[3]); + encoder.set_input_array(biases); + encoder.dispatch([out = array::unsafe_weak_copy(out), + x = array::unsafe_weak_copy(x), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + biases = array::unsafe_weak_copy(biases), + lhs_indices = array::unsafe_weak_copy(lhs_indices), + rhs_indices = array::unsafe_weak_copy(rhs_indices), + group_size_ = group_size_, + bits_ = bits_, + transpose_ = transpose_]() mutable { + _bs_qmm_dispatch( + out, + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + group_size_, + bits_, + transpose_); + }); + } else { + encoder.dispatch([out = array::unsafe_weak_copy(out), + x = array::unsafe_weak_copy(x), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + lhs_indices = array::unsafe_weak_copy(lhs_indices), + rhs_indices = array::unsafe_weak_copy(rhs_indices), + group_size_ = group_size_, + bits_ = bits_, + transpose_ = transpose_]() mutable { + fp_bs_qmm_dispatch( + out, + x, + w, + scales, + lhs_indices, + rhs_indices, + group_size_, + bits_, + transpose_); + }); + } +} + +template +void quantize( + const T* w, + U* out, + T* scales, + T* biases, + int bits, + int group_size, + size_t w_size) { + float n_bins = (1 << bits) - 1; + float eps = 1e-7; + + bool power_of_2_bits = is_power_of_2(bits); + int el_per_int = get_pack_factor(bits, 32); + int bytes_per_pack = get_bytes_per_pack(bits); + int int_per_group = group_size * bytes_per_pack / el_per_int; + size_t n_groups = w_size / group_size; + + for (size_t i = 0; i < n_groups; ++i) { + size_t w_idx = i * group_size; + float w_min = std::numeric_limits::infinity(); + float w_max = -w_min; + for (int j = 0; j < group_size; ++j) { + w_max = std::max(w_max, (float)w[w_idx + j]); + w_min = std::min(w_min, (float)w[w_idx + j]); + } + bool mask = std::abs(w_min) > std::abs(w_max); + float scale = std::max((w_max - w_min) / n_bins, eps); + scale = mask ? scale : -scale; + + float edge = mask ? w_min : w_max; + float q0 = std::rint(edge / scale); + float bias = 0; + if (q0 != 0) { + scale = edge / q0; + bias = edge; + } + size_t out_idx = i * int_per_group; + for (int j = 0; j < int_per_group / bytes_per_pack; ++j) { + uint64_t out_el = 0; + for (int k = 0; k < el_per_int; ++k) { + float w_el = w[w_idx + j * el_per_int + k]; + w_el = std::rint((w_el - bias) / scale); + w_el = std::min(std::max(w_el, 0.0f), n_bins); + out_el |= static_cast(w_el) << (k * bits); + } + if (power_of_2_bits) { + out[out_idx + j] = out_el; + } else if (bits == 5) { + out[out_idx + bytes_per_pack * j] = out_el & 0xff; + out[out_idx + bytes_per_pack * j + 1] = (out_el & 0xff00) >> 8; + out[out_idx + bytes_per_pack * j + 2] = (out_el & 0xff0000) >> 16; + out[out_idx + bytes_per_pack * j + 3] = (out_el & 0xff000000) >> 24; + out[out_idx + bytes_per_pack * j + 4] = (out_el & 0xff00000000) >> 32; + } else { + out[out_idx + bytes_per_pack * j] = out_el & 0xff; + out[out_idx + bytes_per_pack * j + 1] = (out_el & 0xff00) >> 8; + out[out_idx + bytes_per_pack * j + 2] = (out_el & 0xff0000) >> 16; + } + } + scales[i] = static_cast(scale); + biases[i] = static_cast(bias); + } +} + +template +void dispatch_quantize( + const array& w, + array& out, + array& scales, + array& biases, + int bits, + int group_size) { + auto w_ptr = w.data(); + auto out_ptr = out.data(); + auto scales_ptr = scales.data(); + auto biases_ptr = biases.data(); + quantize( + w_ptr, out_ptr, scales_ptr, biases_ptr, bits, group_size, w.size()); +} + +void cpu::quantize_affine_highway( + const std::vector& inputs, + std::vector& outputs, + Stream stream, + int group_size_, + int bits_) { + auto ensure_row_contiguous = [s = stream](const array& arr) { + if (arr.flags().row_contiguous) { + return std::make_pair(arr, false); + } else { + return std::make_pair(contiguous_copy_cpu(arr, s), true); + } + }; + + auto [w, copied] = ensure_row_contiguous(inputs[0]); + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + + auto& scales = outputs[1]; + auto& biases = outputs[2]; + scales.set_data(allocator::malloc(scales.nbytes())); + biases.set_data(allocator::malloc(biases.nbytes())); + auto& encoder = cpu::get_command_encoder(stream); + if (copied) { + encoder.add_temporary(w); + } + encoder.set_input_array(w); + encoder.set_input_array(scales); + encoder.set_input_array(biases); + encoder.set_output_array(out); + encoder.dispatch([w = array::unsafe_weak_copy(w), + out = array::unsafe_weak_copy(out), + scales = array::unsafe_weak_copy(scales), + biases = array::unsafe_weak_copy(biases), + group_size_ = group_size_, + bits_ = bits_]() mutable { + if (w.dtype() == float16) { + if (is_power_of_2(bits_)) { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } else { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } + } else if (w.dtype() == bfloat16) { + if (is_power_of_2(bits_)) { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } else { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } + } else if (w.dtype() == float32) { + if (is_power_of_2(bits_)) { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } else { + dispatch_quantize( + w, out, scales, biases, bits_, group_size_); + } + } else { + throw std::runtime_error( + "[fast::Quantize::eval_cpu] Only supports floating point inputs"); + } + }); +} + +void fast::ConvertFP8::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + auto& in = inputs[0]; + auto& out = outputs[0]; + set_unary_output_data(in, out); + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(in); + encoder.set_output_array(out); + encoder.dispatch([in = array::unsafe_weak_copy(in), + out = array::unsafe_weak_copy(out), + to_fp8 = to_fp8_]() mutable { + if (to_fp8) { + switch (in.dtype()) { + case float16: + unary_op(in, out, detail::ToFP8()); + break; + case bfloat16: + unary_op(in, out, detail::ToFP8()); + break; + default: + unary_op(in, out, detail::ToFP8()); + break; + } + } else { + switch (out.dtype()) { + case float16: + unary_op(in, out, detail::FromFP8()); + break; + case bfloat16: + unary_op(in, out, detail::FromFP8()); + break; + default: + unary_op(in, out, detail::FromFP8()); + break; + } + } + }); +} + +void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { + if (cpu::empty_qmm_cpu(inputs[0], out, stream())) { + return; + } + // No path here quantizes w; quantized.cpp raises the same error. + if (inputs[1].dtype() != uint32) { + throw std::runtime_error("[QQMatmul] NYI for the general case"); + } + auto& encoder = cpu::get_command_encoder(stream()); + auto ensure_row_contiguous = [s = stream(), &encoder](const array& arr) { + if (arr.flags().row_contiguous) { + return arr; + } else { + auto arr_cpy = array(arr.shape(), arr.dtype(), nullptr, {}); + copy_cpu(arr, arr_cpy, CopyType::General, s); + encoder.add_temporary(arr_cpy); + return arr_cpy; + } + }; + + auto x = ensure_row_contiguous(inputs[0]); + auto w = ensure_row_contiguous(inputs[1]); + auto scales = ensure_row_contiguous(inputs[2]); + bool has_global_scales = + mode_ == QuantizationMode::Nvfp4 && inputs.size() == 5; + array global_scale_x(0.0f, float32); + array global_scale_w(0.0f, float32); + if (has_global_scales) { + global_scale_x = ensure_row_contiguous(inputs[3]); + global_scale_w = ensure_row_contiguous(inputs[4]); + } + + out.set_data(allocator::malloc(out.nbytes())); + + // Create a copy of x for quantize-dequantize (simulates quantization noise) + auto x_hat = array(x.shape(), x.dtype(), nullptr, {}); + copy_cpu(x, x_hat, CopyType::General, stream()); + encoder.add_temporary(x_hat); + + encoder.set_input_array(x_hat); + encoder.set_input_array(w); + encoder.set_input_array(scales); + if (has_global_scales) { + encoder.set_input_array(global_scale_x); + encoder.set_input_array(global_scale_w); + } + encoder.set_output_array(out); + encoder.dispatch([out = array::unsafe_weak_copy(out), + x_hat = array::unsafe_weak_copy(x_hat), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + global_scale_x = array::unsafe_weak_copy(global_scale_x), + global_scale_w = array::unsafe_weak_copy(global_scale_w), + has_global_scales, + group_size = group_size_, + bits = bits_, + mode = mode_]() mutable { + float x_global_scale = 0.0f; + float w_scale_factor = 1.0f; + if (has_global_scales) { + x_global_scale = global_scale_x.data()[0]; + w_scale_factor = global_scale_w.data()[0] / (448.0f * 6.0f); + } + // Quantize-dequantize x in-place to simulate input quantization noise + quantize_dequantize_fp_dispatch( + x_hat, group_size, bits, mode, x_global_scale); + // Compute x_hat @ dequant(w) using existing FP quantized matmul + fp_qmm_dispatch( + out, x_hat, w, scales, group_size, bits, true, w_scale_factor); + }); +} + +void GatherQQMM::eval_cpu(const std::vector& inputs, array& out) { + throw std::runtime_error("[GatherQQMM] NYI"); +} + +} // namespace mlx::core +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/quantized_highway_dispatch.cpp b/mlx/backend/cpu/quantized_highway_dispatch.cpp new file mode 100644 index 0000000000..751aeafd25 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway_dispatch.cpp @@ -0,0 +1,333 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/quantized_highway.h" + +#include "hwy/highway.h" + +namespace mlx::core { + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) + +using DequantRowFn = + void (*)(const uint32_t*, const float*, const float*, float*, int, int); +using QuantizeActivationInt8Fn = void (*)( + const void*, + QuantizedHighwayDType, + int, + int, + int8_t*, + float*, + float*); +using QmmTInt8RowFn = void (*)( + float*, + const int8_t*, + const float*, + const float*, + const uint32_t*, + const void*, + const void*, + QuantizedHighwayDType, + int, + int, + int, + int, + int); +using QmmTInt8Fn = bool (*)( + void*, + const void*, + const uint32_t*, + const void*, + const void*, + QuantizedHighwayDType, + int, + int, + int, + int, + int); +using FpQmmTHighwayRowFn = void (*)( + void*, + const void*, + const uint32_t*, + const uint8_t*, + QuantizedHighwayDType, + int, + int, + int, + int, + int, + float, + const float*, + const float*); +using FpQmmTHighwayFn = void (*)( + void*, + const void*, + const uint32_t*, + const uint8_t*, + QuantizedHighwayDType, + int, + int, + int, + int, + int, + float, + const float*, + const float*); +#define MLX_DECLARE_QUANTIZED_TARGET(suffix) \ + void MLX_HIGHWAY_CONCAT(dequant_row_highway_4bit, suffix)( \ + const uint32_t*, const float*, const float*, float*, int, int); \ + void MLX_HIGHWAY_CONCAT(dequant_row_highway_8bit, suffix)( \ + const uint32_t*, const float*, const float*, float*, int, int); \ + void MLX_HIGHWAY_CONCAT(quantize_activation_int8_highway, suffix)( \ + const void*, QuantizedHighwayDType, int, int, int8_t*, float*, float*); \ + void MLX_HIGHWAY_CONCAT(qmm_t_int8_highway_row, suffix)( \ + float*, \ + const int8_t*, \ + const float*, \ + const float*, \ + const uint32_t*, \ + const void*, \ + const void*, \ + QuantizedHighwayDType, \ + int, \ + int, \ + int, \ + int, \ + int); \ + bool MLX_HIGHWAY_CONCAT(qmm_t_int8_highway, suffix)( \ + void*, \ + const void*, \ + const uint32_t*, \ + const void*, \ + const void*, \ + QuantizedHighwayDType, \ + int, \ + int, \ + int, \ + int, \ + int); \ + void MLX_HIGHWAY_CONCAT(fp_qmm_t_highway_row, suffix)( \ + void*, \ + const void*, \ + const uint32_t*, \ + const uint8_t*, \ + QuantizedHighwayDType, \ + int, \ + int, \ + int, \ + int, \ + int, \ + float, \ + const float*, \ + const float*); \ + void MLX_HIGHWAY_CONCAT(fp_qmm_t_highway, suffix)( \ + void*, \ + const void*, \ + const uint32_t*, \ + const uint8_t*, \ + QuantizedHighwayDType, \ + int, \ + int, \ + int, \ + int, \ + int, \ + float, \ + const float*, \ + const float*) + +MLX_DECLARE_QUANTIZED_TARGET(_avx2); +MLX_DECLARE_QUANTIZED_TARGET(_sse4); +MLX_DECLARE_QUANTIZED_TARGET(_ssse3); +MLX_DECLARE_QUANTIZED_TARGET(_sse2); + +#undef MLX_DECLARE_QUANTIZED_TARGET + +namespace { + +struct QuantizedHighwayDispatch { + DequantRowFn dequant4; + DequantRowFn dequant8; + QuantizeActivationInt8Fn quantize_activation_int8; + QmmTInt8RowFn qmm_t_int8_row; + QmmTInt8Fn qmm_t_int8; + FpQmmTHighwayRowFn fp_qmm_t_row; + FpQmmTHighwayFn fp_qmm_t; +}; + +#define MLX_QUANTIZED_DISPATCH(suffix) \ + QuantizedHighwayDispatch { \ + MLX_HIGHWAY_CONCAT(dequant_row_highway_4bit, suffix), \ + MLX_HIGHWAY_CONCAT(dequant_row_highway_8bit, suffix), \ + MLX_HIGHWAY_CONCAT(quantize_activation_int8_highway, suffix), \ + MLX_HIGHWAY_CONCAT(qmm_t_int8_highway_row, suffix), \ + MLX_HIGHWAY_CONCAT(qmm_t_int8_highway, suffix), \ + MLX_HIGHWAY_CONCAT(fp_qmm_t_highway_row, suffix), \ + MLX_HIGHWAY_CONCAT(fp_qmm_t_highway, suffix) \ + } + +const QuantizedHighwayDispatch& quantized_dispatch() { + static const QuantizedHighwayDispatch dispatch = [] { + const int64_t targets = hwy::SupportedTargets(); + if (targets & HWY_AVX2) { + return MLX_QUANTIZED_DISPATCH(_avx2); + } + if (targets & HWY_SSE4) { + return MLX_QUANTIZED_DISPATCH(_sse4); + } + if (targets & HWY_SSSE3) { + return MLX_QUANTIZED_DISPATCH(_ssse3); + } + return MLX_QUANTIZED_DISPATCH(_sse2); + }(); + return dispatch; +} + +#undef MLX_QUANTIZED_DISPATCH +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +} // namespace + +void dequant_row_highway_4bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + quantized_dispatch().dequant4( + w_row, scales_row, biases_row, out, group_size, K); +} + +void dequant_row_highway_8bit( + const uint32_t* w_row, + const float* scales_row, + const float* biases_row, + float* out, + int group_size, + int K) { + quantized_dispatch().dequant8( + w_row, scales_row, biases_row, out, group_size, K); +} + +void quantize_activation_int8_highway( + const void* x, + QuantizedHighwayDType dtype, + int K, + int group_size, + int8_t* x_q, + float* x_scales, + float* x_group_sums) { + quantized_dispatch().quantize_activation_int8( + x, dtype, K, group_size, x_q, x_scales, x_group_sums); +} + +void qmm_t_int8_highway_row( + float* result, + const int8_t* x_q, + const float* x_scales, + const float* x_group_sums, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K) { + quantized_dispatch().qmm_t_int8_row( + result, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + dtype, + bits, + group_size, + n_start, + n_end, + K); +} + +bool qmm_t_int8_highway( + void* result, + const void* x, + const uint32_t* w, + const void* scales, + const void* biases, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K) { + return quantized_dispatch().qmm_t_int8( + result, x, w, scales, biases, dtype, bits, group_size, M, N, K); +} + +void fp_qmm_t_highway_row( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int n_start, + int n_end, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + quantized_dispatch().fp_qmm_t_row( + result, + x, + w, + scales, + dtype, + bits, + group_size, + n_start, + n_end, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +void fp_qmm_t_highway( + void* result, + const void* x, + const uint32_t* w, + const uint8_t* scales, + QuantizedHighwayDType dtype, + int bits, + int group_size, + int M, + int N, + int K, + float scale_factor, + const float* fp4_lut, + const float* fp8_lut) { + quantized_dispatch().fp_qmm_t( + result, + x, + w, + scales, + dtype, + bits, + group_size, + M, + N, + K, + scale_factor, + fp4_lut, + fp8_lut); +} + +} // namespace mlx::core +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index b3de1e9ffa..1e09560f62 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -7,6 +7,9 @@ #include "mlx/backend/common/reduce.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/primitives.h" namespace mlx::core { @@ -71,11 +74,18 @@ const complex64_t Limits::min = template struct ReductionAccumulator { static constexpr int N = std::min(simd::max_size, simd::max_size); +#if defined(MLX_USE_HIGHWAY_KERNELS) + // The facade's float16 arithmetic already runs in float: widen float16 sums + // and products at every width. + static constexpr bool widen_to_float = + std::is_same_v || std::is_same_v; +#else // Widen to float32 only if the input is float16 (with N=1) or bfloat16 as it // improves performance. static constexpr bool widen_to_float = (std::is_same_v || (N == 1 && std::is_same_v)); +#endif // MLX_USE_HIGHWAY_KERNELS using type = std::conditional_t; }; @@ -144,6 +154,57 @@ void strided_reduce( strided_reduce_block(x, accumulator, size, stride, op); } +#if defined(MLX_USE_HIGHWAY_KERNELS) +// Accumulator type: use float for half-precision types to avoid precision loss +template +struct AccumType { + using type = U; +}; +template <> +struct AccumType { + using type = float; +}; +template <> +struct AccumType { + using type = float; +}; + +#endif // MLX_USE_HIGHWAY_KERNELS +#if defined(MLX_USE_HIGHWAY_KERNELS) +template +A contiguous_accumulate_block(const T* x, int size, Op op, A acc, A init) { + constexpr int N = std::min(simd::max_size, simd::max_size); + simd::Simd accumulator_v(init); + while (size >= N) { + accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); + x += N; + size -= N; + } + A result = op(acc, op(accumulator_v)); + while (size-- > 0) { + result = op(result, static_cast(*x)); + x++; + } + return result; +} + +template +A contiguous_accumulate(const T* x, int size, Op op, A acc, A init) { + if constexpr (cascade_sum) { + for (; size > sum_block; size -= sum_block, x += sum_block) { + acc = contiguous_accumulate_block(x, sum_block, op, acc, init); + } + } + return contiguous_accumulate_block(x, size, op, acc, init); +} + +template +void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) { + using A = typename AccumType::type; + *accumulator = static_cast(contiguous_accumulate( + x, size, op, static_cast(*accumulator), static_cast(init))); +} +#else template void contiguous_reduce_block( const T* x, @@ -180,7 +241,57 @@ void contiguous_reduce( } contiguous_reduce_block(x, accumulator, size, op, init); } +#endif // MLX_USE_HIGHWAY_KERNELS + +#if defined(MLX_USE_HIGHWAY_KERNELS) +// Parallel version for large reductions +template +U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { + using A = typename AccumType::type; + auto& pool = cpu::ThreadPool::instance(); + int max_threads = pool.max_threads(); + int n_threads = cpu::effective_threads(size, max_threads); + + if (n_threads <= 1) { + U result = init; + contiguous_reduce(x, &result, static_cast(size), op, init); + return result; + } + + // Each thread computes a partial reduction. Keep each partial on its own + // cache line to avoid false sharing while preserving A's alignment/lifetime. + struct alignas(64) Partial { + A value; + }; + std::vector partials(n_threads); + + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size); + + A* partial = &partials[tid].value; + *partial = static_cast(init); + + if (start < end) { + *partial = contiguous_accumulate( + x + start, + static_cast(end - start), + op, + static_cast(init), + static_cast(init)); + } + }); + + // Final reduction of partial results + A result = static_cast(init); + for (int i = 0; i < n_threads; ++i) { + result = op(result, partials[i].value); + } + return static_cast(result); +} +#endif // MLX_USE_HIGHWAY_KERNELS // Helper for the ndimensional strided loop void nd_loop( std::function callback, @@ -216,16 +327,58 @@ void reduction_op( auto in_ptr = x.data(); auto out_ptr = out.data(); if (plan.type == ContiguousAllReduce) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) *out_ptr = init; contiguous_reduce(in_ptr, out_ptr, x.size(), Op{}, init); +#else + // Use parallel reduction for large arrays + *out_ptr = parallel_contiguous_reduce(in_ptr, x.size(), Op{}, init); +#endif // MLX_USE_HIGHWAY_KERNELS return; } if (plan.type == ContiguousReduce && plan.shape.size() == 1) { int reduction_size = plan.shape[0]; +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int i = 0; i < out.size(); i++, out_ptr++, in_ptr += reduction_size) { *out_ptr = init; contiguous_reduce(in_ptr, out_ptr, reduction_size, Op{}, init); +#else + int num_reductions = out.size(); + + // Parallelize over output elements (each is an independent reduction) + // Only parallelize if total work is large enough AND each thread gets + // enough work + auto& pool = cpu::ThreadPool::instance(); + size_t total_elements = + static_cast(num_reductions) * reduction_size; + int n_threads = cpu::effective_threads(total_elements, pool.max_threads()); + + // Also ensure each thread handles at least a few reductions to amortize + // overhead + n_threads = std::min(n_threads, std::max(1, num_reductions / 4)); + + if (n_threads <= 1) { + for (int i = 0; i < num_reductions; + i++, out_ptr++, in_ptr += reduction_size) { + *out_ptr = init; + contiguous_reduce(in_ptr, out_ptr, reduction_size, Op{}, init); + } + } else { + pool.parallel_for(n_threads, [&, in_ptr, out_ptr](int tid, int nth) { + int chunk = (num_reductions + nth - 1) / nth; + int start = chunk * tid; + int end = std::min(start + chunk, num_reductions); + + const T* my_in = in_ptr + start * reduction_size; + U* my_out = out_ptr + start; + + for (int i = start; i < end; i++, my_out++, my_in += reduction_size) { + *my_out = init; + contiguous_reduce(my_in, my_out, reduction_size, Op{}, init); + } + }); +#endif // MLX_USE_HIGHWAY_KERNELS } return; } diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp new file mode 100644 index 0000000000..609f5005e2 --- /dev/null +++ b/mlx/backend/cpu/rope.cpp @@ -0,0 +1,593 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include +#include +#include + +#include "mlx/allocator.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/fast_primitives.h" +#include "mlx/transforms.h" + +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/rope_highway.h" +#endif + +namespace mlx::core::fast { + +// ISA-specific SIMD implementations for RoPE. Highway kernels are compiled as +// runtime-dispatched translation units when x86 CPU SIMD is enabled. +#if !defined(MLX_USE_HIGHWAY_KERNELS) +constexpr bool has_simd_rope = false; +constexpr int simd_rope_min_size = 1; +template +inline int +rope_traditional_simd(const T*, T*, const float*, const float*, int) { + return 0; +} +template +inline int +rope_non_traditional_simd(const T*, T*, const float*, const float*, int) { + return 0; +} +#endif // !MLX_USE_HIGHWAY_KERNELS + +namespace { + +// Compute sin/cos tables for RoPE positions. +// cos_out, sin_out: [T * half_dims] +void compute_rope_sincos( + float* cos_out, + float* sin_out, + const int* offsets, + int batch_idx, + bool per_batch_offset, + int T, + int half_dims, + float base, + float scale, + const float* freqs) { + int offset_val = per_batch_offset ? offsets[batch_idx] : offsets[0]; + float log_base = std::log(base); + + for (int t = 0; t < T; t++) { + float position = static_cast(t + offset_val) * scale; + float* c = cos_out + t * half_dims; + float* s = sin_out + t * half_dims; + + for (int j = 0; j < half_dims; j++) { + float inv_freq; + if (freqs) { + inv_freq = 1.0f / freqs[j]; + } else { + inv_freq = std::exp(static_cast(-j) * log_base / half_dims); + } + float theta = position * inv_freq; + c[j] = std::cos(theta); + s[j] = std::sin(theta); + } + } +} + +// Apply RoPE to a single head for one time step. +// Non-traditional (split halves): x1 = x[0:half], x2 = x[half:dims] +// x_in and x_out point to D contiguous elements. +// Uses the CPU SIMD layer. Both halves are contiguous, so this vectorizes +// cleanly. +template +inline void rope_apply_non_traditional( + const T* x_in, + T* x_out, + const float* cos_t, + const float* sin_t, + int D, + int dims, + int half_dims) { + using namespace simd; + constexpr int N = max_size; + + int j = 0; +#if defined(MLX_USE_HIGHWAY_KERNELS) + j = rope_non_traditional_highway_simd( + x_in, x_out, cos_t, sin_t, half_dims); +#endif +#if !defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (has_simd_rope && N >= simd_rope_min_size) { + if (j == 0) { + j = rope_non_traditional_simd( + x_in, x_out, cos_t, sin_t, half_dims); + } + } +#endif + + for (; j + N <= half_dims; j += N) { + Simd x1(load(x_in + j)); + Simd x2(load(x_in + j + half_dims)); + Simd c = load(cos_t + j); + Simd s = load(sin_t + j); + + if constexpr (forward) { + store(x_out + j, Simd(x1 * c - x2 * s)); + store(x_out + j + half_dims, Simd(x1 * s + x2 * c)); + } else { + store(x_out + j, Simd(x1 * c + x2 * s)); + store(x_out + j + half_dims, Simd(x2 * c - x1 * s)); + } + } + // Scalar tail + for (; j < half_dims; j++) { + float x1 = static_cast(x_in[j]); + float x2 = static_cast(x_in[j + half_dims]); + float c = cos_t[j]; + float s = sin_t[j]; + + if constexpr (forward) { + x_out[j] = static_cast(x1 * c - x2 * s); + x_out[j + half_dims] = static_cast(x1 * s + x2 * c); + } else { + x_out[j] = static_cast(x1 * c + x2 * s); + x_out[j + half_dims] = static_cast(x2 * c - x1 * s); + } + } + // Passthrough remaining elements + for (int k = dims; k < D; k++) { + x_out[k] = x_in[k]; + } +} + +// Traditional (interleaved pairs): x1 = x[0::2], x2 = x[1::2] +// Data layout: [x0, y0, x1, y1, ...] where (xi, yi) form rotation pairs. +// SIMD approach: load 8 interleaved values (4 pairs), swap within pairs, +// duplicate cos/sin to match pair layout, compute rotation in one FMA. +template +inline void rope_apply_traditional( + const T* x_in, + T* x_out, + const float* cos_t, + const float* sin_t, + int D, + int dims, + int half_dims) { + using namespace simd; + constexpr int N = max_size; + + int j = 0; + +#if defined(MLX_USE_HIGHWAY_KERNELS) + j = rope_traditional_highway_simd( + x_in, x_out, cos_t, sin_t, half_dims); +#endif +#if !defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (has_simd_rope && N >= simd_rope_min_size) { + if (j == 0) { + j = rope_traditional_simd( + x_in, x_out, cos_t, sin_t, half_dims); + } + } +#endif + + // Scalar tail + for (; j < half_dims; j++) { + float x1 = static_cast(x_in[2 * j]); + float x2 = static_cast(x_in[2 * j + 1]); + float c = cos_t[j]; + float s = sin_t[j]; + + if constexpr (forward) { + x_out[2 * j] = static_cast(x1 * c - x2 * s); + x_out[2 * j + 1] = static_cast(x1 * s + x2 * c); + } else { + x_out[2 * j] = static_cast(x1 * c + x2 * s); + x_out[2 * j + 1] = static_cast(x2 * c - x1 * s); + } + } + // Passthrough remaining elements + for (int k = dims; k < D; k++) { + x_out[k] = x_in[k]; + } +} + +// Process assigned heads for contiguous input [B, N, T, D]. +template +void rope_impl_contiguous( + const T* in, + T* out, + const int* offsets, + bool per_batch_offset, + int B, + int N, + int T_len, + int D, + int dims, + float base, + float scale, + const float* freqs, + int head_start, + int head_end) { + int half_dims = dims / 2; + + int cur_batch = -1; + std::vector cos_table(T_len * half_dims); + std::vector sin_table(T_len * half_dims); + + for (int h = head_start; h < head_end; h++) { + int b = h / N; + int n = h % N; + + if (b != cur_batch) { + cur_batch = b; + compute_rope_sincos( + cos_table.data(), + sin_table.data(), + offsets, + b, + per_batch_offset, + T_len, + half_dims, + base, + scale, + freqs); + } + + for (int t = 0; t < T_len; t++) { + size_t idx = (static_cast(b) * N * T_len + n * T_len + t) * D; + const float* c = cos_table.data() + t * half_dims; + const float* s = sin_table.data() + t * half_dims; + + if constexpr (traditional) { + rope_apply_traditional( + in + idx, out + idx, c, s, D, dims, half_dims); + } else { + rope_apply_non_traditional( + in + idx, out + idx, c, s, D, dims, half_dims); + } + } + } +} + +// Process assigned heads for strided input. +// Input is accessed via strides; output is written contiguously. +// in_b_stride: stride between batches in the input +// in_n_stride: stride between heads in the input +// in_t_stride: stride between time steps in the input +// The D-dimension must have stride 1 in the input. +template +void rope_impl_strided( + const T* in, + T* out, + const int* offsets, + bool per_batch_offset, + int B, + int N, + int T_len, + int D, + int dims, + float base, + float scale, + const float* freqs, + int64_t in_b_stride, + int64_t in_n_stride, + int64_t in_t_stride, + int head_start, + int head_end) { + int half_dims = dims / 2; + + int cur_batch = -1; + std::vector cos_table(T_len * half_dims); + std::vector sin_table(T_len * half_dims); + + for (int h = head_start; h < head_end; h++) { + int b = h / N; + int n = h % N; + + if (b != cur_batch) { + cur_batch = b; + compute_rope_sincos( + cos_table.data(), + sin_table.data(), + offsets, + b, + per_batch_offset, + T_len, + half_dims, + base, + scale, + freqs); + } + + for (int t = 0; t < T_len; t++) { + // Input uses strides + int64_t in_idx = b * in_b_stride + n * in_n_stride + t * in_t_stride; + // Output is always row-contiguous + size_t out_idx = (static_cast(b) * N * T_len + n * T_len + t) * D; + const float* c = cos_table.data() + t * half_dims; + const float* s = sin_table.data() + t * half_dims; + + if constexpr (traditional) { + rope_apply_traditional( + in + in_idx, out + out_idx, c, s, D, dims, half_dims); + } else { + rope_apply_non_traditional( + in + in_idx, out + out_idx, c, s, D, dims, half_dims); + } + } + } +} + +template +void rope_dispatch( + const T* in, + T* out, + const int* offsets, + bool per_batch_offset, + int B, + int N, + int T_len, + int D, + int dims, + float base, + float scale, + const float* freqs, + bool traditional, + bool forward, + bool use_strides, + int64_t in_b_stride, + int64_t in_n_stride, + int64_t in_t_stride, + cpu::ThreadPool& pool, + int nth) { + int total_heads = B * N; + + auto run = [&](auto trad_tag, auto fwd_tag) { + auto do_work = [&](int start, int end) { + if (use_strides) { + rope_impl_strided< + T, + decltype(trad_tag)::value, + decltype(fwd_tag)::value>( + in, + out, + offsets, + per_batch_offset, + B, + N, + T_len, + D, + dims, + base, + scale, + freqs, + in_b_stride, + in_n_stride, + in_t_stride, + start, + end); + } else { + rope_impl_contiguous< + T, + decltype(trad_tag)::value, + decltype(fwd_tag)::value>( + in, + out, + offsets, + per_batch_offset, + B, + N, + T_len, + D, + dims, + base, + scale, + freqs, + start, + end); + } + }; + + if (nth > 1) { + pool.parallel_for(nth, [&](int tid, int num_threads) { + int per = (total_heads + num_threads - 1) / num_threads; + int start = per * tid; + int end = std::min(start + per, total_heads); + do_work(start, end); + }); + } else { + do_work(0, total_heads); + } + }; + + if (traditional) { + if (forward) { + run(std::true_type{}, std::true_type{}); + } else { + run(std::true_type{}, std::false_type{}); + } + } else { + if (forward) { + run(std::false_type{}, std::true_type{}); + } else { + run(std::false_type{}, std::false_type{}); + } + } +} + +} // namespace + +void RoPE::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + // Types without a Highway kernel, such as float64, compose MLX's fallback. + if (inputs[0].dtype() != float32 && inputs[0].dtype() != float16 && + inputs[0].dtype() != bfloat16) { + MLX_HIGHWAY_RECORD_FALLBACK(Rope); + auto results = fallback_(inputs); + eval(results); + for (size_t i = 0; i < outputs.size(); i++) { + outputs[i].copy_shared_buffer(results[i]); + } + return; + } + assert(outputs.size() == 1); + auto& in = inputs[0]; + auto& out = outputs[0]; + + int ndim = in.ndim(); + int D = in.shape(ndim - 1); + + // Compute 4D dimensions: [B, N, T, D] + int B = in.shape(0); + int N = 1; + for (int i = 1; i < ndim - 2; i++) { + N *= in.shape(i); + } + int T = in.shape(ndim - 2); + + // Determine input layout + bool row_contiguous = in.flags().row_contiguous; + + // For non-contiguous input, check if D-dimension has stride 1 + // (common case: transpose of (B,T,N,D) -> (B,N,T,D)) + bool d_stride_one = row_contiguous || (in.strides()[ndim - 1] == 1); + + // Compute strides for the B, N, T dimensions + // For contiguous: b_stride = N*T*D, n_stride computed from middle dims, + // t_stride = D + // For non-contiguous: use actual strides + int64_t in_b_stride = 0; + int64_t in_n_stride = 0; + int64_t in_t_stride = 0; + bool use_strides = false; + + if (row_contiguous) { + // Standard contiguous layout + use_strides = false; + } else if (d_stride_one && ndim >= 3) { + // Non-contiguous but D is contiguous -- use strided access + use_strides = true; + in_b_stride = in.strides()[0]; + in_t_stride = in.strides()[ndim - 2]; + // For N (product of middle dims), use the stride of the first middle dim + // This works for 4D (B, N, T, D) but for higher dims we need the stride + // of the flattened N dimension. If the middle dims aren't contiguous with + // each other, fall back to copy. + if (ndim == 3) { + in_n_stride = 0; // N=1, stride doesn't matter + } else if (ndim == 4) { + in_n_stride = in.strides()[1]; + } else { + // For ndim > 4, check if middle dimensions are regularly strided + // For simplicity, fall back to copy for >4D non-contiguous + use_strides = false; + } + } + + // If we can't use strides, make a contiguous copy + array x = in; + bool made_copy = false; + if (!row_contiguous && !use_strides) { + x = contiguous_copy_cpu(in, stream()); + made_copy = true; + } + + // Allocate output as row-contiguous + out.set_data(allocator::malloc(out.nbytes())); + + // Get offset + array offset_arr = inputs[1]; + bool per_batch_offset = offset_arr.size() > 1; + bool has_freqs = inputs.size() == 3; + std::optional freqs; + if (has_freqs) { + freqs = inputs[2]; + } + + // Set up command encoder + auto& encoder = cpu::get_command_encoder(stream()); + // The kernels read offsets and freqs with stride 1. + if (offset_arr.ndim() > 0 && offset_arr.strides()[0] != 1) { + offset_arr = contiguous_copy_cpu(offset_arr, stream()); + encoder.add_temporary(offset_arr); + } + if (has_freqs && freqs->strides()[0] != 1) { + freqs = contiguous_copy_cpu(*freqs, stream()); + encoder.add_temporary(*freqs); + } + encoder.set_input_array(x); + encoder.set_input_array(offset_arr); + if (has_freqs) { + encoder.set_input_array(*freqs); + } + encoder.set_output_array(out); + if (made_copy) { + encoder.add_temporary(x); + } + + // Determine threading + auto& pool = cpu::ThreadPool::instance(); + int total_heads = B * N; + int nth = std::min(pool.max_threads(), total_heads); + size_t total_elements = static_cast(B) * N * T * D; + if (total_elements < cpu::MIN_TOTAL_ELEMENTS) { + nth = 1; + } + + int dims = dims_; + float base = base_; + float scale = scale_; + bool traditional = traditional_; + bool forward = forward_; + + auto dispatch_typed = [&](auto dummy) { + using DType = decltype(dummy); + const DType* x_ptr = x.data(); + const int* off_ptr = offset_arr.data(); + const float* freq_ptr = has_freqs ? freqs->data() : nullptr; + DType* out_ptr = out.data(); + + encoder.dispatch([=, &pool]() { + rope_dispatch( + x_ptr, + out_ptr, + off_ptr, + per_batch_offset, + B, + N, + T, + D, + dims, + base, + scale, + freq_ptr, + traditional, + forward, + use_strides, + in_b_stride, + in_n_stride, + in_t_stride, + pool, + nth); + }); + }; + + switch (x.dtype()) { + case float32: + dispatch_typed(float{}); + break; + case float16: + dispatch_typed(float16_t{}); + break; + case bfloat16: + dispatch_typed(bfloat16_t{}); + break; + default: + throw std::runtime_error("[RoPE::eval_cpu] Unsupported type"); + } +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/rope_highway.cpp b/mlx/backend/cpu/rope_highway.cpp new file mode 100644 index 0000000000..e7f7ad4ed6 --- /dev/null +++ b/mlx/backend/cpu/rope_highway.cpp @@ -0,0 +1,364 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +// Normally this file is compiled directly and Highway emits its runtime +// dispatch targets. Native MSVC builds compile this file once per target with +// MLX_HIGHWAY_MANUAL_TARGET and MLX_HIGHWAY_TARGET_SUFFIX so the same kernels +// are emitted as one manually suffixed specialization. + +#include "mlx/backend/cpu/rope_highway.h" +#include "mlx/backend/cpu/highway_info.h" + +#if !defined(MLX_HIGHWAY_MANUAL_TARGET) +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/rope_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep +#endif + +#include "hwy/highway.h" +#include "mlx/backend/cpu/highway_utils.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::fast { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; +namespace hu = mlx::core::highway::HWY_NAMESPACE; +using hu::load_interleaved_typed_as_f32; +using hu::load_typed_as_f32; +using hu::store_f32_as_typed; +using hu::store_interleaved_f32_as_typed; + +template +int rope_traditional( + const T* HWY_RESTRICT x_in, + T* HWY_RESTRICT x_out, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + + int j = 0; + HWY_UNROLL(4) + for (; j + lanes <= half_dims; j += lanes) { + V x0; + V x1; + load_interleaved_typed_as_f32(d, x_in, 2 * j, x0, x1); + + const V c = hn::LoadU(d, cos_t + j); + const V s = hn::LoadU(d, sin_t + j); + + V out0; + V out1; + if constexpr (forward) { + out0 = hn::Sub(hn::Mul(x0, c), hn::Mul(x1, s)); + out1 = hn::Add(hn::Mul(x0, s), hn::Mul(x1, c)); + } else { + out0 = hn::Add(hn::Mul(x0, c), hn::Mul(x1, s)); + out1 = hn::Sub(hn::Mul(x1, c), hn::Mul(x0, s)); + } + + store_interleaved_f32_as_typed(d, out0, out1, x_out, 2 * j); + } + return j; +} + +template +int rope_non_traditional( + const T* HWY_RESTRICT x_in, + T* HWY_RESTRICT x_out, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims) { + const hn::ScalableTag d; + using V = hn::Vec; + + const int lanes = static_cast(hn::Lanes(d)); + + int j = 0; + HWY_UNROLL(4) + for (; j + lanes <= half_dims; j += lanes) { + const V x0 = load_typed_as_f32(d, x_in, j); + const V x1 = load_typed_as_f32(d, x_in, j + half_dims); + const V c = hn::LoadU(d, cos_t + j); + const V s = hn::LoadU(d, sin_t + j); + + V out0; + V out1; + if constexpr (forward) { + out0 = hn::Sub(hn::Mul(x0, c), hn::Mul(x1, s)); + out1 = hn::Add(hn::Mul(x0, s), hn::Mul(x1, c)); + } else { + out0 = hn::Add(hn::Mul(x0, c), hn::Mul(x1, s)); + out1 = hn::Sub(hn::Mul(x1, c), hn::Mul(x0, s)); + } + + store_f32_as_typed(d, out0, x_out, j); + store_f32_as_typed(d, out1, x_out, j + half_dims); + } + return j; +} + +template +int rope_traditional_dispatch( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims) { + switch (dtype) { + case RopeHighwayDType::Float32: + return rope_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + case RopeHighwayDType::Float16: + return rope_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + case RopeHighwayDType::BFloat16: + return rope_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + } + return 0; +} + +template +int rope_non_traditional_dispatch( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims) { + switch (dtype) { + case RopeHighwayDType::Float32: + return rope_non_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + case RopeHighwayDType::Float16: + return rope_non_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + case RopeHighwayDType::BFloat16: + return rope_non_traditional( + static_cast(x_in), + static_cast(x_out), + cos_t, + sin_t, + half_dims); + } + return 0; +} + +void RopeTraditionalForward( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims, + int* HWY_RESTRICT processed) { + MLX_HIGHWAY_RECORD(Rope); + *processed = rope_traditional_dispatch( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +void RopeTraditionalReverse( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims, + int* HWY_RESTRICT processed) { + MLX_HIGHWAY_RECORD(Rope); + *processed = rope_traditional_dispatch( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +void RopeNonTraditionalForward( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims, + int* HWY_RESTRICT processed) { + MLX_HIGHWAY_RECORD(Rope); + *processed = rope_non_traditional_dispatch( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +void RopeNonTraditionalReverse( + const void* HWY_RESTRICT x_in, + void* HWY_RESTRICT x_out, + RopeHighwayDType dtype, + const float* HWY_RESTRICT cos_t, + const float* HWY_RESTRICT sin_t, + int half_dims, + int* HWY_RESTRICT processed) { + MLX_HIGHWAY_RECORD(Rope); + *processed = rope_non_traditional_dispatch( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +} // namespace +} // namespace HWY_NAMESPACE +} // namespace mlx::core::fast +HWY_AFTER_NAMESPACE(); + +#if HWY_ONCE +namespace mlx::core::fast { + +#if defined(MLX_HIGHWAY_MANUAL_TARGET) + +#ifndef MLX_HIGHWAY_TARGET_SUFFIX +#error "MLX_HIGHWAY_TARGET_SUFFIX must be defined for manual Highway targets" +#endif + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) +#define MLX_HIGHWAY_TARGET_FUNC(name) \ + MLX_HIGHWAY_CONCAT(name, MLX_HIGHWAY_TARGET_SUFFIX) + +int MLX_HIGHWAY_TARGET_FUNC(rope_traditional_highway_forward)( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_STATIC_DISPATCH(RopeTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int MLX_HIGHWAY_TARGET_FUNC(rope_traditional_highway_reverse)( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_STATIC_DISPATCH(RopeTraditionalReverse) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int MLX_HIGHWAY_TARGET_FUNC(rope_non_traditional_highway_forward)( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_STATIC_DISPATCH(RopeNonTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int MLX_HIGHWAY_TARGET_FUNC(rope_non_traditional_highway_reverse)( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_STATIC_DISPATCH(RopeNonTraditionalReverse) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +#undef MLX_HIGHWAY_TARGET_FUNC +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +#else + +HWY_EXPORT(RopeTraditionalForward); +HWY_EXPORT(RopeTraditionalReverse); +HWY_EXPORT(RopeNonTraditionalForward); +HWY_EXPORT(RopeNonTraditionalReverse); + +int rope_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_DYNAMIC_DISPATCH(RopeTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int rope_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_DYNAMIC_DISPATCH(RopeTraditionalReverse) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int rope_non_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_DYNAMIC_DISPATCH(RopeNonTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +int rope_non_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + int processed = 0; + HWY_DYNAMIC_DISPATCH(RopeNonTraditionalReverse) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); + return processed; +} + +#endif + +} // namespace mlx::core::fast +#endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/rope_highway.h b/mlx/backend/cpu/rope_highway.h new file mode 100644 index 0000000000..7eff1641b1 --- /dev/null +++ b/mlx/backend/cpu/rope_highway.h @@ -0,0 +1,101 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include + +#include "mlx/types/half_types.h" + +namespace mlx::core::fast { + +constexpr bool has_simd_rope = true; +constexpr int simd_rope_min_size = 1; + +enum class RopeHighwayDType : uint8_t { + Float32, + Float16, + BFloat16, +}; + +template +constexpr RopeHighwayDType rope_highway_dtype() { + if constexpr (std::is_same_v) { + return RopeHighwayDType::Float32; + } else if constexpr (std::is_same_v) { + return RopeHighwayDType::Float16; + } else if constexpr (std::is_same_v) { + return RopeHighwayDType::BFloat16; + } else { + static_assert( + std::is_same_v || std::is_same_v || + std::is_same_v, + "Unsupported Highway RoPE dtype"); + } +} + +int rope_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims); + +int rope_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims); + +int rope_non_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims); + +int rope_non_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims); + +template +inline int rope_traditional_highway_simd( + const T* x_in, + T* x_out, + const float* cos_t, + const float* sin_t, + int half_dims) { + if constexpr (forward) { + return rope_traditional_highway_forward( + x_in, x_out, rope_highway_dtype(), cos_t, sin_t, half_dims); + } else { + return rope_traditional_highway_reverse( + x_in, x_out, rope_highway_dtype(), cos_t, sin_t, half_dims); + } +} + +template +inline int rope_non_traditional_highway_simd( + const T* x_in, + T* x_out, + const float* cos_t, + const float* sin_t, + int half_dims) { + if constexpr (forward) { + return rope_non_traditional_highway_forward( + x_in, x_out, rope_highway_dtype(), cos_t, sin_t, half_dims); + } else { + return rope_non_traditional_highway_reverse( + x_in, x_out, rope_highway_dtype(), cos_t, sin_t, half_dims); + } +} + +} // namespace mlx::core::fast diff --git a/mlx/backend/cpu/rope_highway_dispatch.cpp b/mlx/backend/cpu/rope_highway_dispatch.cpp new file mode 100644 index 0000000000..4c1c6a2776 --- /dev/null +++ b/mlx/backend/cpu/rope_highway_dispatch.cpp @@ -0,0 +1,122 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/rope_highway.h" + +#include "hwy/highway.h" + +namespace mlx::core::fast { + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) + +using RopeFn = int (*)( + const void*, + void*, + RopeHighwayDType, + const float*, + const float*, + int); +#define MLX_DECLARE_ROPE_TARGET(suffix) \ + int MLX_HIGHWAY_CONCAT(rope_traditional_highway_forward, suffix)( \ + const void*, void*, RopeHighwayDType, const float*, const float*, int); \ + int MLX_HIGHWAY_CONCAT(rope_traditional_highway_reverse, suffix)( \ + const void*, void*, RopeHighwayDType, const float*, const float*, int); \ + int MLX_HIGHWAY_CONCAT(rope_non_traditional_highway_forward, suffix)( \ + const void*, void*, RopeHighwayDType, const float*, const float*, int); \ + int MLX_HIGHWAY_CONCAT(rope_non_traditional_highway_reverse, suffix)( \ + const void*, void*, RopeHighwayDType, const float*, const float*, int) + +MLX_DECLARE_ROPE_TARGET(_avx2); +MLX_DECLARE_ROPE_TARGET(_sse4); +MLX_DECLARE_ROPE_TARGET(_ssse3); +MLX_DECLARE_ROPE_TARGET(_sse2); + +#undef MLX_DECLARE_ROPE_TARGET + +namespace { + +struct RopeHighwayDispatch { + RopeFn traditional_forward; + RopeFn traditional_reverse; + RopeFn non_traditional_forward; + RopeFn non_traditional_reverse; +}; + +#define MLX_ROPE_DISPATCH(suffix) \ + RopeHighwayDispatch { \ + MLX_HIGHWAY_CONCAT(rope_traditional_highway_forward, suffix), \ + MLX_HIGHWAY_CONCAT(rope_traditional_highway_reverse, suffix), \ + MLX_HIGHWAY_CONCAT(rope_non_traditional_highway_forward, suffix), \ + MLX_HIGHWAY_CONCAT(rope_non_traditional_highway_reverse, suffix) \ + } + +const RopeHighwayDispatch& rope_dispatch() { + static const RopeHighwayDispatch dispatch = [] { + const int64_t targets = hwy::SupportedTargets(); + if (targets & HWY_AVX2) { + return MLX_ROPE_DISPATCH(_avx2); + } + if (targets & HWY_SSE4) { + return MLX_ROPE_DISPATCH(_sse4); + } + if (targets & HWY_SSSE3) { + return MLX_ROPE_DISPATCH(_ssse3); + } + return MLX_ROPE_DISPATCH(_sse2); + }(); + return dispatch; +} + +#undef MLX_ROPE_DISPATCH +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +} // namespace + +int rope_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + return rope_dispatch().traditional_forward( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +int rope_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + return rope_dispatch().traditional_reverse( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +int rope_non_traditional_highway_forward( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + return rope_dispatch().non_traditional_forward( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +int rope_non_traditional_highway_reverse( + const void* x_in, + void* x_out, + RopeHighwayDType dtype, + const float* cos_t, + const float* sin_t, + int half_dims) { + return rope_dispatch().non_traditional_reverse( + x_in, x_out, dtype, cos_t, sin_t, half_dims); +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/scratch.h b/mlx/backend/cpu/scratch.h new file mode 100644 index 0000000000..5540499044 --- /dev/null +++ b/mlx/backend/cpu/scratch.h @@ -0,0 +1,64 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include + +#include "mlx/api.h" + +namespace mlx::core::cpu { + +// Bytes of kernel scratch every thread keeps between operations, process-wide. +MLX_API inline std::atomic& scratch_retained() { + static std::atomic bytes{0}; + return bytes; +} + +MLX_API inline size_t scratch_retained_bytes() { + return scratch_retained().load(std::memory_order_relaxed); +} + +// A thread's scratch buffer, borrowed for one operation, which frees it if it +// grew past kKeepBytes. A thread holds one lease at a time. +class ScratchLease { + public: + static constexpr size_t kKeepBytes = size_t{64} << 20; + + ScratchLease(std::vector& buffer, size_t floats) : buffer_(buffer) { + // A second lease could reallocate the buffer under the first. + if (leased_) { + throw std::logic_error("ScratchLease: this thread already holds a lease"); + } + const size_t before = buffer_.capacity(); + if (buffer_.size() < floats) { + buffer_.resize(floats); + } + scratch_retained().fetch_add( + (buffer_.capacity() - before) * sizeof(float), + std::memory_order_relaxed); + leased_ = true; + } + ScratchLease(const ScratchLease&) = delete; + ScratchLease& operator=(const ScratchLease&) = delete; + ~ScratchLease() { + leased_ = false; + const size_t bytes = buffer_.capacity() * sizeof(float); + if (bytes > kKeepBytes) { + std::vector().swap(buffer_); + scratch_retained().fetch_sub(bytes, std::memory_order_relaxed); + } + } + float* data() { + return buffer_.data(); + } + + private: + static inline thread_local bool leased_ = false; + std::vector& buffer_; +}; + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp new file mode 100644 index 0000000000..5bc998d092 --- /dev/null +++ b/mlx/backend/cpu/sdpa.cpp @@ -0,0 +1,1022 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include +#include +#include +#include +#include +#include + +#include "mlx/allocator.h" +#include "mlx/backend/cpu/copy.h" +#include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/sdpa_highway.h" +#endif +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/fast_primitives.h" + +namespace mlx::core::fast { + +namespace { + +using namespace mlx::core::simd; + +// SDPA kernel for a single query position (float32), prompt path. +// Uses online softmax with scalar exp: minimal register pressure, best for +// prompt where SDPA is a small fraction of total time. +void sdpa_single_head_f32_prompt( + float* output, + const float* query, + const float* keys, + const float* values, + int seq_len, + int head_dim, + float scale, + int effective_len, + const float* mask, + float sink_value, + bool has_sinks) { + constexpr int N = max_size; + constexpr int MAX_ACC = 256 / N; + int n_full_acc = std::min(head_dim / N, (int)MAX_ACC); + int d_simd = n_full_acc * N; + int tail_len = head_dim - d_simd; + const float neg_inf = -std::numeric_limits::infinity(); + + Simd O_acc[MAX_ACC]; + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = Simd(0.0f); + } + float O_tail[N] = {}; + float running_max = neg_inf; + float running_sum = 0.0f; + + for (int s = 0; s < effective_len; s++) { + // Q * K[s] dot product + const float* k_row = keys + s * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(query + d), load(k_row + d), dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += query[d] * k_row[d]; + } + dot *= scale; + if (mask) { + dot += mask[s]; + } + if (dot == neg_inf) { + continue; + } + + // Online softmax update + float new_max = std::max(running_max, dot); + if (new_max > running_max) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] *= correction; + } + running_max = new_max; + } + + float exp_dot = std::exp(dot - running_max); + running_sum += exp_dot; + + // Accumulate weighted V + const float* v_row = values + s * head_dim; + Simd vexp(exp_dot); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = fma(vexp, load(v_row + i * N), O_acc[i]); + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] += exp_dot * v_row[d_simd + j]; + } + } + + // Attention sinks + if (has_sinks) { + float new_max = std::max(running_max, sink_value); + if (new_max > neg_inf) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] *= correction; + } + running_sum += std::exp(sink_value - new_max); + } + } + + // Normalize and store + if (running_sum > 0.0f) { + float inv_sum = 1.0f / running_sum; + Simd vinv(inv_sum); + for (int i = 0; i < n_full_acc; i++) { + store(output + i * N, O_acc[i] * vinv); + } + for (int j = 0; j < tail_len; j++) { + output[d_simd + j] = O_tail[j] * inv_sum; + } + } else { + std::fill(output, output + head_dim, 0.0f); + } +} + +// SDPA kernel for a single query position (float32), generation path. +// Uses online softmax with SIMD-batched exp: processes N KV positions at a +// time, amortizing exp() cost. Best for generation where SDPA is ~24% of +// per-token time and KV caches are long. +void sdpa_single_head_f32_gen( + float* output, + const float* query, + const float* keys, + const float* values, + int seq_len, + int head_dim, + float scale, + int effective_len, + const float* mask, + float sink_value, + bool has_sinks) { + constexpr int N = max_size; + constexpr int MAX_ACC = 256 / N; + int n_full_acc = std::min(head_dim / N, (int)MAX_ACC); + int d_simd = n_full_acc * N; + int tail_len = head_dim - d_simd; + const float neg_inf = -std::numeric_limits::infinity(); + + Simd O_acc[MAX_ACC]; + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = Simd(0.0f); + } + float O_tail[N] = {}; + float running_max = neg_inf; + float running_sum = 0.0f; + + // Main loop: N positions per iteration for SIMD exp + int s = 0; + for (; s + N <= effective_len; s += N) { + // Compute N dot products + alignas(32) float dots[N]; + for (int b = 0; b < N; b++) { + const float* k_row = keys + (s + b) * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(query + d), load(k_row + d), dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += query[d] * k_row[d]; + } + dot *= scale; + if (mask) { + dot += mask[s + b]; + } + dots[b] = dot; + } + + Simd vdots = load(dots); + float block_max = max(vdots); + if (block_max == neg_inf) { + continue; + } + if (block_max > running_max) { + float correction = std::exp(running_max - block_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] *= correction; + } + running_max = block_max; + } + + // SIMD exp of N scores at once + Simd vexp = exp(vdots - Simd(running_max)); + running_sum += sum(vexp); + + alignas(32) float exp_arr[N]; + store(exp_arr, vexp); + for (int b = 0; b < N; b++) { + if (exp_arr[b] == 0.0f) { + continue; + } + const float* v_row = values + (s + b) * head_dim; + Simd vw(exp_arr[b]); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = fma(vw, load(v_row + i * N), O_acc[i]); + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] += exp_arr[b] * v_row[d_simd + j]; + } + } + } + + // Scalar tail for remaining < N positions + for (; s < effective_len; s++) { + const float* k_row = keys + s * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(query + d), load(k_row + d), dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += query[d] * k_row[d]; + } + dot *= scale; + if (mask) { + dot += mask[s]; + } + if (dot == neg_inf) { + continue; + } + float new_max = std::max(running_max, dot); + if (new_max > running_max) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] *= correction; + } + running_max = new_max; + } + float exp_dot = std::exp(dot - running_max); + running_sum += exp_dot; + const float* v_row = values + s * head_dim; + Simd vw(exp_dot); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = fma(vw, load(v_row + i * N), O_acc[i]); + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] += exp_dot * v_row[d_simd + j]; + } + } + + // Attention sinks + if (has_sinks) { + float new_max = std::max(running_max, sink_value); + if (new_max > neg_inf) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_full_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + for (int j = 0; j < tail_len; j++) { + O_tail[j] *= correction; + } + running_sum += std::exp(sink_value - new_max); + } + } + + // Normalize and store + if (running_sum > 0.0f) { + float inv_sum = 1.0f / running_sum; + Simd vinv(inv_sum); + for (int i = 0; i < n_full_acc; i++) { + store(output + i * N, O_acc[i] * vinv); + } + for (int j = 0; j < tail_len; j++) { + output[d_simd + j] = O_tail[j] * inv_sum; + } + } else { + std::fill(output, output + head_dim, 0.0f); + } +} + +// Load N elements of half type T as Simd. +// Uses F16C SIMD conversion when max_size >= N, scalar fallback otherwise. +template +inline Simd load_half_as_float(const T* ptr) { + constexpr int NT = max_size; + if constexpr (NT >= N) { + return Simd(load(ptr)); + } else { + alignas(32) float tmp[N]; + for (int j = 0; j < N; j++) { + tmp[j] = static_cast(ptr[j]); + } + return load(tmp); + } +} + +// Store N float elements as half type T. +// Uses F16C SIMD conversion when max_size >= N, scalar fallback otherwise. +template +inline void store_float_as_half(T* ptr, Simd v) { + constexpr int NT = max_size; + if constexpr (NT >= N) { + store(ptr, Simd(v)); + } else { + alignas(32) float tmp[N]; + store(tmp, v); + for (int j = 0; j < N; j++) { + ptr[j] = static_cast(tmp[j]); + } + } +} + +// SDPA kernel for half types (float16_t / bfloat16_t), prompt path. +// Online softmax with scalar exp. Converts to float32 via SIMD for compute. +template +void sdpa_single_head_half_prompt( + T* output, + const T* query, + const T* keys, + const T* values, + int seq_len, + int head_dim, + float scale, + int effective_len, + const T* mask, + float sink_value, + bool has_sinks) { + constexpr int N = max_size; + constexpr int MAX_ACC = 256 / N; + int n_acc = std::min((head_dim + N - 1) / N, (int)MAX_ACC); + const float neg_inf = -std::numeric_limits::infinity(); + + alignas(32) float q_f[256]; + { + int d = 0; + for (; d + N <= head_dim; d += N) { + store(&q_f[d], load_half_as_float(query + d)); + } + for (; d < head_dim; d++) { + q_f[d] = static_cast(query[d]); + } + } + + Simd O_acc[MAX_ACC]; + for (int i = 0; i < n_acc; i++) { + O_acc[i] = Simd(0.0f); + } + float running_max = neg_inf; + float running_sum = 0.0f; + + for (int s = 0; s < effective_len; s++) { + const T* k_row = keys + s * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(&q_f[d]), + load_half_as_float(k_row + d), + dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += q_f[d] * static_cast(k_row[d]); + } + dot *= scale; + if (mask) { + dot += static_cast(mask[s]); + } + if (dot == neg_inf) { + continue; + } + + float new_max = std::max(running_max, dot); + if (new_max > running_max) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + running_max = new_max; + } + + float exp_dot = std::exp(dot - running_max); + running_sum += exp_dot; + + const T* v_row = values + s * head_dim; + Simd vw(exp_dot); + for (int i = 0; i < n_acc && i * N < head_dim; i++) { + if (i * N + N <= head_dim) { + O_acc[i] = fma(vw, load_half_as_float(v_row + i * N), O_acc[i]); + } else { + alignas(32) float v_tmp[N] = {}; + int remaining = head_dim - i * N; + for (int j = 0; j < remaining; j++) { + v_tmp[j] = static_cast(v_row[i * N + j]); + } + O_acc[i] = fma(vw, load(v_tmp), O_acc[i]); + } + } + } + + if (has_sinks) { + float new_max = std::max(running_max, sink_value); + if (new_max > neg_inf) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + running_sum += std::exp(sink_value - new_max); + } + } + + if (running_sum > 0.0f) { + float inv_sum = 1.0f / running_sum; + Simd vinv(inv_sum); + for (int i = 0; i < n_acc && i * N < head_dim; i++) { + if (i * N + N <= head_dim) { + store_float_as_half(output + i * N, O_acc[i] * vinv); + } else { + alignas(32) float tmp[N]; + store(tmp, O_acc[i] * vinv); + int remaining = head_dim - i * N; + for (int j = 0; j < remaining; j++) { + output[i * N + j] = static_cast(tmp[j]); + } + } + } + } else { + for (int d = 0; d < head_dim; d++) { + output[d] = static_cast(0.0f); + } + } +} + +// SDPA kernel for half types, generation path. +// Online softmax with SIMD-batched exp over N KV positions at a time. +template +void sdpa_single_head_half_gen( + T* output, + const T* query, + const T* keys, + const T* values, + int seq_len, + int head_dim, + float scale, + int effective_len, + const T* mask, + float sink_value, + bool has_sinks) { + constexpr int N = max_size; + constexpr int MAX_ACC = 256 / N; + int n_acc = std::min((head_dim + N - 1) / N, (int)MAX_ACC); + const float neg_inf = -std::numeric_limits::infinity(); + + alignas(32) float q_f[256]; + { + int d = 0; + for (; d + N <= head_dim; d += N) { + store(&q_f[d], load_half_as_float(query + d)); + } + for (; d < head_dim; d++) { + q_f[d] = static_cast(query[d]); + } + } + + Simd O_acc[MAX_ACC]; + for (int i = 0; i < n_acc; i++) { + O_acc[i] = Simd(0.0f); + } + float running_max = neg_inf; + float running_sum = 0.0f; + + // Helper: accumulate weighted V (kept as lambda -- only ~32 calls/SDPA for + // generation, so call overhead is negligible) + auto accum_v = [&](const T* v_row, float w) { + Simd vw(w); + for (int i = 0; i < n_acc && i * N < head_dim; i++) { + if (i * N + N <= head_dim) { + O_acc[i] = fma(vw, load_half_as_float(v_row + i * N), O_acc[i]); + } else { + alignas(32) float v_tmp[N] = {}; + int remaining = head_dim - i * N; + for (int j = 0; j < remaining; j++) { + v_tmp[j] = static_cast(v_row[i * N + j]); + } + O_acc[i] = fma(vw, load(v_tmp), O_acc[i]); + } + } + }; + + // Main loop: N positions per iteration + int s = 0; + for (; s + N <= effective_len; s += N) { + alignas(32) float dots[N]; + for (int b = 0; b < N; b++) { + const T* k_row = keys + (s + b) * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(&q_f[d]), + load_half_as_float(k_row + d), + dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += q_f[d] * static_cast(k_row[d]); + } + dot *= scale; + if (mask) { + dot += static_cast(mask[s + b]); + } + dots[b] = dot; + } + + Simd vdots = load(dots); + float block_max = max(vdots); + if (block_max == neg_inf) { + continue; + } + if (block_max > running_max) { + float correction = std::exp(running_max - block_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + running_max = block_max; + } + + Simd vexp = exp(vdots - Simd(running_max)); + running_sum += sum(vexp); + + alignas(32) float exp_arr[N]; + store(exp_arr, vexp); + for (int b = 0; b < N; b++) { + if (exp_arr[b] == 0.0f) { + continue; + } + accum_v(values + (s + b) * head_dim, exp_arr[b]); + } + } + + // Scalar tail + for (; s < effective_len; s++) { + const T* k_row = keys + s * head_dim; + Simd dot_acc(0.0f); + int d = 0; + for (; d + N <= head_dim; d += N) { + dot_acc = + fma(load(&q_f[d]), + load_half_as_float(k_row + d), + dot_acc); + } + float dot = sum(dot_acc); + for (; d < head_dim; d++) { + dot += q_f[d] * static_cast(k_row[d]); + } + dot *= scale; + if (mask) { + dot += static_cast(mask[s]); + } + if (dot == neg_inf) { + continue; + } + float new_max = std::max(running_max, dot); + if (new_max > running_max) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + running_max = new_max; + } + float exp_dot = std::exp(dot - running_max); + running_sum += exp_dot; + accum_v(values + s * head_dim, exp_dot); + } + + if (has_sinks) { + float new_max = std::max(running_max, sink_value); + if (new_max > neg_inf) { + float correction = std::exp(running_max - new_max); + running_sum *= correction; + Simd vcorr(correction); + for (int i = 0; i < n_acc; i++) { + O_acc[i] = O_acc[i] * vcorr; + } + running_sum += std::exp(sink_value - new_max); + } + } + + if (running_sum > 0.0f) { + float inv_sum = 1.0f / running_sum; + Simd vinv(inv_sum); + for (int i = 0; i < n_acc && i * N < head_dim; i++) { + if (i * N + N <= head_dim) { + store_float_as_half(output + i * N, O_acc[i] * vinv); + } else { + alignas(32) float tmp[N]; + store(tmp, O_acc[i] * vinv); + int remaining = head_dim - i * N; + for (int j = 0; j < remaining; j++) { + output[i * N + j] = static_cast(tmp[j]); + } + } + } + } else { + for (int d = 0; d < head_dim; d++) { + output[d] = static_cast(0.0f); + } + } +} + +// Kernel dispatch function pointer types +using f32_kernel_fn = void (*)( + float*, + const float*, + const float*, + const float*, + int, + int, + float, + int, + const float*, + float, + bool); + +template +using half_kernel_fn = void (*)( + T*, + const T*, + const T*, + const T*, + int, + int, + float, + int, + const T*, + float, + bool); + +template +void sdpa_impl( + T* output, + const T* queries, + const T* keys, + const T* values, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const T* mask, + bool has_mask, + const T* sinks, + bool has_sinks) { + int n_repeats = n_q_heads / n_kv_heads; + int total_work = B * n_q_heads * M; + + auto& pool = cpu::ThreadPool::instance(); + int nth = std::min(pool.max_threads(), total_work); + if (total_work < 4) { + nth = 1; + } + + // Select kernel: SIMD-batched exp for generation (M=1), scalar for prompt. + // Resolved once here via function pointer -- no branch in hot loop. + auto get_kernel = [&]() { + if constexpr (std::is_same_v) { + return (M == 1) ? &sdpa_single_head_f32_gen + : &sdpa_single_head_f32_prompt; + } else { + return (M == 1) ? &sdpa_single_head_half_gen + : &sdpa_single_head_half_prompt; + } + }; + auto kernel = get_kernel(); + + auto work = [&](int tid, int num_threads) { + int work_per = (total_work + num_threads - 1) / num_threads; + int start = work_per * tid; + int end = std::min(start + work_per, total_work); + + for (int idx = start; idx < end; idx++) { + int m = idx % M; + int rem = idx / M; + int h = rem % n_q_heads; + int b = rem / n_q_heads; + int kv_h = h / n_repeats; + + const T* q = queries + ((b * n_q_heads + h) * M + m) * head_dim; + const T* k = keys + (b * n_kv_heads + kv_h) * seq_len * head_dim; + const T* v = values + (b * n_kv_heads + kv_h) * seq_len * head_dim; + T* out = output + ((b * n_q_heads + h) * M + m) * head_dim; + + int effective_len = + do_causal ? std::min(seq_len, seq_len - M + m + 1) : seq_len; + + const T* m_ptr = + has_mask ? mask + ((b * n_q_heads + h) * M + m) * seq_len : nullptr; + + float sink_val = has_sinks ? static_cast(sinks[h]) : 0.0f; + + kernel( + out, + q, + k, + v, + seq_len, + head_dim, + scale, + effective_len, + m_ptr, + sink_val, + has_sinks); + } + }; + + if (nth > 1) { + pool.parallel_for(nth, work); + } else { + work(0, 1); + } +} + +} // namespace + +void ScaledDotProductAttention::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + if (output_logsumexp_) { + throw std::runtime_error( + "[ScaledDotProductAttention::eval_cpu] logsumexp output not supported " + "on CPU. This should have been caught by use_fallback."); + } + if (inputs[0].shape(-1) != inputs[2].shape(-1) || inputs[0].shape(-1) > 256 || + inputs[1].shape(-2) != inputs[2].shape(-2)) { + throw std::invalid_argument( + "[ScaledDotProductAttention::eval_cpu] The CPU kernel needs queries, " + "keys and values with one head dimension of at most 256, and values " + "as long as the keys. This should have been caught by use_fallback."); + } + + auto& q_in = inputs[0]; // (B, n_q_heads, M, head_dim) + auto& k_in = inputs[1]; // (B, n_kv_heads, S, head_dim) + auto& v_in = inputs[2]; // (B, n_kv_heads, S, head_dim) + auto& out = outputs[0]; // (B, n_q_heads, M, head_dim) + + // Determine which optional inputs are present. + // Input layout: {q, k, v, [mask], [sinks]} + // - No mask, no sinks: size=3 + // - Mask only: size=4, mask=inputs[3] + // - Sinks only: size=4, sinks=inputs[3] (has_sinks_ is true) + // - Both: size=5, mask=inputs[3], sinks=inputs[4] + bool has_arr_mask = + (!has_sinks_ && inputs.size() > 3) || (has_sinks_ && inputs.size() > 4); + + // Ensure contiguous with stride-1 last dim + auto ensure_contiguous = [this](const array& arr) -> array { + if (arr.flags().row_contiguous) { + return arr; + } + return contiguous_copy_cpu(arr, stream()); + }; + + array q = ensure_contiguous(q_in); + array k = ensure_contiguous(k_in); + array v = ensure_contiguous(v_in); + + // Make mask contiguous if present + auto mask_arr = has_arr_mask + ? std::optional(ensure_contiguous(inputs[3])) + : std::nullopt; + + // Sinks is 1D (n_q_heads,); the kernels read it with stride 1. + auto sinks_arr = has_sinks_ + ? std::optional(ensure_contiguous(inputs.back())) + : std::nullopt; + + int B = q.shape(0); + int n_q_heads = q.shape(1); + int n_kv_heads = k.shape(1); + int M = q.shape(2); + int seq_len = k.shape(2); + int head_dim = q.shape(3); + + // Allocate output + out.set_data(allocator::malloc(out.nbytes())); + + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(q); + encoder.set_input_array(k); + encoder.set_input_array(v); + if (has_arr_mask) { + encoder.set_input_array(*mask_arr); + } + if (has_sinks_) { + encoder.set_input_array(*sinks_arr); + } + encoder.set_output_array(out); + + // Keep temporaries alive if we made copies + if (!q_in.flags().row_contiguous) { + encoder.add_temporary(q); + } + if (!k_in.flags().row_contiguous) { + encoder.add_temporary(k); + } + if (!v_in.flags().row_contiguous) { + encoder.add_temporary(v); + } + if (has_arr_mask && !inputs[3].flags().row_contiguous) { + encoder.add_temporary(*mask_arr); + } + if (has_sinks_ && !inputs.back().flags().row_contiguous) { + encoder.add_temporary(*sinks_arr); + } + + float scale = scale_; + bool do_causal = do_causal_; + bool has_sinks = has_sinks_; + + switch (q.dtype()) { + case float32: { + const float* q_ptr = q.data(); + const float* k_ptr = k.data(); + const float* v_ptr = v.data(); + float* out_ptr = out.data(); + const float* mask_ptr = has_arr_mask ? mask_arr->data() : nullptr; + const float* sinks_ptr = has_sinks ? sinks_arr->data() : nullptr; + + encoder.dispatch([=]() { +#if defined(MLX_USE_HIGHWAY_KERNELS) + sdpa_highway( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + SdpaHighwayDType::Float32, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#else + sdpa_impl( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#endif + }); + break; + } + case float16: { + const float16_t* q_ptr = q.data(); + const float16_t* k_ptr = k.data(); + const float16_t* v_ptr = v.data(); + float16_t* out_ptr = out.data(); + const float16_t* mask_ptr = + has_arr_mask ? mask_arr->data() : nullptr; + const float16_t* sinks_ptr = + has_sinks ? sinks_arr->data() : nullptr; + + encoder.dispatch([=]() { +#if defined(MLX_USE_HIGHWAY_KERNELS) + sdpa_highway( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + SdpaHighwayDType::Float16, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#else + sdpa_impl( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#endif + }); + break; + } + case bfloat16: { + const bfloat16_t* q_ptr = q.data(); + const bfloat16_t* k_ptr = k.data(); + const bfloat16_t* v_ptr = v.data(); + bfloat16_t* out_ptr = out.data(); + const bfloat16_t* mask_ptr = + has_arr_mask ? mask_arr->data() : nullptr; + const bfloat16_t* sinks_ptr = + has_sinks ? sinks_arr->data() : nullptr; + + encoder.dispatch([=]() { +#if defined(MLX_USE_HIGHWAY_KERNELS) + sdpa_highway( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + SdpaHighwayDType::BFloat16, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#else + sdpa_impl( + out_ptr, + q_ptr, + k_ptr, + v_ptr, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask_ptr, + has_arr_mask, + sinks_ptr, + has_sinks); +#endif + }); + break; + } + default: + throw std::runtime_error( + "[ScaledDotProductAttention::eval_cpu] Unsupported type"); + } +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/sdpa_highway.cpp b/mlx/backend/cpu/sdpa_highway.cpp new file mode 100644 index 0000000000..41190127a1 --- /dev/null +++ b/mlx/backend/cpu/sdpa_highway.cpp @@ -0,0 +1,588 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +// Normally this file is compiled directly and Highway emits its runtime +// dispatch targets. Native MSVC builds compile this file once per target with +// MLX_HIGHWAY_MANUAL_TARGET and MLX_HIGHWAY_TARGET_SUFFIX so the same kernels +// are emitted as one manually suffixed specialization. + +#include +#include +#include + +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/sdpa_highway.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/types/half_types.h" + +#if !defined(MLX_HIGHWAY_MANUAL_TARGET) +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/sdpa_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep +#endif + +#include "hwy/highway.h" +#include "mlx/backend/cpu/highway_utils.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::fast { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; +namespace hu = mlx::core::highway::HWY_NAMESPACE; +using hu::load_typed_as_f32; +using hu::store_f32_as_typed; + +// 16 float lanes at most: no SVE until kernels are vector-length agnostic. +constexpr int kMaxLanes = 16; +static_assert( + hn::MaxLanes(hn::ScalableTag()) <= kMaxLanes, + "a float vector must fit the per-lane buffers"); + +template +hn::Vec exp_lanes(DF df, hn::Vec x) { + using V = hn::Vec; + const hn::Rebind di; + + const V x_init = x; + x = hn::Mul(x, hn::Set(df, 1.442695f)); + const V ipart = hn::Floor(hn::Add(x, hn::Set(df, 0.5f))); + const V fpart = hn::Sub(x, ipart); + + V poly = hn::Set(df, 1.535336188319500e-4f); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 1.339887440266574e-3f)); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 9.618437357674640e-3f)); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 5.550332471162809e-2f)); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 2.402264791363012e-1f)); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 6.931472028550421e-1f)); + poly = hn::MulAdd(poly, fpart, hn::Set(df, 1.000000000000000f)); + + const auto biased_exp = + hn::Add(hn::ConvertTo(di, ipart), hn::Set(di, int32_t{127})); + V result = hn::Mul(hn::BitCast(df, hn::ShiftLeft<23>(biased_exp)), poly); + result = + hn::IfThenElse(hn::Lt(x_init, hn::Set(df, -88.0f)), hn::Zero(df), result); + result = hn::IfThenElse( + hn::Gt(x_init, hn::Set(df, 88.0f)), + hn::Set(df, std::numeric_limits::infinity()), + result); + return result; +} + +template +float sdpa_dot_one( + DF df, + const float* HWY_RESTRICT query, + const T* HWY_RESTRICT key, + int head_dim, + float scale, + const T* HWY_RESTRICT mask, + int row) { + using V = hn::Vec; + const int lanes = static_cast(hn::Lanes(df)); + V dot_acc = hn::Zero(df); + int d = 0; + for (; d + lanes <= head_dim; d += lanes) { + dot_acc = hn::MulAdd( + hn::LoadU(df, query + d), load_typed_as_f32(df, key, d), dot_acc); + } + float dot = hn::ReduceSum(df, dot_acc); + for (; d < head_dim; ++d) { + dot += query[d] * static_cast(key[d]); + } + dot *= scale; + if (mask) { + dot += static_cast(mask[row]); + } + return dot; +} + +template +void sdpa_dot_four( + DF df, + const float* HWY_RESTRICT query, + const T* HWY_RESTRICT keys, + int head_dim, + float scale, + const T* HWY_RESTRICT mask, + int row, + float* HWY_RESTRICT dots) { + using V = hn::Vec; + const int lanes = static_cast(hn::Lanes(df)); + const T* key0 = keys + row * head_dim; + const T* key1 = key0 + head_dim; + const T* key2 = key1 + head_dim; + const T* key3 = key2 + head_dim; + + V acc0 = hn::Zero(df); + V acc1 = hn::Zero(df); + V acc2 = hn::Zero(df); + V acc3 = hn::Zero(df); + int d = 0; + for (; d + lanes <= head_dim; d += lanes) { + const V q = hn::LoadU(df, query + d); + acc0 = hn::MulAdd(q, load_typed_as_f32(df, key0, d), acc0); + acc1 = hn::MulAdd(q, load_typed_as_f32(df, key1, d), acc1); + acc2 = hn::MulAdd(q, load_typed_as_f32(df, key2, d), acc2); + acc3 = hn::MulAdd(q, load_typed_as_f32(df, key3, d), acc3); + } + + float dot0 = hn::ReduceSum(df, acc0); + float dot1 = hn::ReduceSum(df, acc1); + float dot2 = hn::ReduceSum(df, acc2); + float dot3 = hn::ReduceSum(df, acc3); + for (; d < head_dim; ++d) { + const float q = query[d]; + dot0 += q * static_cast(key0[d]); + dot1 += q * static_cast(key1[d]); + dot2 += q * static_cast(key2[d]); + dot3 += q * static_cast(key3[d]); + } + + dots[0] = dot0 * scale; + dots[1] = dot1 * scale; + dots[2] = dot2 * scale; + dots[3] = dot3 * scale; + if (mask) { + dots[0] += static_cast(mask[row]); + dots[1] += static_cast(mask[row + 1]); + dots[2] += static_cast(mask[row + 2]); + dots[3] += static_cast(mask[row + 3]); + } +} + +template +void sdpa_accum_values( + DF df, + hn::Vec* HWY_RESTRICT output, + int n_acc, + int lanes, + int head_dim, + const T* HWY_RESTRICT values, + const float* HWY_RESTRICT weights, + int rows) { + using V = hn::Vec; + for (int i = 0; i < n_acc && i * lanes < head_dim; ++i) { + const int offset = i * lanes; + V acc = output[i]; + if (offset + lanes <= head_dim) { + for (int r = 0; r < rows; ++r) { + acc = hn::MulAdd( + hn::Set(df, weights[r]), + load_typed_as_f32(df, values + r * head_dim, offset), + acc); + } + } else { + const int remaining = head_dim - offset; + for (int r = 0; r < rows; ++r) { + alignas(64) float v_tmp[kMaxLanes] = {}; + for (int j = 0; j < remaining; ++j) { + v_tmp[j] = static_cast(values[r * head_dim + offset + j]); + } + acc = hn::MulAdd(hn::Set(df, weights[r]), hn::LoadU(df, v_tmp), acc); + } + } + output[i] = acc; + } +} + +template +void sdpa_single_head( + T* HWY_RESTRICT output, + const T* HWY_RESTRICT query, + const T* HWY_RESTRICT keys, + const T* HWY_RESTRICT values, + int head_dim, + float scale, + int effective_len, + const T* HWY_RESTRICT mask, + float sink_value, + bool has_sinks) { + const hn::ScalableTag df; + using V = hn::Vec; + + constexpr int kMaxHeadDim = 256; + constexpr int kMaxAcc = 64; + const int lanes = static_cast(hn::Lanes(df)); + const int n_acc = std::min((head_dim + lanes - 1) / lanes, kMaxAcc); + const float neg_inf = -std::numeric_limits::infinity(); + + alignas(64) float q_f[kMaxHeadDim]; + int d = 0; + for (; d + lanes <= head_dim; d += lanes) { + hn::StoreU(load_typed_as_f32(df, query, d), df, q_f + d); + } + for (; d < head_dim; ++d) { + q_f[d] = static_cast(query[d]); + } + + V O_acc[kMaxAcc]; + for (int i = 0; i < n_acc; ++i) { + O_acc[i] = hn::Zero(df); + } + float running_max = neg_inf; + float running_sum = 0.0f; + + int s = 0; + for (; s + lanes <= effective_len; s += lanes) { + alignas(64) float dots[kMaxLanes]; + for (int b = 0; b + 4 <= lanes; b += 4) { + sdpa_dot_four(df, q_f, keys, head_dim, scale, mask, s + b, dots + b); + } + for (int b = lanes / 4 * 4; b < lanes; ++b) { + dots[b] = sdpa_dot_one( + df, q_f, keys + (s + b) * head_dim, head_dim, scale, mask, s + b); + } + + const V vdots = hn::LoadU(df, dots); + const float block_max = hn::ReduceMax(df, vdots); + if (block_max == neg_inf) { + continue; + } + if (block_max > running_max) { + const float correction = std::exp(running_max - block_max); + running_sum *= correction; + const V vcorr = hn::Set(df, correction); + for (int i = 0; i < n_acc; ++i) { + O_acc[i] = hn::Mul(O_acc[i], vcorr); + } + running_max = block_max; + } + + const V vexp = exp_lanes(df, hn::Sub(vdots, hn::Set(df, running_max))); + running_sum += hn::ReduceSum(df, vexp); + + alignas(64) float exp_arr[kMaxLanes]; + hn::StoreU(vexp, df, exp_arr); + for (int b = 0; b < lanes; b += 4) { + sdpa_accum_values( + df, + O_acc, + n_acc, + lanes, + head_dim, + values + (s + b) * head_dim, + exp_arr + b, + std::min(4, lanes - b)); + } + } + + for (; s < effective_len; ++s) { + const float dot = + sdpa_dot_one(df, q_f, keys + s * head_dim, head_dim, scale, mask, s); + if (dot == neg_inf) { + continue; + } + + const float new_max = std::max(running_max, dot); + if (new_max > running_max) { + const float correction = std::exp(running_max - new_max); + running_sum *= correction; + const V vcorr = hn::Set(df, correction); + for (int i = 0; i < n_acc; ++i) { + O_acc[i] = hn::Mul(O_acc[i], vcorr); + } + running_max = new_max; + } + const float exp_dot = std::exp(dot - running_max); + running_sum += exp_dot; + sdpa_accum_values( + df, O_acc, n_acc, lanes, head_dim, values + s * head_dim, &exp_dot, 1); + } + + if (has_sinks) { + const float new_max = std::max(running_max, sink_value); + if (new_max > neg_inf) { + const float correction = std::exp(running_max - new_max); + running_sum *= correction; + const V vcorr = hn::Set(df, correction); + for (int i = 0; i < n_acc; ++i) { + O_acc[i] = hn::Mul(O_acc[i], vcorr); + } + running_sum += std::exp(sink_value - new_max); + } + } + + if (running_sum > 0.0f) { + const float inv_sum = 1.0f / running_sum; + const V vinv = hn::Set(df, inv_sum); + for (int i = 0; i < n_acc && i * lanes < head_dim; ++i) { + const V result = hn::Mul(O_acc[i], vinv); + if (i * lanes + lanes <= head_dim) { + store_f32_as_typed(df, result, output, i * lanes); + } else { + alignas(64) float tmp[kMaxLanes]; + hn::StoreU(result, df, tmp); + const int remaining = head_dim - i * lanes; + for (int j = 0; j < remaining; ++j) { + output[i * lanes + j] = static_cast(tmp[j]); + } + } + } + } else { + for (int i = 0; i < head_dim; ++i) { + output[i] = static_cast(0.0f); + } + } +} + +template +void SdpaHighwayForDType( + T* HWY_RESTRICT output, + const T* HWY_RESTRICT queries, + const T* HWY_RESTRICT keys, + const T* HWY_RESTRICT values, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const T* HWY_RESTRICT mask, + bool has_mask, + const T* HWY_RESTRICT sinks, + bool has_sinks) { + const int n_repeats = n_q_heads / n_kv_heads; + const int total_work = B * n_q_heads * M; + + auto& pool = cpu::ThreadPool::instance(); + int nth = std::min(pool.max_threads(), total_work); + if (total_work < 4) { + nth = 1; + } + + auto work = [&](int tid, int num_threads) { + const int work_per = (total_work + num_threads - 1) / num_threads; + const int start = work_per * tid; + const int end = std::min(start + work_per, total_work); + + for (int idx = start; idx < end; ++idx) { + const int m = idx % M; + const int rem = idx / M; + const int h = rem % n_q_heads; + const int b = rem / n_q_heads; + const int kv_h = h / n_repeats; + + const T* q = queries + ((b * n_q_heads + h) * M + m) * head_dim; + const T* k = keys + (b * n_kv_heads + kv_h) * seq_len * head_dim; + const T* v = values + (b * n_kv_heads + kv_h) * seq_len * head_dim; + T* out = output + ((b * n_q_heads + h) * M + m) * head_dim; + + const int effective_len = + do_causal ? std::min(seq_len, seq_len - M + m + 1) : seq_len; + const T* mask_ptr = + has_mask ? mask + ((b * n_q_heads + h) * M + m) * seq_len : nullptr; + const float sink_val = has_sinks ? static_cast(sinks[h]) : 0.0f; + + sdpa_single_head( + out, + q, + k, + v, + head_dim, + scale, + effective_len, + mask_ptr, + sink_val, + has_sinks); + } + }; + + if (nth > 1) { + pool.parallel_for(nth, work); + } else { + work(0, 1); + } +} + +void SdpaHighway( + void* HWY_RESTRICT output, + const void* HWY_RESTRICT queries, + const void* HWY_RESTRICT keys, + const void* HWY_RESTRICT values, + SdpaHighwayDType dtype, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const void* HWY_RESTRICT mask, + bool has_mask, + const void* HWY_RESTRICT sinks, + bool has_sinks) { + MLX_HIGHWAY_RECORD(Sdpa); + switch (dtype) { + case SdpaHighwayDType::Float32: + SdpaHighwayForDType( + static_cast(output), + static_cast(queries), + static_cast(keys), + static_cast(values), + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + static_cast(mask), + has_mask, + static_cast(sinks), + has_sinks); + break; + case SdpaHighwayDType::Float16: + SdpaHighwayForDType( + static_cast(output), + static_cast(queries), + static_cast(keys), + static_cast(values), + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + static_cast(mask), + has_mask, + static_cast(sinks), + has_sinks); + break; + case SdpaHighwayDType::BFloat16: + SdpaHighwayForDType( + static_cast(output), + static_cast(queries), + static_cast(keys), + static_cast(values), + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + static_cast(mask), + has_mask, + static_cast(sinks), + has_sinks); + break; + } +} + +} // namespace +} // namespace HWY_NAMESPACE +} // namespace mlx::core::fast +HWY_AFTER_NAMESPACE(); + +#if HWY_ONCE +namespace mlx::core::fast { + +#if defined(MLX_HIGHWAY_MANUAL_TARGET) + +#ifndef MLX_HIGHWAY_TARGET_SUFFIX +#error "MLX_HIGHWAY_TARGET_SUFFIX must be defined for manual Highway targets" +#endif + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) +#define MLX_HIGHWAY_TARGET_FUNC(name) \ + MLX_HIGHWAY_CONCAT(name, MLX_HIGHWAY_TARGET_SUFFIX) + +void MLX_HIGHWAY_TARGET_FUNC(sdpa_highway)( + void* output, + const void* queries, + const void* keys, + const void* values, + SdpaHighwayDType dtype, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const void* mask, + bool has_mask, + const void* sinks, + bool has_sinks) { + HWY_STATIC_DISPATCH(SdpaHighway) + (output, + queries, + keys, + values, + dtype, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask, + has_mask, + sinks, + has_sinks); +} + +#undef MLX_HIGHWAY_TARGET_FUNC +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +#else + +HWY_EXPORT(SdpaHighway); + +void sdpa_highway( + void* output, + const void* queries, + const void* keys, + const void* values, + SdpaHighwayDType dtype, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const void* mask, + bool has_mask, + const void* sinks, + bool has_sinks) { + HWY_DYNAMIC_DISPATCH(SdpaHighway) + (output, + queries, + keys, + values, + dtype, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask, + has_mask, + sinks, + has_sinks); +} + +#endif + +} // namespace mlx::core::fast +#endif +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/sdpa_highway.h b/mlx/backend/cpu/sdpa_highway.h new file mode 100644 index 0000000000..a37b18e279 --- /dev/null +++ b/mlx/backend/cpu/sdpa_highway.h @@ -0,0 +1,34 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include + +namespace mlx::core::fast { + +enum class SdpaHighwayDType : uint8_t { + Float32, + Float16, + BFloat16, +}; + +void sdpa_highway( + void* output, + const void* queries, + const void* keys, + const void* values, + SdpaHighwayDType dtype, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const void* mask, + bool has_mask, + const void* sinks, + bool has_sinks); + +} // namespace mlx::core::fast diff --git a/mlx/backend/cpu/sdpa_highway_dispatch.cpp b/mlx/backend/cpu/sdpa_highway_dispatch.cpp new file mode 100644 index 0000000000..2f3f633253 --- /dev/null +++ b/mlx/backend/cpu/sdpa_highway_dispatch.cpp @@ -0,0 +1,132 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/sdpa_highway.h" + +#include "hwy/highway.h" + +namespace mlx::core::fast { + +#define MLX_HIGHWAY_CONCAT2(a, b) a##b +#define MLX_HIGHWAY_CONCAT(a, b) MLX_HIGHWAY_CONCAT2(a, b) + +using SdpaFn = void (*)( + void*, + const void*, + const void*, + const void*, + SdpaHighwayDType, + int, + int, + int, + int, + int, + int, + float, + bool, + const void*, + bool, + const void*, + bool); + +#define MLX_DECLARE_SDPA_TARGET(suffix) \ + void MLX_HIGHWAY_CONCAT(sdpa_highway, suffix)( \ + void*, \ + const void*, \ + const void*, \ + const void*, \ + SdpaHighwayDType, \ + int, \ + int, \ + int, \ + int, \ + int, \ + int, \ + float, \ + bool, \ + const void*, \ + bool, \ + const void*, \ + bool) + +MLX_DECLARE_SDPA_TARGET(_avx2); +MLX_DECLARE_SDPA_TARGET(_sse4); +MLX_DECLARE_SDPA_TARGET(_ssse3); +MLX_DECLARE_SDPA_TARGET(_sse2); + +#undef MLX_DECLARE_SDPA_TARGET + +namespace { + +struct SdpaHighwayDispatch { + SdpaFn sdpa; +}; + +#define MLX_SDPA_DISPATCH(suffix) \ + SdpaHighwayDispatch { \ + MLX_HIGHWAY_CONCAT(sdpa_highway, suffix) \ + } + +const SdpaHighwayDispatch& sdpa_dispatch() { + static const SdpaHighwayDispatch dispatch = [] { + const int64_t targets = hwy::SupportedTargets(); + if (targets & HWY_AVX2) { + return MLX_SDPA_DISPATCH(_avx2); + } + if (targets & HWY_SSE4) { + return MLX_SDPA_DISPATCH(_sse4); + } + if (targets & HWY_SSSE3) { + return MLX_SDPA_DISPATCH(_ssse3); + } + return MLX_SDPA_DISPATCH(_sse2); + }(); + return dispatch; +} + +#undef MLX_SDPA_DISPATCH +#undef MLX_HIGHWAY_CONCAT +#undef MLX_HIGHWAY_CONCAT2 + +} // namespace + +void sdpa_highway( + void* output, + const void* queries, + const void* keys, + const void* values, + SdpaHighwayDType dtype, + int B, + int n_q_heads, + int n_kv_heads, + int M, + int seq_len, + int head_dim, + float scale, + bool do_causal, + const void* mask, + bool has_mask, + const void* sinks, + bool has_sinks) { + sdpa_dispatch().sdpa( + output, + queries, + keys, + values, + dtype, + B, + n_q_heads, + n_kv_heads, + M, + seq_len, + head_dim, + scale, + do_causal, + mask, + has_mask, + sinks, + has_sinks); +} + +} // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index a094c1a334..007b1a0c74 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -1,4 +1,27 @@ #pragma once +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#ifdef _MSC_VER +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES +#endif +#include +#endif + +#include +#include +#include +#include +#include +#include + +// Fallback definitions for math constants on MSVC +// (may not be defined if was included before _USE_MATH_DEFINES was set) +#ifndef M_LN2 +#define M_LN2 0.69314718055994530942 +#endif + +#else // Required for using M_LN2 in MSVC. #define _USE_MATH_DEFINES @@ -14,6 +37,7 @@ #include // For _BitScanReverse #endif +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/backend/cpu/simd/saturating_cast.h" #include "mlx/types/complex.h" #include "mlx/types/half_types.h" @@ -44,6 +68,32 @@ struct Simd { } }; +#if defined(MLX_USE_HIGHWAY_KERNELS) +namespace detail { + +template +struct HasStaticLoad : std::false_type {}; + +template +struct HasStaticLoad< + V, + T, + std::void_t()))>> : std::true_type { +}; + +template +struct HasMemberStore : std::false_type {}; + +template +struct HasMemberStore< + V, + T, + std::void_t().store(std::declval()))>> + : std::true_type {}; + +} // namespace detail + +#endif // MLX_USE_HIGHWAY_KERNELS // Conversion of a value that is known to fit in To, without a range test. template Simd convert_in_range(Simd v) { @@ -52,11 +102,25 @@ Simd convert_in_range(Simd v) { template Simd load(const T* x) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) return *(Simd*)x; +#else + if constexpr (detail::HasStaticLoad, T>::value) { + return Simd::load(x); + } else { + return *(Simd*)x; + } +#endif // MLX_USE_HIGHWAY_KERNELS } template void store(T* dst, Simd x) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if constexpr (detail::HasMemberStore, T>::value) { + x.store(dst); + return; + } +#endif // MLX_USE_HIGHWAY_KERNELS // Maintain invariant that bool is either 0 or 1 as // simd comparison ops set all bits in the result to 1 if constexpr (std::is_same_v && N > 1) { @@ -246,12 +310,17 @@ Simd abs(Simd in) { template Simd clz(Simd x_) { #ifdef _MSC_VER +#if !defined(MLX_USE_HIGHWAY_KERNELS) // MSVC doesn't have __builtin_clz, use _BitScanReverse instead unsigned long index; if (_BitScanReverse(&index, static_cast(x_.value))) { return static_cast(31 - index); } return static_cast(32); // All zeros case +#else + unsigned long idx; + return _BitScanReverse(&idx, (unsigned long)x_.value) ? (31 - idx) : 32; +#endif // MLX_USE_HIGHWAY_KERNELS #else return __builtin_clz(x_.value); #endif @@ -293,7 +362,11 @@ Simd remainder(Simd a_, Simd b_) { } r = a % b; } else { +#if !defined(MLX_USE_HIGHWAY_KERNELS) r = std::remainder(a, b); +#else + r = std::fmod(a, b); +#endif // MLX_USE_HIGHWAY_KERNELS } if constexpr (is_signed_v) { if (r != 0 && (r < 0 != b < 0)) { @@ -308,6 +381,11 @@ Simd maximum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if (std::isnan(b)) { + return b; + } +#endif // MLX_USE_HIGHWAY_KERNELS if (mlx::core::isnan(a)) { return a; } @@ -320,6 +398,11 @@ Simd minimum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + if (std::isnan(b)) { + return b; + } +#endif // MLX_USE_HIGHWAY_KERNELS if (mlx::core::isnan(a)) { return a; } diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h new file mode 100644 index 0000000000..15a8e6a900 --- /dev/null +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -0,0 +1,1031 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/backend/cpu/simd/base_simd.h" +#include "mlx/types/half_types.h" + +#include "hwy/highway.h" + +#include + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::simd { +namespace hn = hwy::HWY_NAMESPACE; + +// Highway's AVX3-family x86 targets use 512-bit vectors. +#if HWY_TARGET == HWY_AVX3 || HWY_TARGET == HWY_AVX3_DL || \ + HWY_TARGET == HWY_AVX3_ZEN4 || HWY_TARGET == HWY_AVX3_SPR || \ + HWY_TARGET == HWY_AVX10_2 +inline constexpr int highway_max_f32_lanes = 16; +inline constexpr int highway_max_f64_lanes = 8; +#elif HWY_TARGET == HWY_AVX2 +inline constexpr int highway_max_f32_lanes = 8; +inline constexpr int highway_max_f64_lanes = 4; +#else +inline constexpr int highway_max_f32_lanes = 4; +inline constexpr int highway_max_f64_lanes = 2; +#endif + +template <> +inline constexpr int max_size = highway_max_f32_lanes; +template <> +inline constexpr int max_size = highway_max_f64_lanes; +template <> +inline constexpr int max_size = highway_max_f32_lanes; +template <> +inline constexpr int max_size = highway_max_f32_lanes; +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = highway_max_f32_lanes; +template <> +inline constexpr int max_size = highway_max_f32_lanes; + +namespace highway_detail { + +template +struct LaneType { + using type = T; +}; + +template <> +struct LaneType { + using type = hwy::float16_t; +}; + +template <> +struct LaneType { + using type = hwy::bfloat16_t; +}; + +template +using LaneTypeT = typename LaneType::type; + +template +using D = hn::FixedTag, N>; + +template +struct IsSimd : std::false_type {}; + +template +struct IsSimd> : std::true_type {}; + +template +using EnableIfVector = std::enable_if_t<(N > 1), T>; + +template +using EnableIfVectorNonBool = + std::enable_if_t<(N > 1) && !std::is_same_v, R>; + +template +constexpr bool is_half_v = + std::is_same_v || std::is_same_v; + +template +uint16_t half_bits(T value) { + uint16_t bits; + std::memcpy(&bits, &value, sizeof(bits)); + return bits; +} + +template +LaneTypeT to_lane(U value) { + if constexpr (std::is_same_v) { + return hwy::float16_t::FromBits( + half_bits(static_cast(static_cast(value)))); + } else if constexpr (std::is_same_v) { + return hwy::bfloat16_t::FromBits( + half_bits(static_cast(static_cast(value)))); + } else { + return static_cast(value); + } +} + +template +T from_lane(Lane value) { + if constexpr (std::is_same_v) { + uint16_t bits = hwy::BitCastScalar(value); + float16_t out; + std::memcpy(&out, &bits, sizeof(out)); + return out; + } else if constexpr (std::is_same_v) { + uint16_t bits = hwy::BitCastScalar(value); + bfloat16_t out; + std::memcpy(&out, &bits, sizeof(out)); + return out; + } else { + return static_cast(value); + } +} + +template +const LaneTypeT* lane_ptr(const T* ptr) { + return reinterpret_cast*>(ptr); +} + +template +LaneTypeT* lane_ptr(T* ptr) { + return reinterpret_cast*>(ptr); +} + +// Highway's emulated float16 -> float32 decodes exponent 31 as finite (inf as +// 65536); return inf or quiet NaN there. Same as highway_utils.h's copy. +template +hn::Vec promote_f16(DF df, hn::Vec> v) { + const hn::RebindToUnsigned du; + const hn::Rebind du16; + const auto bits = hn::PromoteTo(du, hn::BitCast(du16, v)); + const auto mantissa = hn::And(bits, hn::Set(du, 0x3FFu)); + const auto special = + hn::Eq(hn::And(bits, hn::Set(du, 0x7C00u)), hn::Set(du, 0x7C00u)); + const auto quiet = hn::IfThenElseZero( + hn::Ne(mantissa, hn::Zero(du)), hn::Set(du, 0x400000u)); + const auto inf_nan = hn::Or( + hn::Or( + hn::ShiftLeft<16>(hn::And(bits, hn::Set(du, 0x8000u))), + hn::Set(du, 0x7F800000u)), + hn::Or(hn::ShiftLeft<13>(mantissa), quiet)); + return hn::IfThenElse( + hn::RebindMask(df, special), + hn::BitCast(df, inf_nan), + hn::PromoteTo(df, v)); +} + +template +Simd map_unary(Simd x, Fn fn); + +template +Simd map_binary(Simd x, Simd y, Fn fn); + +template +struct BoolSimdBase { + static constexpr int size = N; + uint8_t bits[(N + 7) / 8] = {}; + + BoolSimdBase() = default; + + BoolSimdBase(bool value) { + if (value) { + for (int i = 0; i < static_cast(sizeof(bits)); ++i) { + bits[i] = 0xFF; + } + bits[sizeof(bits) - 1] &= + static_cast((1u << (((N - 1) % 8) + 1)) - 1u); + } + } + + template + explicit BoolSimdBase(Simd value) { + static_assert( + !is_half_v, + "Highway does not compare float16 and bfloat16 lanes on every target"); + using D = highway_detail::D; + const D d; + // Compare with zero, as static_cast does. MaskFromVec is defined + // only for lanes of all zeros or all ones: x86 reads the top bit of each + // lane, and NEON bit i of lane i. + hn::StoreMaskBits(d, hn::Ne(value.value, hn::Zero(d)), bits); + } + + template + hn::Mask to_mask(D d) const { + return hn::LoadMaskBits(d, bits); + } + + static BoolSimdBase load(const bool* ptr) { + BoolSimdBase out; + for (int i = 0; i < N; ++i) { + if (ptr[i]) { + out.bits[i / 8] |= static_cast(1u << (i % 8)); + } + } + return out; + } + + void store(bool* ptr) const { + for (int i = 0; i < N; ++i) { + ptr[i] = (bits[i / 8] & static_cast(1u << (i % 8))) != 0; + } + } + + bool operator[](int idx) const { + return (bits[idx / 8] & static_cast(1u << (idx % 8))) != 0; + } +}; + +} // namespace highway_detail + +#define MLX_HIGHWAY_BOOL_SIMD(N) \ + template <> \ + struct Simd : highway_detail::BoolSimdBase { \ + using Base = highway_detail::BoolSimdBase; \ + using Base::Base; \ + \ + static Simd load(const bool* ptr) { \ + Simd out; \ + static_cast(out) = Base::load(ptr); \ + return out; \ + } \ + \ + template \ + static Simd from_mask(D d, hn::Mask mask) { \ + Simd out; \ + hn::StoreMaskBits(d, mask, out.bits); \ + return out; \ + } \ + }; + +MLX_HIGHWAY_BOOL_SIMD(2) +MLX_HIGHWAY_BOOL_SIMD(4) +MLX_HIGHWAY_BOOL_SIMD(8) +MLX_HIGHWAY_BOOL_SIMD(16) +#undef MLX_HIGHWAY_BOOL_SIMD + +template +struct Simd { + static constexpr int size = N; + using D = highway_detail::D; + using V = hn::Vec; + + V value; + + Simd() : value(hn::Zero(D())) {} + + template < + typename U, + typename = + std::enable_if_t>::value>> + Simd(U v) : value(hn::Set(D(), highway_detail::to_lane(v))) {} + + template + Simd(Simd other) { + if constexpr (std::is_same_v) { + value = other.value; + } else if constexpr ( + std::is_same_v && highway_detail::is_half_v) { + if constexpr (std::is_same_v) { + value = highway_detail::promote_f16(D(), other.value); + } else { + value = hn::PromoteTo(D(), other.value); + } + } else if constexpr ( + highway_detail::is_half_v && std::is_same_v) { + value = hn::DemoteTo(D(), other.value); + } else if constexpr ( + !highway_detail::is_half_v && !highway_detail::is_half_v && + !std::is_same_v && !std::is_same_v && + std::is_integral_v && std::is_integral_v && + sizeof(T) == sizeof(U)) { + value = hn::BitCast(D(), other.value); + } else if constexpr ( + !highway_detail::is_half_v && !highway_detail::is_half_v && + !std::is_same_v && !std::is_same_v && + sizeof(T) == sizeof(U)) { + if constexpr (is_float_to_int_cast_v) { + // ConvertTo saturates. Its result for NaN depends on the target. + value = hn::ConvertTo( + D(), hn::IfThenZeroElse(hn::IsNaN(other.value), other.value)); + } else { + value = hn::ConvertTo(D(), other.value); + } + } else if constexpr (std::is_same_v) { + const D d; + value = hn::IfThenElse( + other.to_mask(d), + hn::Set(d, highway_detail::to_lane(1)), + hn::Zero(d)); + } else { + alignas(64) U tmp_in[N]; + alignas(64) T tmp_out[N]; + other.store(tmp_in); + for (int i = 0; i < N; ++i) { + tmp_out[i] = saturating_cast(tmp_in[i]); + } + value = load(tmp_out).value; + } + } + + static Simd load(const T* ptr) { + Simd out; + out.value = hn::LoadU(D(), highway_detail::lane_ptr(ptr)); + return out; + } + + void store(T* ptr) const { + hn::StoreU(value, D(), highway_detail::lane_ptr(ptr)); + } + + T operator[](int idx) const { + alignas(64) T tmp[N]; + store(tmp); + return tmp[idx]; + } + + T& operator[](int idx) { + return reinterpret_cast(&value)[idx]; + } +}; + +template <> +struct Simd { + static constexpr int size = 4; + Simd lo; + Simd hi; + + Simd() = default; + Simd(int64_t v) : lo(v), hi(v) {} + + static Simd load(const int64_t* ptr) { + Simd out; + out.lo = simd::load(ptr); + out.hi = simd::load(ptr + 2); + return out; + } + + void store(int64_t* ptr) const { + simd::store(ptr, lo); + simd::store(ptr + 2, hi); + } + + int64_t operator[](int idx) const { + return idx < 2 ? lo[idx] : hi[idx - 2]; + } +}; + +template <> +struct Simd { + static constexpr int size = 8; + Simd lo; + Simd hi; + + Simd() = default; + Simd(int64_t v) : lo(v), hi(v) {} + + static Simd load(const int64_t* ptr) { + Simd out; + out.lo = simd::load(ptr); + out.hi = simd::load(ptr + 4); + return out; + } + + void store(int64_t* ptr) const { + simd::store(ptr, lo); + simd::store(ptr + 4, hi); + } + + int64_t operator[](int idx) const { + return idx < 4 ? lo[idx] : hi[idx - 4]; + } +}; + +template <> +struct Simd { + static constexpr int size = 4; + Simd lo; + Simd hi; + + Simd() = default; + Simd(uint64_t v) : lo(v), hi(v) {} + + static Simd load(const uint64_t* ptr) { + Simd out; + out.lo = simd::load(ptr); + out.hi = simd::load(ptr + 2); + return out; + } + + void store(uint64_t* ptr) const { + simd::store(ptr, lo); + simd::store(ptr + 2, hi); + } + + uint64_t operator[](int idx) const { + return idx < 2 ? lo[idx] : hi[idx - 2]; + } +}; + +template <> +struct Simd { + static constexpr int size = 8; + Simd lo; + Simd hi; + + Simd() = default; + Simd(uint64_t v) : lo(v), hi(v) {} + + static Simd load(const uint64_t* ptr) { + Simd out; + out.lo = simd::load(ptr); + out.hi = simd::load(ptr + 4); + return out; + } + + void store(uint64_t* ptr) const { + simd::store(ptr, lo); + simd::store(ptr + 4, hi); + } + + uint64_t operator[](int idx) const { + return idx < 4 ? lo[idx] : hi[idx - 4]; + } +}; + +namespace highway_detail { + +template +using MapComputeT = + std::conditional_t, double, float>; + +template +Simd map_unary(Simd x, Fn fn) { + alignas(64) T in[N]; + alignas(64) T out[N]; + x.store(in); + for (int i = 0; i < N; ++i) { + out[i] = static_cast(fn(static_cast>(in[i]))); + } + return Simd::load(out); +} + +template +Simd map_binary(Simd x, Simd y, Fn fn) { + alignas(64) T in_x[N]; + alignas(64) T in_y[N]; + alignas(64) T out[N]; + x.store(in_x); + y.store(in_y); + for (int i = 0; i < N; ++i) { + out[i] = static_cast( + fn(static_cast>(in_x[i]), + static_cast>(in_y[i]))); + } + return Simd::load(out); +} + +template +Simd map_integer_binary(Simd x, Simd y, Fn fn) { + alignas(64) T in_x[N]; + alignas(64) T in_y[N]; + alignas(64) T out[N]; + x.store(in_x); + y.store(in_y); + for (int i = 0; i < N; ++i) { + out[i] = static_cast(fn(in_x[i], in_y[i])); + } + return Simd::load(out); +} + +} // namespace highway_detail + +template = 0> +inline Simd operator!(Simd x) { + Simd out; + for (int i = 0; i < static_cast(sizeof(out.bits)); ++i) { + out.bits[i] = static_cast(~x.bits[i]); + } + out.bits[sizeof(out.bits) - 1] &= + static_cast((1u << (((N - 1) % 8) + 1)) - 1u); + return out; +} + +#define MLX_HIGHWAY_BOOL_OP(name, op) \ + template = 0> \ + inline Simd name(Simd a, Simd b) { \ + Simd out; \ + for (int i = 0; i < static_cast(sizeof(out.bits)); ++i) { \ + out.bits[i] = static_cast(a.bits[i] op b.bits[i]); \ + } \ + return out; \ + } + +MLX_HIGHWAY_BOOL_OP(operator&&, &) +MLX_HIGHWAY_BOOL_OP(operator&, &) +MLX_HIGHWAY_BOOL_OP(operator||, |) +MLX_HIGHWAY_BOOL_OP(operator|, |) +MLX_HIGHWAY_BOOL_OP(operator^, ^) +#undef MLX_HIGHWAY_BOOL_OP + +template = 0> +inline Simd operator==(Simd a, Simd b) { + return !(a ^ b); +} + +template = 0> +inline Simd operator!=(Simd a, Simd b) { + return a ^ b; +} + +#define MLX_HIGHWAY_ARITHMETIC(name, hwy_op) \ + template = 0> \ + inline Simd name(Simd a, Simd b) { \ + if constexpr (highway_detail::is_half_v) { \ + return Simd(name(Simd(a), Simd(b))); \ + } else { \ + Simd out; \ + out.value = hn::hwy_op(a.value, b.value); \ + return out; \ + } \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(Simd a, U b) { \ + return name(a, Simd(b)); \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(U a, Simd b) { \ + return name(Simd(a), b); \ + } + +MLX_HIGHWAY_ARITHMETIC(operator+, Add) +MLX_HIGHWAY_ARITHMETIC(operator-, Sub) +MLX_HIGHWAY_ARITHMETIC(operator*, Mul) +#undef MLX_HIGHWAY_ARITHMETIC + +template = 0> +inline Simd operator/(Simd a, Simd b) { + if constexpr (std::is_integral_v) { + return highway_detail::map_integer_binary(a, b, [](T x, T y) { + return divide(Simd(x), Simd(y)).value; + }); + } else if constexpr (highway_detail::is_half_v) { + return Simd(Simd(a) / Simd(b)); + } else { + Simd out; + out.value = hn::Div(a.value, b.value); + return out; + } +} + +// base_simd.h's divide: each lane divides as a scalar, because hn::Div is +// implementation-defined for y == 0 and INT_MIN / -1. +template = 0> +inline Simd divide(Simd a, Simd b) { + if constexpr (std::is_integral_v) { + return highway_detail::map_integer_binary(a, b, [](T x, T y) { + return divide(Simd(x), Simd(y)).value; + }); + } else { + return a / b; + } +} + +template = 0> +inline Simd operator/(Simd a, U b) { + return a / Simd(b); +} + +template = 0> +inline Simd operator/(U a, Simd b) { + return Simd(a) / b; +} + +template = 0> +inline Simd operator-(Simd a) { + if constexpr (highway_detail::is_half_v) { + return Simd(-Simd(a)); + } else if constexpr (std::is_unsigned_v) { + Simd out; + out.value = hn::Sub(hn::Zero(typename Simd::D()), a.value); + return out; + } else { + Simd out; + out.value = hn::Neg(a.value); + return out; + } +} + +#define MLX_HIGHWAY_BITWISE(name, hwy_op) \ + template = 0> \ + inline Simd name(Simd a, Simd b) { \ + Simd out; \ + out.value = hn::hwy_op(a.value, b.value); \ + return out; \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(Simd a, U b) { \ + return name(a, Simd(b)); \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(U a, Simd b) { \ + return name(Simd(a), b); \ + } + +MLX_HIGHWAY_BITWISE(operator&, And) +MLX_HIGHWAY_BITWISE(operator|, Or) +MLX_HIGHWAY_BITWISE(operator^, Xor) +#undef MLX_HIGHWAY_BITWISE + +template = 0> +inline Simd operator~(Simd a) { + Simd out; + out.value = hn::Not(a.value); + return out; +} + +template = 0> +inline Simd operator<<(Simd a, int bits) { + Simd out; + out.value = hn::ShiftLeftSame(a.value, bits); + return out; +} + +template = 0> +inline Simd operator>>(Simd a, int bits) { + Simd out; + out.value = hn::ShiftRightSame(a.value, bits); + return out; +} + +template = 0> +inline Simd operator<<(Simd a, Simd b) { + Simd out; + out.value = a.value << b.value; + return out; +} + +template = 0> +inline Simd operator>>(Simd a, Simd b) { + Simd out; + out.value = a.value >> b.value; + return out; +} + +template = 0> +inline Simd operator!(Simd a) { + if constexpr (highway_detail::is_half_v) { + return !Simd(a); + } else { + const typename Simd::D d; + return Simd::from_mask(d, hn::Eq(a.value, hn::Zero(d))); + } +} + +#define MLX_HIGHWAY_COMPARE(name, hwy_op) \ + template = 0> \ + inline Simd name(Simd a, Simd b) { \ + if constexpr (highway_detail::is_half_v) { \ + return name(Simd(a), Simd(b)); \ + } else { \ + const typename Simd::D d; \ + return Simd::from_mask(d, hn::hwy_op(a.value, b.value)); \ + } \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(Simd a, U b) { \ + return name(a, Simd(b)); \ + } \ + template < \ + typename T, \ + int N, \ + typename U, \ + highway_detail::EnableIfVector = 0> \ + inline Simd name(U a, Simd b) { \ + return name(Simd(a), b); \ + } + +MLX_HIGHWAY_COMPARE(operator==, Eq) +MLX_HIGHWAY_COMPARE(operator!=, Ne) +MLX_HIGHWAY_COMPARE(operator<, Lt) +MLX_HIGHWAY_COMPARE(operator>, Gt) +MLX_HIGHWAY_COMPARE(operator<=, Le) +MLX_HIGHWAY_COMPARE(operator>=, Ge) +#undef MLX_HIGHWAY_COMPARE + +template = 0> +inline Simd operator&&(Simd a, Simd b) { + return Simd((a != Simd(0)) && (b != Simd(0))); +} + +template = 0> +inline Simd operator||(Simd a, Simd b) { + return Simd((a != Simd(0)) || (b != Simd(0))); +} + +template = 0> +inline Simd select(Simd mask, Simd x, Simd y) { + const typename Simd::D d; + Simd out; + out.value = hn::IfThenElse(mask.to_mask(d), x.value, y.value); + return out; +} + +template = 0> +inline Simd abs(Simd a) { + if constexpr (std::is_unsigned_v) { + return a; + } else if constexpr (highway_detail::is_half_v) { + return Simd(abs(Simd(a))); + } else { + Simd out; + out.value = hn::Abs(a.value); + return out; + } +} + +template = 0> +inline Simd isnan(Simd a) { + if constexpr (std::is_floating_point_v) { + const typename Simd::D d; + return Simd::from_mask(d, hn::IsNaN(a.value)); + } else if constexpr (highway_detail::is_half_v) { + return isnan(Simd(a)); + } else { + return Simd(false); + } +} + +template = 0> +inline Simd sqrt(Simd a) { + if constexpr (highway_detail::is_half_v) { + return Simd(sqrt(Simd(a))); + } else { + Simd out; + out.value = hn::Sqrt(a.value); + return out; + } +} + +// At SSE2 and SSSE3, Highway's Floor, Ceil and Round can return +0 where C +// returns -0. A result rounded to an integer has its input's sign: copy it. +template = 0> +inline Simd floor(Simd a) { + if constexpr (highway_detail::is_half_v) { + return Simd(floor(Simd(a))); + } else if constexpr (std::is_floating_point_v) { + Simd out; + out.value = hn::CopySign(hn::Floor(a.value), a.value); + return out; + } else { + return a; + } +} + +template = 0> +inline Simd ceil(Simd a) { + if constexpr (highway_detail::is_half_v) { + return Simd(ceil(Simd(a))); + } else if constexpr (std::is_floating_point_v) { + Simd out; + out.value = hn::CopySign(hn::Ceil(a.value), a.value); + return out; + } else { + return a; + } +} + +template = 0> +inline Simd rint(Simd a) { + if constexpr (highway_detail::is_half_v) { + return Simd(rint(Simd(a))); + } else if constexpr (std::is_floating_point_v) { + Simd out; + out.value = hn::CopySign(hn::Round(a.value), a.value); + return out; + } else { + return a; + } +} + +template = 0> +inline Simd recip(Simd a) { + return Simd(1) / a; +} + +template = 0> +inline Simd rsqrt(Simd a) { + return Simd(1) / sqrt(a); +} + +template = 0> +inline Simd maximum(Simd a, Simd b) { + if constexpr (highway_detail::is_half_v) { + return Simd(maximum(Simd(a), Simd(b))); + } else { + Simd out; + out.value = hn::Max(a.value, b.value); + if constexpr (std::is_floating_point_v) { + out = select(isnan(b), b, select(isnan(a), a, out)); + } + return out; + } +} + +template = 0> +inline Simd minimum(Simd a, Simd b) { + if constexpr (highway_detail::is_half_v) { + return Simd(minimum(Simd(a), Simd(b))); + } else { + Simd out; + out.value = hn::Min(a.value, b.value); + if constexpr (std::is_floating_point_v) { + out = select(isnan(b), b, select(isnan(a), a, out)); + } + return out; + } +} + +template = 0> +inline Simd clamp(Simd v, Simd min_v, Simd max_v) { + return minimum(maximum(v, min_v), max_v); +} + +template = 0> +inline Simd fma(Simd x, Simd y, U z) { + if constexpr (highway_detail::is_half_v) { + return Simd( + fma(Simd(x), Simd(y), Simd(z))); + } else { +#if HWY_NATIVE_FMA + Simd out; + out.value = hn::MulAdd(x.value, y.value, Simd(z).value); + return out; +#else + if constexpr (std::is_floating_point_v) { + // Without FMA instructions MulAdd rounds twice. std::fma rounds once, as + // base_simd.h does, and MLX's polynomials rely on that. + alignas(64) T xs[N]; + alignas(64) T ys[N]; + alignas(64) T zs[N]; + x.store(xs); + y.store(ys); + Simd(z).store(zs); + for (int i = 0; i < N; ++i) { + xs[i] = std::fma(xs[i], ys[i], zs[i]); + } + return Simd::load(xs); + } else { + Simd out; + out.value = hn::MulAdd(x.value, y.value, Simd(z).value); + return out; + } +#endif + } +} + +template = 0> +inline Simd remainder(Simd a, Simd b) { + if constexpr (std::is_integral_v) { + return highway_detail::map_integer_binary(a, b, [](T x, T y) { + return remainder(Simd(x), Simd(y)).value; + }); + } else { + return highway_detail::map_binary(a, b, [](auto x, auto y) { + auto r = std::fmod(x, y); + if (r != 0 && (std::signbit(r) != std::signbit(y))) { + r += y; + } + return r; + }); + } +} + +template = 0> +inline Simd pow(Simd base, Simd exp) { + if constexpr (std::is_integral_v) { + return highway_detail::map_integer_binary(base, exp, [](T x, T y) { + return pow(Simd(x), Simd(y)).value; + }); + } else { + return highway_detail::map_binary( + base, exp, [](auto x, auto y) { return std::pow(x, y); }); + } +} + +template = 0> +inline Simd atan2(Simd a, Simd b) { + return highway_detail::map_binary( + a, b, [](auto x, auto y) { return std::atan2(x, y); }); +} + +template = 0> +inline Simd clz(Simd x) { + Simd out; + out.value = hn::LeadingZeroCount(x.value); + return out; +} + +template = 0> +inline T sum(Simd x) { + if constexpr (highway_detail::is_half_v) { + return static_cast(sum(Simd(x))); + } else { + return hn::ReduceSum(typename Simd::D(), x.value); + } +} + +template = 0> +inline T max(Simd x) { + if constexpr (highway_detail::is_half_v) { + return static_cast(max(Simd(x))); + } else { + return hn::ReduceMax(typename Simd::D(), x.value); + } +} + +template = 0> +inline T min(Simd x) { + if constexpr (highway_detail::is_half_v) { + return static_cast(min(Simd(x))); + } else { + return hn::ReduceMin(typename Simd::D(), x.value); + } +} + +template = 0> +inline T prod(Simd x) { + alignas(64) T tmp[N]; + x.store(tmp); + T result = 1; + for (int i = 0; i < N; ++i) { + result = static_cast(result * tmp[i]); + } + return result; +} + +template = 0> +inline bool any(Simd x) { + for (int i = 0; i < static_cast(sizeof(x.bits)); ++i) { + if (x.bits[i] != 0) { + return true; + } + } + return false; +} + +template = 0> +inline bool all(Simd x) { + for (int i = 0; i < N; ++i) { + if (!x[i]) { + return false; + } + } + return true; +} + +template = 0> +inline bool any(Simd x) { + return any(!(!x)); +} + +template = 0> +inline bool all(Simd x) { + return all(!(!x)); +} + +#define MLX_HIGHWAY_TRANSCENDENTAL(name, std_name) \ + template = 0> \ + inline Simd name(Simd x) { \ + return highway_detail::map_unary( \ + x, [](auto v) { return std::std_name(v); }); \ + } + +MLX_HIGHWAY_TRANSCENDENTAL(acos, acos) +MLX_HIGHWAY_TRANSCENDENTAL(acosh, acosh) +MLX_HIGHWAY_TRANSCENDENTAL(asin, asin) +MLX_HIGHWAY_TRANSCENDENTAL(asinh, asinh) +MLX_HIGHWAY_TRANSCENDENTAL(atan, atan) +MLX_HIGHWAY_TRANSCENDENTAL(atanh, atanh) +MLX_HIGHWAY_TRANSCENDENTAL(cosh, cosh) +MLX_HIGHWAY_TRANSCENDENTAL(expm1, expm1) +MLX_HIGHWAY_TRANSCENDENTAL(log, log) +MLX_HIGHWAY_TRANSCENDENTAL(log1p, log1p) +MLX_HIGHWAY_TRANSCENDENTAL(log2, log2) +MLX_HIGHWAY_TRANSCENDENTAL(log10, log10) +MLX_HIGHWAY_TRANSCENDENTAL(sinh, sinh) +MLX_HIGHWAY_TRANSCENDENTAL(tan, tan) +MLX_HIGHWAY_TRANSCENDENTAL(tanh, tanh) +#undef MLX_HIGHWAY_TRANSCENDENTAL + +// Conversion of a value that is known to fit in To, without a range test. +// The vector form of convert_in_range in base_simd.h. +template < + typename To, + typename T, + int N, + highway_detail::EnableIfVector = 0> +inline Simd convert_in_range(Simd v) { + return Simd(v); +} + +} // namespace mlx::core::simd +HWY_AFTER_NAMESPACE(); diff --git a/mlx/backend/cpu/simd/math.h b/mlx/backend/cpu/simd/math.h index dd8e2f0260..cf49bf0b45 100644 --- a/mlx/backend/cpu/simd/math.h +++ b/mlx/backend/cpu/simd/math.h @@ -3,6 +3,10 @@ #pragma once #include "mlx/backend/cpu/simd/type.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/types/complex.h" +#include "mlx/types/half_types.h" +#endif // MLX_USE_HIGHWAY_KERNELS namespace mlx::core::simd { @@ -184,23 +188,80 @@ Simd erf(Simd x) { return out; } // https://github.com/pytorch/pytorch/blob/abf28982a8cb43342e7669d859de9543fd804cc9/aten/src/ATen/cpu/vec/vec256/vec256_float.h#L175 +#if !defined(MLX_USE_HIGHWAY_KERNELS) Simd v = x; auto t = recip(fma(Simd(0.3275911f), abs(v), 1.0f)); auto r = fma(Simd(1.061405429f), t, -1.453152027f); r = fma(r, t, 1.421413741f); r = fma(r, t, -0.284496736f); r = fma(r, t, 0.254829592f); +#else + // Use explicit ComputeT so half-type Simd (float16/bfloat16) promotes to + // float32 and bare float literals don't cause template deduction ambiguity + // in fma(). For float/double T, ComputeT == T so behavior is unchanged. + using ComputeT = std::conditional_t< + std::is_same_v || std::is_same_v, + float, + T>; + Simd v = x; + auto t = recip( + fma(Simd(ComputeT(0.3275911f)), abs(v), ComputeT(1.0f))); + auto r = fma( + Simd(ComputeT(1.061405429f)), t, ComputeT(-1.453152027f)); + r = fma(r, t, ComputeT(1.421413741f)); + r = fma(r, t, ComputeT(-0.284496736f)); + r = fma(r, t, ComputeT(0.254829592f)); +#endif // MLX_USE_HIGHWAY_KERNELS auto e = -exp(-v * v); +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto result = Simd(fma(e * t, r, 1.0f)); return select(x > 0, result, -result); +#else + auto result = Simd(fma(e * t, r, ComputeT(1.0f))); + return select(x > ComputeT(0), result, -result); +#endif // MLX_USE_HIGHWAY_KERNELS } template +#if defined(MLX_USE_HIGHWAY_KERNELS) +Simd sigmoid(Simd x) { + // For float16/bfloat16 inputs, compute in float32 precision for accuracy + // For float32/float64, compute in the same precision + using ComputeT = std::conditional_t< + std::is_same_v || std::is_same_v, + float, + T>; + Simd in = x; + auto y = recip(ComputeT(1.0f) + exp(abs(in))); + return Simd(select(in < Simd{0}, y, ComputeT(1.0f) - y)); +} + +// Complex sigmoid: 1 / (1 + exp(-z)) +template +Simd sigmoid(Simd x) { + return Simd(recip(Simd(1.0f) + exp(-x))); +} + +template +#endif // MLX_USE_HIGHWAY_KERNELS Simd erfinv(Simd a_) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) Simd a = a_; auto t = fma(a, 0.0f - a, 1.0f); +#else + // Use explicit ComputeT so half-type Simd (float16/bfloat16) promotes to + // float32 and bare float literals don't cause template deduction ambiguity + // in fma(). For float/double T, ComputeT == T so behavior is unchanged. + using ComputeT = std::conditional_t< + std::is_same_v || std::is_same_v, + float, + T>; + Simd a = a_; + auto t = fma(a, ComputeT(0.0f) - a, ComputeT(1.0f)); +#endif // MLX_USE_HIGHWAY_KERNELS t = log(t); auto lhs = [](auto t) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) Simd p; p = 3.03697567e-10f; // 0x1.4deb44p-32 p = fma(p, t, 2.93243101e-8f); // 0x1.f7c9aep-26 @@ -211,8 +272,21 @@ Simd erfinv(Simd a_) { p = fma(p, t, 4.83185798e-3f); // 0x1.3ca920p-8 p = fma(p, t, -2.64646143e-1f); // -0x1.0eff66p-2 return fma(p, t, 8.40016484e-1f); // 0x1.ae16a4p-1 +#else + Simd p; + p = ComputeT(3.03697567e-10f); // 0x1.4deb44p-32 + p = fma(p, t, ComputeT(2.93243101e-8f)); // 0x1.f7c9aep-26 + p = fma(p, t, ComputeT(1.22150334e-6f)); // 0x1.47e512p-20 + p = fma(p, t, ComputeT(2.84108955e-5f)); // 0x1.dca7dep-16 + p = fma(p, t, ComputeT(3.93552968e-4f)); // 0x1.9cab92p-12 + p = fma(p, t, ComputeT(3.02698812e-3f)); // 0x1.8cc0dep-9 + p = fma(p, t, ComputeT(4.83185798e-3f)); // 0x1.3ca920p-8 + p = fma(p, t, ComputeT(-2.64646143e-1f)); // -0x1.0eff66p-2 + return fma(p, t, ComputeT(8.40016484e-1f)); // 0x1.ae16a4p-1 +#endif // MLX_USE_HIGHWAY_KERNELS }; auto rhs = [](auto t) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) Simd p; p = 5.43877832e-9f; // 0x1.75c000p-28 p = fma(p, t, 1.43285448e-7f); // 0x1.33b402p-23 @@ -224,17 +298,46 @@ Simd erfinv(Simd a_) { p = fma(p, t, 1.15392581e-2f); // 0x1.7a1e50p-7 p = fma(p, t, -2.32015476e-1f); // -0x1.db2aeep-3 return fma(p, t, 8.86226892e-1f); // 0x1.c5bf88p-1 +#else + Simd p; + p = ComputeT(5.43877832e-9f); // 0x1.75c000p-28 + p = fma(p, t, ComputeT(1.43285448e-7f)); // 0x1.33b402p-23 + p = fma(p, t, ComputeT(1.22774793e-6f)); // 0x1.499232p-20 + p = fma(p, t, ComputeT(1.12963626e-7f)); // 0x1.e52cd2p-24 + p = fma(p, t, ComputeT(-5.61530760e-5f)); // -0x1.d70bd0p-15 + p = fma(p, t, ComputeT(-1.47697632e-4f)); // -0x1.35be90p-13 + p = fma(p, t, ComputeT(2.31468678e-3f)); // 0x1.2f6400p-9 + p = fma(p, t, ComputeT(1.15392581e-2f)); // 0x1.7a1e50p-7 + p = fma(p, t, ComputeT(-2.32015476e-1f)); // -0x1.db2aeep-3 + return fma(p, t, ComputeT(8.86226892e-1f)); // 0x1.c5bf88p-1 +#endif // MLX_USE_HIGHWAY_KERNELS }; +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto thresh = 6.125f; +#else + auto thresh = ComputeT(6.125f); +#endif // MLX_USE_HIGHWAY_KERNELS // Compute both branches and select if N > 1 if constexpr (N == 1) { if ((abs(t) > thresh).value) { // maximum ulp error = 2.35793 +#if !defined(MLX_USE_HIGHWAY_KERNELS) return a * lhs(t); +#else + return Simd(a * lhs(t)); +#endif // MLX_USE_HIGHWAY_KERNELS } else { // maximum ulp error = 2.35002 +#if !defined(MLX_USE_HIGHWAY_KERNELS) return a * rhs(t); +#else + return Simd(a * rhs(t)); +#endif // MLX_USE_HIGHWAY_KERNELS } } else { +#if !defined(MLX_USE_HIGHWAY_KERNELS) return a * select(abs(t) > thresh, lhs(t), rhs(t)); +#else + return Simd(a * select(abs(t) > thresh, lhs(t), rhs(t))); +#endif // MLX_USE_HIGHWAY_KERNELS } } diff --git a/mlx/backend/cpu/simd/type.h b/mlx/backend/cpu/simd/type.h index 59b6ecca30..032508be24 100644 --- a/mlx/backend/cpu/simd/type.h +++ b/mlx/backend/cpu/simd/type.h @@ -2,6 +2,12 @@ #include "mlx/backend/cpu/simd/base_simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#if defined(MLX_USE_HIGHWAY_KERNELS) || defined(MLX_USE_HIGHWAY_JIT_SIMD) +#include "mlx/backend/cpu/simd/highway_simd.h" +#endif + +#endif // MLX_USE_HIGHWAY_KERNELS #ifdef MLX_USE_ACCELERATE #if defined(__x86_64__) // the accelerate_simd implementation require neon -- use base implementation diff --git a/mlx/backend/cpu/softmax.cpp b/mlx/backend/cpu/softmax.cpp index cbd6277de6..eac4054e0a 100644 --- a/mlx/backend/cpu/softmax.cpp +++ b/mlx/backend/cpu/softmax.cpp @@ -6,6 +6,9 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/dtype_utils.h" #include "mlx/primitives.h" #include "mlx/types/limits.h" @@ -19,7 +22,104 @@ using namespace mlx::core::simd; // Rows up to this length are summed as one block, so they keep their results. constexpr int sum_block = 4096; +#if defined(MLX_USE_HIGHWAY_KERNELS) +// Process a single row of softmax +#endif // MLX_USE_HIGHWAY_KERNELS template +#if defined(MLX_USE_HIGHWAY_KERNELS) +void softmax_row(const T* in_ptr, T* out_ptr, int M) { + constexpr bool same_t = std::is_same_v; + constexpr int N = std::min(max_size, max_size); + + const T* current_in_ptr; + T* current_out_ptr; + + // Find the maximum + current_in_ptr = in_ptr; + Simd vmaximum(-numeric_limits::infinity()); + size_t s = M; + while (s >= N) { + Simd vals = load(current_in_ptr); + vmaximum = maximum(vals, vmaximum); + current_in_ptr += N; + s -= N; + } + + AccT maximum = max(vmaximum); + while (s-- > 0) { + maximum = std::max(maximum, static_cast(*current_in_ptr)); + current_in_ptr++; + } + + // Compute the normalizer and the exponentials. A row longer than sum_block + // sums each block on its own, then adds the block sums. + current_out_ptr = out_ptr; + current_in_ptr = in_ptr; + auto block_normalizer = [&](size_t n) { + Simd vnormalizer(0.0); + while (n >= N) { + Simd vexp = load(current_in_ptr); + vexp = exp(vexp - maximum); + if constexpr (same_t) { + store(current_out_ptr, vexp); + } + vnormalizer = vnormalizer + vexp; + current_in_ptr += N; + current_out_ptr += N; + n -= N; + } + AccT block_sum = sum(vnormalizer); + while (n-- > 0) { + AccT _exp = std::exp(*current_in_ptr - maximum); + if constexpr (same_t) { + *current_out_ptr = _exp; + } + block_sum += _exp; + current_in_ptr++; + current_out_ptr++; + } + return block_sum; + }; + size_t block = std::min(M, sum_block); + AccT normalizer = block_normalizer(block); + for (s = M - block; s > 0; s -= block) { + block = std::min(s, sum_block); + normalizer += block_normalizer(block); + } + normalizer = 1 / normalizer; + + // Normalize + current_out_ptr = out_ptr; + current_in_ptr = in_ptr; + s = M; + while (s >= N) { + if constexpr (same_t) { + store( + current_out_ptr, + Simd(load(current_out_ptr) * normalizer)); + } else { + Simd vexp = load(current_in_ptr); + vexp = exp(vexp - maximum) * normalizer; + store(current_out_ptr, Simd(vexp)); + current_in_ptr += N; + } + current_out_ptr += N; + s -= N; + } + while (s-- > 0) { + if constexpr (same_t) { + *current_out_ptr *= normalizer; + } else { + AccT _exp = std::exp(*current_in_ptr - maximum); + *current_out_ptr = static_cast(_exp * normalizer); + current_in_ptr++; + } + current_out_ptr++; + } +} + +template +#endif // MLX_USE_HIGHWAY_KERNELS void softmax(const array& in, array& out, Stream stream) { auto& encoder = cpu::get_command_encoder(stream); encoder.set_input_array(in); @@ -31,13 +131,36 @@ void softmax(const array& in, array& out, Stream stream) { int M = in.shape().back(); int L = in.data_size() / M; +#if !defined(MLX_USE_HIGHWAY_KERNELS) encoder.dispatch([in_ptr, out_ptr, M, L]() mutable { constexpr bool same_t = std::is_same_v; constexpr int N = std::min(max_size, max_size); +#else + // Parallelize over rows, limited by number of rows + auto& pool = cpu::ThreadPool::instance(); + // Only parallelize if we have enough rows and elements + // Each row needs enough work (M elements) to justify threading overhead + int nth = std::min(pool.max_threads(), L); + size_t total_elements = static_cast(L) * M; + if (total_elements < cpu::MIN_TOTAL_ELEMENTS) { + nth = 1; + } +#endif // MLX_USE_HIGHWAY_KERNELS +#if !defined(MLX_USE_HIGHWAY_KERNELS) const T* current_in_ptr; T* current_out_ptr; +#else + if (nth > 1) { + encoder.dispatch([in_ptr, out_ptr, M, L, nth, &pool]() { + pool.parallel_for(nth, [=](int tid, int num_threads) { + // Divide rows among threads + int rows_per_thread = (L + num_threads - 1) / num_threads; + int row_start = rows_per_thread * tid; + int row_end = std::min(row_start + rows_per_thread, L); +#endif // MLX_USE_HIGHWAY_KERNELS +#if !defined(MLX_USE_HIGHWAY_KERNELS) for (int i = 0; i < L; i++, in_ptr += M, out_ptr += M) { // Find the maximum current_in_ptr = in_ptr; @@ -49,7 +172,12 @@ void softmax(const array& in, array& out, Stream stream) { current_in_ptr += N; s -= N; } +#else + const T* row_in = in_ptr + row_start * M; + T* row_out = out_ptr + row_start * M; +#endif // MLX_USE_HIGHWAY_KERNELS +#if !defined(MLX_USE_HIGHWAY_KERNELS) AccT maximum = max(vmaximum); while (s-- > 0) { maximum = std::max(maximum, static_cast(*current_in_ptr)); @@ -152,6 +280,22 @@ void softmax(const array& in, array& out, Stream stream) { } } }); +#else + for (int i = row_start; i < row_end; i++) { + softmax_row(row_in, row_out, M); + row_in += M; + row_out += M; + } + }); + }); + } else { + encoder.dispatch([in_ptr, out_ptr, M, L]() mutable { + for (int i = 0; i < L; i++, in_ptr += M, out_ptr += M) { + softmax_row(in_ptr, out_ptr, M); + } + }); + } +#endif // MLX_USE_HIGHWAY_KERNELS } } // namespace diff --git a/mlx/backend/cpu/threading/CMakeLists.txt b/mlx/backend/cpu/threading/CMakeLists.txt new file mode 100644 index 0000000000..e7086c6995 --- /dev/null +++ b/mlx/backend/cpu/threading/CMakeLists.txt @@ -0,0 +1,7 @@ +# The CPU thread pool, used only by builds with Highway kernels. The parent adds +# this directory inside its MLX_USE_HIGHWAY block. +target_sources( + mlx + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/common.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/config.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/openblas/thread_pool.cpp) diff --git a/mlx/backend/cpu/threading/base.h b/mlx/backend/cpu/threading/base.h new file mode 100644 index 0000000000..8272ff7315 --- /dev/null +++ b/mlx/backend/cpu/threading/base.h @@ -0,0 +1,44 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include + +namespace mlx::core::cpu { + +/** + * Pure virtual interface for the thread pool implementation: persistent + * threading with optional OpenBLAS coordination (openblas/thread_pool.cpp). + */ +class ThreadPoolBackend { + public: + virtual ~ThreadPoolBackend() = default; + + /** + * Execute a function in parallel across n_threads. + * + * @param n_threads Number of threads to use (1 to max_threads()) + * @param f Function to execute, called as f(thread_id, n_threads) + * where thread_id is in [0, n_threads) and n_threads is the + * total number of threads participating. + * + * Blocks until all threads complete their work. + */ + virtual void parallel_for( + int n_threads, + std::function f) = 0; + + /** + * Get the maximum number of threads available. + */ + virtual int max_threads() const = 0; +}; + +/** + * Factory function to create the thread pool backend, implemented in + * openblas/thread_pool.cpp. + */ +std::unique_ptr create_thread_pool_backend(); + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/common.cpp b/mlx/backend/cpu/threading/common.cpp new file mode 100644 index 0000000000..2fac3df5e6 --- /dev/null +++ b/mlx/backend/cpu/threading/common.cpp @@ -0,0 +1,32 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/threading/common.h" + +namespace mlx::core::cpu { + +ThreadPool& ThreadPool::instance() { + // Leak on all platforms - see Scheduler singleton comment in scheduler.cpp. + static ThreadPool* pool = new ThreadPool; + return *pool; +} + +ThreadPool::ThreadPool() : backend_(create_thread_pool_backend()) {} + +void ThreadPool::parallel_for( + int n_threads, + std::function f) { + if (n_threads <= 0) { + return; + } + backend_->parallel_for(n_threads, std::move(f)); +} + +ThreadPool::~ThreadPool() = default; + +int ThreadPool::max_threads() const { + return backend_->max_threads(); +} + +} // namespace mlx::core::cpu +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/threading/common.h b/mlx/backend/cpu/threading/common.h new file mode 100644 index 0000000000..8d7e23581c --- /dev/null +++ b/mlx/backend/cpu/threading/common.h @@ -0,0 +1,90 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/api.h" +#include "mlx/backend/cpu/threading/base.h" + +#include +#include + +namespace mlx::core::cpu { + +/** + * Thread pool for CPU backend parallelism. + * + * Provides a simple interface for parallel execution of work across multiple + * threads: persistent threading with optional OpenBLAS coordination, in builds + * with Highway kernels. + * + * Usage: + * auto& pool = ThreadPool::instance(); + * int nth = std::min(pool.max_threads(), (int)(size / 4096)); + * if (nth > 1) { + * pool.parallel_for(nth, [&](int tid, int nth) { + * size_t chunk = (size + nth - 1) / nth; + * size_t start = chunk * tid; + * size_t end = std::min(start + chunk, size); + * process_chunk(start, end); + * }); + * } else { + * process_chunk(0, size); + * } + */ +class MLX_API ThreadPool { + public: + /// Get the singleton instance. + static ThreadPool& instance(); + + /// Get the maximum number of threads available. + int max_threads() const; + + /** + * Execute a function in parallel across n_threads. + * + * @param n_threads Number of threads to use (1 to max_threads()) + * @param f Function to execute, called as f(thread_id, n_threads) + * where thread_id is in [0, n_threads) and n_threads is the + * total number of threads participating. + * + * Blocks until all threads complete their work. + */ + void parallel_for(int n_threads, std::function f); + + ~ThreadPool(); + + // Non-copyable + ThreadPool(const ThreadPool&) = delete; + ThreadPool& operator=(const ThreadPool&) = delete; + + private: + ThreadPool(); + + std::unique_ptr backend_; +}; + +// Minimum total elements before considering parallelization. +// Below this threshold, threading overhead exceeds benefits. +constexpr size_t MIN_TOTAL_ELEMENTS = 262144; // 256K elements + +// Minimum elements per thread to avoid too many threads +constexpr size_t MIN_ELEMENTS_PER_THREAD = 32768; // 32K elements + +/** + * Helper to compute effective thread count for a given workload size. + * + * @param size Total number of elements to process + * @param max_threads Maximum threads to use (typically pool.max_threads()) + * @return Number of threads to use (1 if size is too small) + */ +inline int effective_threads(size_t size, int max_threads) { + // Don't parallelize small workloads + if (size < MIN_TOTAL_ELEMENTS) { + return 1; + } + // Compute threads based on per-thread minimum + int n = static_cast(size / MIN_ELEMENTS_PER_THREAD); + return std::min(std::max(1, n), max_threads); +} + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/config.cpp b/mlx/backend/cpu/threading/config.cpp new file mode 100644 index 0000000000..46f62dfb18 --- /dev/null +++ b/mlx/backend/cpu/threading/config.cpp @@ -0,0 +1,223 @@ +// Copyright © 2026 Apple Inc. +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/threading/config.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +// #3019's Windows core count: physical cores, since SMT siblings share the +// SIMD units, caches and memory bandwidth. +#if defined(_WIN32) +#include +static int get_physical_cores() { + DWORD len = 0; + GetLogicalProcessorInformation(nullptr, &len); + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) + return 0; + std::vector buf( + len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)); + if (!GetLogicalProcessorInformation(buf.data(), &len)) + return 0; + int cores = 0; + for (auto& info : buf) { + if (info.Relationship == RelationProcessorCore) + cores++; + } + return cores; +} +#endif + +namespace mlx::core::cpu { + +namespace detail { + +std::optional parse_thread_count(const char* value, std::string& error) { + if (value == nullptr) { + return std::nullopt; + } + const std::string text(value); + char* end = nullptr; + errno = 0; + const long n = std::strtol(text.c_str(), &end, 10); + if (text.empty() || *end != '\0' || errno != 0 || n <= 0 || n > 4096) { + error = "MLX_CPU_THREADS must be a positive integer up to 4096, got \"" + + text + "\""; + return std::nullopt; + } + return static_cast(n); +} + +std::optional parse_cpu_max(std::string_view contents) { + std::istringstream in{std::string(contents)}; + std::string quota; + long long period = 0; + if (!(in >> quota >> period) || period <= 0 || quota == "max") { + return std::nullopt; + } + char* end = nullptr; + const long long q = std::strtoll(quota.c_str(), &end, 10); + if (*end != '\0' || q <= 0) { + return std::nullopt; + } + return static_cast(std::max(1, q / period)); +} + +int count_physical_cores( + const std::vector& cpus, + const Topology& topology) { + std::set> cores; + int unknown = 0; + for (int cpu : cpus) { + if (auto t = topology(cpu)) { + cores.insert(*t); + } else { + ++unknown; + } + } + return static_cast(cores.size()) + unknown; +} + +std::optional> sysfs_topology( + const std::string& root, + int cpu) { + // core_id is not unique within a package on every kernel: key a core by + // the first CPU of its list. + const std::string base = root + "/cpu" + std::to_string(cpu) + "/topology/"; + for (const char* list : {"core_cpus_list", "thread_siblings_list"}) { + std::ifstream in(base + list); + int first = 0; + if (in >> first) { + int package = 0; + std::ifstream package_file(base + "physical_package_id"); + package_file >> package; + return std::make_pair(package, first); + } + } + return std::nullopt; +} + +std::optional cgroup_cpu_limit( + const std::string& root, + std::string_view self_cgroup) { + std::string path; + std::istringstream lines{std::string(self_cgroup)}; + for (std::string line; std::getline(lines, line);) { + if (line.rfind("0::", 0) == 0) { + path = line.substr(3); + break; + } + } + if (path.empty() || path[0] != '/') { + return std::nullopt; // the walk below needs an absolute path to end + } + std::optional limit; + std::string dir = root + (path == "/" ? std::string() : path); + while (true) { + std::ifstream max_file(dir + "/cpu.max"); + std::string contents; + if (max_file && std::getline(max_file, contents)) { + if (auto n = parse_cpu_max(contents)) { + limit = limit ? std::min(*limit, *n) : *n; + } + } + if (dir.size() <= root.size()) { + break; + } + dir = dir.substr(0, dir.find_last_of('/')); + } + return limit; +} + +ThreadConfig resolve_thread_config( + const char* override_value, + const std::vector& allowed_cpus, + const Topology& topology, + std::optional cgroup_limit) { + ThreadConfig config{1, "physical cores", {}}; + if (auto n = parse_thread_count(override_value, config.error)) { + config.threads = *n; + config.reason = "MLX_CPU_THREADS"; + return config; + } + config.threads = std::max(1, count_physical_cores(allowed_cpus, topology)); + if (cgroup_limit && *cgroup_limit < config.threads) { + config.threads = *cgroup_limit; + config.reason = "cgroup cpu.max"; + } + return config; +} + +} // namespace detail + +namespace { + +std::vector allowed_cpus() { + std::vector cpus; +#if defined(__linux__) + cpu_set_t set; + CPU_ZERO(&set); + if (sched_getaffinity(0, sizeof(set), &set) == 0) { + for (int i = 0; i < CPU_SETSIZE; ++i) { + if (CPU_ISSET(i, &set)) { + cpus.push_back(i); + } + } + } +#endif + if (cpus.empty()) { + const int n = std::max(1u, std::thread::hardware_concurrency()); + for (int i = 0; i < n; ++i) { + cpus.push_back(i); + } + } + return cpus; +} + +std::string read_file(const char* path) { + std::ifstream in(path); + std::ostringstream text; + text << in.rdbuf(); + return text.str(); +} + +} // namespace + +const ThreadConfig& thread_config() { + static const ThreadConfig config = [] { + ThreadConfig resolved = detail::resolve_thread_config( + std::getenv("MLX_CPU_THREADS"), + allowed_cpus(), + [](int cpu) { + return detail::sysfs_topology("/sys/devices/system/cpu", cpu); + }, + detail::cgroup_cpu_limit( + "/sys/fs/cgroup", read_file("/proc/self/cgroup"))); +#if defined(_WIN32) + // No sysfs topology on Windows: count its cores as #3019 did. + if (std::string_view(resolved.reason) == "physical cores") { + if (const int cores = get_physical_cores(); cores > 0) { + resolved.threads = cores; + } + } +#endif + return resolved; + }(); + return config; +} + +} // namespace mlx::core::cpu + +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/threading/config.h b/mlx/backend/cpu/threading/config.h new file mode 100644 index 0000000000..406c5e4188 --- /dev/null +++ b/mlx/backend/cpu/threading/config.h @@ -0,0 +1,82 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/api.h" +#include "mlx/backend/cpu/threading/base.h" + +namespace mlx::core::cpu { + +// How many threads the CPU pool runs, and why. +struct ThreadConfig { + int threads; + // "MLX_CPU_THREADS", "cgroup cpu.max" or "physical cores". + const char* reason; + // Set when MLX_CPU_THREADS is not a positive integer: the pool then uses its + // default, and keeps the message here for a caller to report. + std::string error; +}; + +// The pool's configuration, resolved once per process. +MLX_API const ThreadConfig& thread_config(); + +// Whether OpenBLAS's thread setter was found, and whether the pool pinned +// OpenBLAS to one thread (it does at every pool size). +MLX_API bool openblas_present(); +MLX_API bool openblas_pinned(); + +namespace detail { +// A positive integer up to 4096, or nullopt; `error` is set for a value that is +// present but invalid, and left alone for nullptr. +MLX_API std::optional parse_thread_count( + const char* value, + std::string& error); +// cgroup v2 cpu.max, " " or "max ": floor(quota / +// period), at least 1. nullopt without a limit, or for text it cannot read. +MLX_API std::optional parse_cpu_max(std::string_view contents); +// Distinct topology keys among `cpus`. A CPU with no topology counts as a core +// of its own. +using Topology = std::function>(int cpu)>; +MLX_API int count_physical_cores( + const std::vector& cpus, + const Topology& topology); +// The topology key of `cpu`, read under `root`: its package and the first +// CPU of its core's CPU list. nullopt where neither list can be read. +MLX_API std::optional> sysfs_topology( + const std::string& root, + int cpu); +// The tightest cgroup v2 cpu.max from the "0::" line's cgroup up to `root`; +// nullopt without that line, for a relative path, or without a limit. +MLX_API std::optional cgroup_cpu_limit( + const std::string& root, + std::string_view self_cgroup); +// The override if valid; else the physical cores among `allowed_cpus`, capped +// by `cgroup_limit`. +MLX_API ThreadConfig resolve_thread_config( + const char* override_value, + const std::vector& allowed_cpus, + const Topology& topology, + std::optional cgroup_limit); + +// For tests: a pool of `threads` threads, the calling thread included. +MLX_API std::unique_ptr make_thread_pool(int threads); +// For tests: the points where a pool worker calls the test hook. +enum class PoolTestPoint { + AfterReady, // The worker has told the pool that it is ready. + BeforeClaim, // The worker has seen a free slot, and not yet claimed it. +}; +using PoolTestHook = void (*)(PoolTestPoint point, int worker); +// Process-wide. Null, the default, removes the hook. +MLX_API void set_pool_test_hook(PoolTestHook hook); +} // namespace detail + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp new file mode 100644 index 0000000000..8449760439 --- /dev/null +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -0,0 +1,364 @@ +// Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) + +#include "mlx/backend/cpu/threading/openblas/thread_pool.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/backend/cpu/threading/config.h" + +#include +#include + +// Spin-wait hint: reduces power consumption and avoids starving sibling +// hyperthreads during busy-wait loops. +#if defined(_MSC_VER) +#include +#if defined(_M_ARM64) || defined(_M_ARM) +#define MLX_SPIN_PAUSE() __yield() +#else +#define MLX_SPIN_PAUSE() _mm_pause() +#endif +#elif defined(__SSE2__) +#include +#define MLX_SPIN_PAUSE() _mm_pause() +#elif defined(__aarch64__) || defined(__arm__) +#define MLX_SPIN_PAUSE() __asm__ __volatile__("yield") +#else +#define MLX_SPIN_PAUSE() ((void)0) +#endif + +// OpenBLAS thread coordination -- pin BLAS to single-threaded at startup when +// OpenBLAS is the linked BLAS implementation. +#ifdef _WIN32 +#include +static void (*blas_set_threads)(int) = nullptr; +static void init_blas_funcs() { + static bool done = false; + if (done) + return; + done = true; + HMODULE h = GetModuleHandleA("libopenblas.dll"); + if (!h) + h = GetModuleHandleA("openblas.dll"); + if (h) { + blas_set_threads = + (void (*)(int))GetProcAddress(h, "openblas_set_num_threads"); + } +} +static void set_blas_threads(int n) { + init_blas_funcs(); + if (blas_set_threads) + blas_set_threads(n); +} +#elif defined(__unix__) || defined(__linux__) +#include +static void (*blas_set_threads)(int) = nullptr; +static void init_blas_funcs() { + static bool done = false; + if (done) + return; + done = true; + blas_set_threads = + (void (*)(int))dlsym(RTLD_DEFAULT, "openblas_set_num_threads"); +} +static void set_blas_threads(int n) { + init_blas_funcs(); + if (blas_set_threads) + blas_set_threads(n); +} +#else +static void (*blas_set_threads)(int) = nullptr; +static void init_blas_funcs() {} +static void set_blas_threads(int n) { + (void)n; +} +#endif + +static std::atomic& openblas_pinned_flag() { + static std::atomic flag{false}; + return flag; +} + +namespace mlx::core::cpu { + +namespace { +int get_default_threads() { + return thread_config().threads; +} + +// Set while this thread runs a slot of some parallel_for. +thread_local bool in_parallel_for = false; + +std::atomic test_hook{nullptr}; + +// Calls the test hook if a test set one. Otherwise costs one relaxed load. +inline void test_point(detail::PoolTestPoint point, int worker) { + if (auto hook = test_hook.load(std::memory_order_relaxed)) { + hook(point, worker); + } +} +} // namespace + +void CPUThreadPool::run_slot(int slot, int nth) { + in_parallel_for = true; + try { + (*task_ptr_)(slot, nth); + } catch (...) { + std::lock_guard lk(error_mtx_); + if (!first_error_) { + first_error_ = std::current_exception(); + } + } + in_parallel_for = false; +} + +CPUThreadPool::CPUThreadPool() : CPUThreadPool(get_default_threads()) {} + +CPUThreadPool::CPUThreadPool(int threads) + : max_threads_(std::clamp(threads, 1, MAX_WORKERS + 1)) { + // Spawn max_threads_ - 1 workers. The main thread takes slot 0 in + // parallel_for, so we only need (max_threads_ - 1) workers for the + // remaining slots. This saves one thread of spin overhead. + int n_workers = max_threads_ - 1; + workers_.reserve(n_workers); + for (int i = 0; i < n_workers; i++) { + workers_.emplace_back([this, i] { worker_loop(i); }); + } + // Wait for all workers to be initialized before allowing parallel_for. + // This prevents a race where a late-starting worker misses the first + // task notification and never sees the condition become true. + while (ready_.load(std::memory_order_acquire) < n_workers) { + MLX_SPIN_PAUSE(); + } + // Look OpenBLAS up at any pool size, so that openblas_present() can answer. + init_blas_funcs(); + // Pin OpenBLAS to one thread at every pool size, 1 included: cblas.cpp splits + // SGEMMs across the pool, and MLX_CPU_THREADS is the one setting. + set_blas_threads(1); + openblas_pinned_flag().store(blas_set_threads != nullptr); +} + +CPUThreadPool::~CPUThreadPool() { + { + std::lock_guard lk(mtx_); + stop_ = true; + } + // Update per-worker flags and gen_ to wake all workers. + uint64_t new_gen = gen_.fetch_add(1, std::memory_order_release) + 1; + int n_workers = static_cast(workers_.size()); + for (int i = 0; i < n_workers; i++) { + worker_slots_[i].wake_gen.store(new_gen, std::memory_order_release); + } + cv_.notify_all(); + for (auto& w : workers_) { + w.join(); + } +} + +// Workers spin briefly on their private cache-line flag before falling back +// to cv_.wait. The spin window covers the typical inter-parallel_for gap +// during token generation (~30-50us), keeping workers ready for immediate +// dispatch without OS wakeup latency (~10-50us for futex). +static constexpr int WORKER_SPIN_COUNT = 32768; // ~160us at ~5ns/iter + +void CPUThreadPool::claim_slot(int worker_id, uint64_t gen) { + uint64_t c = claim_.load(std::memory_order_acquire); + while ((c >> 32) == (gen & 0xffffffff)) { + int nth = static_cast((c >> 16) & 0xffff); + int slot = static_cast(c & 0xffff); + if (slot >= nth) { + return; + } + test_point(detail::PoolTestPoint::BeforeClaim, worker_id); + if (claim_.compare_exchange_weak( + c, c + 1, std::memory_order_acquire, std::memory_order_acquire)) { + run_slot(slot, nth); + done_.fetch_add(1, std::memory_order_acq_rel); + return; + } + } +} + +void CPUThreadPool::worker_loop(int worker_id) { + // Read gen_ before this worker is ready: a call can start just after that. + uint64_t my_gen = gen_.load(std::memory_order_acquire); + // Signal that this worker is ready and waiting for tasks. + ready_.fetch_add(1, std::memory_order_release); + test_point(detail::PoolTestPoint::AfterReady, worker_id); + + while (true) { + // Phase 1: Spin on per-worker flag (private cache line, no contention). + // The main thread writes to each worker's flag after setting up the task. + // The acquire load on wake_gen provides happens-before for all writes + // the main thread did before the release store (task_ptr_, claim_, done_), + // so we can access them without the mutex. + bool woken_by_spin = false; + for (int i = 0; i < WORKER_SPIN_COUNT; i++) { + uint64_t wake = + worker_slots_[worker_id].wake_gen.load(std::memory_order_acquire); + if (wake > my_gen) { + my_gen = wake; + woken_by_spin = true; + break; + } + MLX_SPIN_PAUSE(); + } + + if (woken_by_spin) { + // Fast path: skip mutex entirely. + if (stop_) + return; + claim_slot(worker_id, my_gen); + continue; + } + + // Phase 2: cv_.wait fallback for long idle periods. + // Workers that exhaust the spin count sleep here until cv_.notify_one. + { + std::unique_lock lk(mtx_); + // Announce sleeping INSIDE mutex -- the main thread reads + // sleeping_count_ under the same mutex to decide how many + // cv_.notify_one calls to make. This gives an exact count. + sleeping_count_.fetch_add(1, std::memory_order_relaxed); + cv_.wait(lk, [&] { + return gen_.load(std::memory_order_acquire) != my_gen || stop_; + }); + sleeping_count_.fetch_sub(1, std::memory_order_relaxed); + if (stop_) + return; + my_gen = gen_.load(std::memory_order_acquire); + // Release mutex immediately -- task state is visible via gen_ acquire + // (happens-before from parallel_for's gen_.fetch_add release). + lk.unlock(); + claim_slot(worker_id, my_gen); + } + } +} + +void CPUThreadPool::parallel_for( + int n_threads, + std::function f) { + n_threads = std::min(std::max(n_threads, 1), max_threads_); + if (n_threads == 1) { + f(0, 1); + return; + } + + // Nested: run every slot inline, since the workers are busy with the outer + // call and dispatch_mtx_ is not recursive. Callers size state by n_threads. + if (in_parallel_for) { + for (int slot = 0; slot < n_threads; ++slot) { + f(slot, n_threads); + } + return; + } + + // Serialize concurrent parallel_for calls from different CPU streams. + // All task state (task_ptr_, claim_, done_, etc.) is shared, so + // concurrent calls would corrupt each other. The second caller blocks + // until the first completes -- this is correct because the workers are + // shared and can only process one task at a time anyway. + std::lock_guard dispatch_lk(dispatch_mtx_); + first_error_ = nullptr; + + int needed_workers = n_threads - 1; + int n_workers = static_cast(workers_.size()); + + // -- NORMAL DISPATCH PATH ------------------------------------------- + // Used when workers are spinning on wake_gen or sleeping in cv_.wait. + // Requires mutex for gen_ update (cv_ lost-wakeup safety) and + // per-worker wake_gen writes. + + // Set up the task. The release store to claim_ below publishes it. + task_ptr_ = &f; + done_.store(0, std::memory_order_relaxed); + + int wake_count = std::min(needed_workers, n_workers); + + // Increment generation under the mutex to prevent lost-wakeup race. + // Without the mutex, a worker between cv_.wait's predicate check and + // the actual wait() call could miss the notify. The mutex serializes + // gen_ update with the workers' predicate-to-wait transition. + // + uint64_t new_gen; + int n_sleeping; + { + std::lock_guard lk(mtx_); + n_sleeping = sleeping_count_.load(std::memory_order_relaxed); + new_gen = gen_.fetch_add(1, std::memory_order_release) + 1; + // Slot 0 is the caller's, so the workers start at slot 1. + claim_.store( + (new_gen << 32) | (static_cast(n_threads) << 16) | 1, + std::memory_order_release); + } + + // Write per-worker wake flags -- spinning workers see these immediately. + // Writing wake_gen only to needed workers avoids cache-line invalidations + // on idle workers' slots. + for (int i = 0; i < wake_count; i++) { + worker_slots_[i].wake_gen.store(new_gen, std::memory_order_release); + } + + // Wake sleeping workers. Using notify_all instead of Nxnotify_one + // because a fast worker can finish its task, exhaust the spin loop, + // and re-enter cv_.wait before all notify_one calls are sent -- causing + // it to "absorb" a notification meant for another worker (lost wakeup). + // notify_all is a single futex(FUTEX_WAKE, INT_MAX) syscall on Linux, + // actually cheaper than 31x futex(FUTEX_WAKE, 1). Workers whose + // my_gen already matches gen_ will re-check the predicate and go back + // to sleep immediately (no spurious task execution). + if (n_sleeping > 0) { + cv_.notify_all(); + } + + // Main thread executes slot 0 + run_slot(0, n_threads); + done_.fetch_add(1, std::memory_order_acq_rel); + + // Wait for workers -- spin then yield + for (int i = 0; done_.load(std::memory_order_acquire) < n_threads; i++) { + if (i < 4096) { + MLX_SPIN_PAUSE(); + } else { + std::this_thread::yield(); + } + } + + if (first_error_) { + std::exception_ptr error = first_error_; + first_error_ = nullptr; + std::rethrow_exception(error); + } +} + +int CPUThreadPool::max_threads() const { + return max_threads_; +} + +std::unique_ptr create_thread_pool_backend() { + return std::make_unique(); +} + +namespace detail { +std::unique_ptr make_thread_pool(int threads) { + return std::make_unique(threads); +} + +void set_pool_test_hook(PoolTestHook hook) { + test_hook.store(hook, std::memory_order_relaxed); +} +} // namespace detail + +bool openblas_present() { + // The pool's constructor runs init_blas_funcs, whose one-time guard is not + // synchronised: let it happen there, once. + ThreadPool::instance(); + return blas_set_threads != nullptr; +} + +bool openblas_pinned() { + ThreadPool::instance(); // the pool pins at construction + return openblas_pinned_flag().load(); +} + +} // namespace mlx::core::cpu +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.h b/mlx/backend/cpu/threading/openblas/thread_pool.h new file mode 100644 index 0000000000..e4b1ee973b --- /dev/null +++ b/mlx/backend/cpu/threading/openblas/thread_pool.h @@ -0,0 +1,88 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/backend/cpu/threading/base.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace mlx::core::cpu { + +/** + * Persistent thread pool for Linux/Windows with optional OpenBLAS coordination. + * + * This pool manages its own std::thread workers and pins OpenBLAS to + * single-threaded mode at startup when OpenBLAS symbols are available. This + * avoids over-subscription (e.g. our 32 threads + OpenBLAS's 32 threads + * fighting for 32 cores). BLAS performance is unaffected because matmul + * (cblas.cpp) calls cblas_sgemm from within parallel_for -- each worker invokes + * single-threaded BLAS on its row slice, achieving full core utilization + * without internal BLAS threading. + * + * Worker wakeup uses per-worker cache-line-aligned generation flags. Workers + * spin briefly on their private flag (no cross-core cache contention), then + * fall back to cv_.wait for long idle periods. + */ +class CPUThreadPool : public ThreadPoolBackend { + public: + CPUThreadPool(); + // A pool of `threads` threads, the calling thread included. + explicit CPUThreadPool(int threads); + ~CPUThreadPool() override; + + void parallel_for(int n_threads, std::function f) + override; + int max_threads() const override; + + private: + void worker_loop(int worker_id); + void run_slot(int slot, int nth); + // Claims and runs one slot of call `gen`, if the call has a slot left. + void claim_slot(int worker_id, uint64_t gen); + + // Per-worker wake flag on its own cache line to avoid false sharing. + // Workers spin on their private flag -- no cross-core cache contention. + struct alignas(64) WorkerSlot { + std::atomic wake_gen{0}; + }; + // Maximum background workers. The main caller also participates, so + // max_threads_ can be at most MAX_WORKERS + 1. + static constexpr int MAX_WORKERS = 128; + + std::vector workers_; + int max_threads_; + + // Serializes concurrent parallel_for calls from different CPU streams. + // MLX's stream_generate uses a separate generation_stream, so two + // StreamThreads may call parallel_for simultaneously. Since all task + // state (task_ptr_, claim_, done_, etc.) is shared, concurrent calls + // must be serialized. + std::mutex dispatch_mtx_; + + std::mutex mtx_; // worker sleep/wake coordination + std::condition_variable cv_; + + const std::function* task_ptr_ = nullptr; + // The call's generation (high 32 bits), slot count and next slot (16 bits + // each). One CAS claims a slot, and it fails when the call has changed. + std::atomic claim_{0}; + std::atomic done_{0}; + std::atomic ready_{0}; + std::atomic gen_{0}; + std::atomic sleeping_count_{0}; // workers currently in cv_.wait + std::atomic stop_{false}; + + // The first exception any slot of the current parallel_for threw. + std::mutex error_mtx_; + std::exception_ptr first_error_; + + WorkerSlot worker_slots_[MAX_WORKERS]; +}; + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/unary.h b/mlx/backend/cpu/unary.h index 096521df89..4a0e870ce0 100644 --- a/mlx/backend/cpu/unary.h +++ b/mlx/backend/cpu/unary.h @@ -5,6 +5,9 @@ #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/threading/common.h" +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/dtype_utils.h" #include "mlx/utils.h" @@ -18,6 +21,26 @@ void unary_op(const T* a, U* out, size_t shape, size_t stride) { } } +#if defined(MLX_USE_HIGHWAY_KERNELS) +// Helper to process a contiguous chunk of unary op with SIMD +template +void unary_op_contiguous_chunk(const T* src, U* dst, size_t size) { + constexpr int N = std::min(simd::max_size, simd::max_size); + while (size >= N) { + simd::store(dst, simd::Simd(Op{}(simd::load(src)))); + size -= N; + src += N; + dst += N; + } + while (size > 0) { + *dst = Op{}(*src); + size--; + dst++; + src++; + } +} + +#endif // MLX_USE_HIGHWAY_KERNELS template void unary_op(const array& a, array& out, Op) { const T* src = a.data(); @@ -25,30 +48,106 @@ void unary_op(const array& a, array& out, Op) { auto ndim = a.ndim(); if (a.flags().contiguous) { auto size = a.data_size(); +#if !defined(MLX_USE_HIGHWAY_KERNELS) constexpr int N = std::min(simd::max_size, simd::max_size); while (size >= N) { simd::store(dst, simd::Simd(Op{}(simd::load(src)))); size -= N; src += N; dst += N; +#else + + // Check if parallelization is beneficial + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(size, pool.max_threads()); + + if (n_threads > 1) { + // Parallel path for large contiguous arrays + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, size); + if (start < end) { + unary_op_contiguous_chunk( + src + start, dst + start, end - start); + } + }); + } else { + // Single-threaded path + unary_op_contiguous_chunk(src, dst, size); +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) while (size > 0) { *dst = Op{}(*src); size--; dst++; src++; } +#endif // MLX_USE_HIGHWAY_KERNELS } else { +#if !defined(MLX_USE_HIGHWAY_KERNELS) size_t shape = ndim > 0 ? a.shape().back() : 1; size_t stride = ndim > 0 ? a.strides().back() : 1; +#else + size_t inner_shape = ndim > 0 ? a.shape().back() : 1; + size_t inner_stride = ndim > 0 ? a.strides().back() : 1; +#endif // MLX_USE_HIGHWAY_KERNELS if (ndim <= 1) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) unary_op(src, dst, shape, stride); +#else + unary_op(src, dst, inner_shape, inner_stride); +#endif // MLX_USE_HIGHWAY_KERNELS return; } +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto it = ContiguousIterator(a.shape(), a.strides(), ndim - 1); for (size_t elem = 0; elem < a.size(); elem += shape) { unary_op(src + it.loc, dst + elem, shape, stride); it.step(); +#else + + if (a.size() == 0) { + return; + } + size_t num_iterations = a.size() / inner_shape; + + // Check if parallelization is beneficial + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(a.size(), pool.max_threads()); + + if (n_threads > 1 && num_iterations >= static_cast(n_threads)) { + // Parallel path for strided arrays + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (num_iterations + nth - 1) / nth; + size_t start_iter = chunk * tid; + size_t end_iter = std::min(start_iter + chunk, num_iterations); + + if (start_iter >= end_iter) { + return; + } + + ContiguousIterator it(a.shape(), a.strides(), ndim - 1); + it.seek(static_cast(start_iter)); + + for (size_t iter = start_iter; iter < end_iter; ++iter) { + unary_op( + src + it.loc, + dst + iter * inner_shape, + inner_shape, + inner_stride); + it.step(); + } + }); + } else { + // Sequential path + auto it = ContiguousIterator(a.shape(), a.strides(), ndim - 1); + for (size_t elem = 0; elem < a.size(); elem += inner_shape) { + unary_op(src + it.loc, dst + elem, inner_shape, inner_stride); + it.step(); + } +#endif // MLX_USE_HIGHWAY_KERNELS } } } diff --git a/mlx/backend/cpu/unary_ops.h b/mlx/backend/cpu/unary_ops.h index 64e20c65da..d8fbe6eabc 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -77,8 +77,12 @@ struct Real { struct Sigmoid { template Simd operator()(Simd x) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto y = 1.0f / (1.0f + simd::exp(simd::abs(x))); return simd::select(x < Simd{0}, y, Simd{1} - y); +#else + return simd::sigmoid(x); +#endif // MLX_USE_HIGHWAY_KERNELS } SINGLE() }; @@ -88,12 +92,17 @@ struct Sign { Simd operator()(Simd x) { auto z = Simd{0}; auto o = Simd{1}; +#if !defined(MLX_USE_HIGHWAY_KERNELS) auto m = Simd{-1}; +#endif // MLX_USE_HIGHWAY_KERNELS if constexpr (std::is_unsigned_v) { return simd::select(x == z, z, o); } else if constexpr (std::is_same_v) { return simd::select(x == z, x, Simd(x / simd::abs(x))); } else { +#if defined(MLX_USE_HIGHWAY_KERNELS) + auto m = Simd{-1}; +#endif // MLX_USE_HIGHWAY_KERNELS return simd::select(x < z, m, simd::select(x > z, o, z)); } } @@ -159,6 +168,7 @@ struct FromFP8 { auto v = Simd(x & 127); auto sign_bit = Simd((x >> 7) & 1) << 15; auto u = (v << 7) | (((v + 1) >> 7) << 14) | sign_bit; +#if !defined(MLX_USE_HIGHWAY_KERNELS) Simd out; if constexpr (simd::max_size >= N) { auto converted = *(Simd*)(&u); @@ -170,6 +180,10 @@ struct FromFP8 { } } return out; +#else + auto converted = *(Simd*)(&u); + return Simd(converted) * 256.0f; +#endif // MLX_USE_HIGHWAY_KERNELS } float operator()(uint8_t x) { return (*this)(Simd(x)).value; diff --git a/mlx/backend/no_cpu/CMakeLists.txt b/mlx/backend/no_cpu/CMakeLists.txt index c81a258557..1d7593a2f1 100644 --- a/mlx/backend/no_cpu/CMakeLists.txt +++ b/mlx/backend/no_cpu/CMakeLists.txt @@ -4,4 +4,5 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/primitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../cpu/eval.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../cpu/encoder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../cpu/precision.cpp ${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp) diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index c37515f9ef..b4cdd7e24b 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -34,6 +34,18 @@ bool fast::ScaledDotProductAttention::use_fallback( bool output_logsumexp, bool force_fused, Stream s) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + // Use native CPU kernel for inference (handles causal, array mask, sinks). + // It takes float32, float16 and bfloat16, one head dim up to 256, and keys + // and values of the same length. + const bool native_type = + q.dtype() == float32 || q.dtype() == float16 || q.dtype() == bfloat16; + if (s.device == Device::cpu && !output_logsumexp && native_type && + q.shape(-1) == v.shape(-1) && q.shape(-1) <= 256 && + k.shape(-2) == v.shape(-2)) { + return false; + } +#endif // MLX_USE_HIGHWAY_KERNELS if (force_fused) { throw std::invalid_argument( "[scaled_dot_product_attention] force_fused=True but no fused " @@ -182,11 +194,35 @@ NO_GPU(MaskedScatter) namespace fast { NO_GPU_USE_FALLBACK(CrossEntropy) NO_GPU_MULTI(CrossEntropyVJP) +#if !defined(MLX_USE_HIGHWAY_KERNELS) NO_GPU_USE_FALLBACK(LayerNorm) +#else +// LayerNorm and RMSNorm have native CPU implementations (norms.cpp) +// so don't use fallback on CPU +bool LayerNorm::use_fallback(Stream s) { + return false; // Use native eval_cpu +} +NO_GPU_MULTI(LayerNorm) +#endif // MLX_USE_HIGHWAY_KERNELS NO_GPU_MULTI(LayerNormVJP) +#if !defined(MLX_USE_HIGHWAY_KERNELS) NO_GPU_USE_FALLBACK(RMSNorm) +#else +bool RMSNorm::use_fallback(Stream s) { + return false; // Use native eval_cpu +} +NO_GPU_MULTI(RMSNorm) +#endif // MLX_USE_HIGHWAY_KERNELS NO_GPU_MULTI(RMSNormVJP) +#if !defined(MLX_USE_HIGHWAY_KERNELS) NO_GPU_USE_FALLBACK(RoPE) +#else +// RoPE has native CPU implementation (rope.cpp) +bool RoPE::use_fallback(Stream s) { + return false; // Use native eval_cpu +} +NO_GPU_MULTI(RoPE) +#endif // MLX_USE_HIGHWAY_KERNELS NO_GPU_MULTI(ScaledDotProductAttention) NO_GPU_MULTI(ScaledDotProductAttentionVJP) NO_GPU_MULTI(GatedDeltaUpdate) diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index dd893fa5da..730dc4c7ef 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -48,9 +48,13 @@ class RMSNorm : public Custom { static bool use_fallback(Stream stream); void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -81,9 +85,13 @@ class RMSNormVJP : public Custom { : Custom(stream, std::move(fallback)), eps_(eps) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -169,9 +177,13 @@ class LayerNorm : public Custom { static bool use_fallback(Stream s); void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -201,9 +213,13 @@ class LayerNormVJP : public Custom { : Custom(stream, std::move(fallback)), eps_(eps) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -237,9 +253,13 @@ class RoPE : public Custom { static bool use_fallback(Stream s); void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -296,10 +316,14 @@ class ScaledDotProductAttention : public Custom { static bool supports_bool_mask(); void eval_cpu(const std::vector& inputs, std::vector& outputs) +#if !defined(MLX_USE_HIGHWAY_KERNELS) override { throw std::runtime_error("NYI"); } +#else + override; +#endif // MLX_USE_HIGHWAY_KERNELS void eval_gpu(const std::vector& inputs, std::vector& outputs) override; diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 6365251437..4a15c84e6b 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -1,4 +1,4 @@ -# Copyright © 2023-2024 Apple Inc. +# Copyright © 2023-2026 Apple Inc. import gc import inspect @@ -1723,6 +1723,188 @@ def fun(x): x = mx.array([1.0, float("nan"), 3.0]) self.assertTrue(mx.array_equal(mx.compile(fun)(x), mx.array([False, True]))) + def test_compile_large_contiguous(self): + """Test compiled kernels on large arrays (triggers parallel dispatch).""" + N = 500_000 # > 256K threshold for threading + + def fn(x): + return mx.exp(x) + 1.0 + + x = mx.random.normal((N,)) + mx.eval(x) + + compiled_fn = mx.compile(fn) + out = compiled_fn(x) + expected = fn(x) + self.assertTrue(mx.allclose(out, expected, atol=1e-5)) + + def test_compile_large_with_scalar_broadcast(self): + """Scalar broadcasts must not be offset in parallel dispatch.""" + N = 500_000 + + def fn(x, scale): + return x * scale + + x = mx.random.normal((N,)) + scale = mx.array(2.5) # scalar + mx.eval(x, scale) + + compiled_fn = mx.compile(fn) + out = compiled_fn(x, scale) + expected = fn(x, scale) + self.assertTrue(mx.allclose(out, expected, atol=1e-5)) + + def test_compile_large_multi_output(self): + """Multiple outputs with large arrays and parallel dispatch.""" + N = 500_000 + + def fn(x): + return mx.exp(x), mx.sin(x) + + x = mx.random.normal((N,)) + mx.eval(x) + + compiled_fn = mx.compile(fn) + out_a, out_b = compiled_fn(x) + exp_a, exp_b = fn(x) + self.assertTrue(mx.allclose(out_a, exp_a, atol=1e-5)) + self.assertTrue(mx.allclose(out_b, exp_b, atol=1e-5)) + + def test_compile_large_dtypes(self): + """Large arrays with different dtypes for parallel dispatch.""" + N = 500_000 + + def fn(x): + return x + x + + for dtype in [mx.float32, mx.float16, mx.int32]: + if dtype == mx.int32: + x = mx.random.randint(0, 100, (N,)) + else: + x = mx.random.normal((N,)).astype(dtype) + mx.eval(x) + + compiled_fn = mx.compile(fn) + out = compiled_fn(x) + expected = fn(x) + self.assertTrue(mx.array_equal(out, expected)) + + def test_compile_small_no_threading(self): + """Small arrays should still work (single-threaded path).""" + + def fn(x, y): + return mx.exp(x + y) + + x = mx.array([1.0, 2.0, 3.0]) + y = mx.array([0.5, 0.5, 0.5]) + mx.eval(x, y) + + compiled_fn = mx.compile(fn) + out = compiled_fn(x, y) + expected = fn(x, y) + self.assertTrue(mx.allclose(out, expected, atol=1e-6)) + + def test_compile_strided(self): + """Transposed (non-contiguous) inputs exercise strided code generation.""" + + def fn(x, y): + return x + y + + a = mx.arange(12, dtype=mx.float32).reshape(3, 4) + # Transpose makes strides non-contiguous + a_t = a.T + b = mx.ones((4, 3), dtype=mx.float32) + mx.eval(a_t, b) + + compiled_fn = mx.compile(fn) + out = compiled_fn(a_t, b) + expected = fn(a_t, b) + self.assertTrue(mx.array_equal(out, expected)) + + def test_compile_bfloat16(self): + """Compiled kernel with bfloat16 dtype.""" + + def fn(x, y): + return x * y + x + + x = mx.ones((64,), dtype=mx.bfloat16) * 2.0 + y = mx.ones((64,), dtype=mx.bfloat16) * 3.0 + mx.eval(x, y) + + compiled_fn = mx.compile(fn) + out = compiled_fn(x, y) + expected = fn(x, y) + self.assertTrue(mx.allclose(out, expected, atol=1e-2)) + self.assertEqual(out.dtype, mx.bfloat16) + + def test_compile_large_strided(self): + """Large transposed array to trigger parallel strided dispatch.""" + + def fn(x): + return x * 2.0 + + # 500K+ elements, transposed for non-contiguous strides + a = mx.arange(512 * 1024, dtype=mx.float32).reshape(512, 1024) + a_t = a.T + mx.eval(a_t) + + compiled_fn = mx.compile(fn) + out = compiled_fn(a_t) + expected = fn(a_t) + self.assertTrue(mx.array_equal(out, expected)) + + def test_compile_strided_multidim(self): + """3D array with permuted axes exercises multi-dimensional strided path.""" + + def fn(x, y): + return x + y + + a = mx.arange(2 * 3 * 4, dtype=mx.float32).reshape(2, 3, 4) + # Permute axes: (2,3,4) -> (4,2,3) + a_p = mx.transpose(a, axes=(2, 0, 1)) + b = mx.ones((4, 2, 3), dtype=mx.float32) + mx.eval(a_p, b) + + compiled_fn = mx.compile(fn) + out = compiled_fn(a_p, b) + expected = fn(a_p, b) + self.assertTrue(mx.array_equal(out, expected)) + + def test_compile_strided_broadcast(self): + """Strided array combined with scalar broadcast in a compiled kernel.""" + + def fn(x, s): + return x + s + + a = mx.arange(12, dtype=mx.float32).reshape(3, 4).T + s = mx.array(10.0) + mx.eval(a, s) + + compiled_fn = mx.compile(fn) + out = compiled_fn(a, s) + expected = fn(a, s) + self.assertTrue(mx.array_equal(out, expected)) + + def test_compile_bypass_threshold(self): + """Arrays at the compile bypass boundary still produce correct results.""" + + def fn(x): + return x + 1.0 + + # At exactly the threshold (262144 = 2^18) + x_at = mx.ones(262144, dtype=mx.float32) + # Just below threshold + x_below = mx.ones(262143, dtype=mx.float32) + # Just above threshold + x_above = mx.ones(262145, dtype=mx.float32) + mx.eval(x_at, x_below, x_above) + + compiled_fn = mx.compile(fn) + for x in [x_at, x_below, x_above]: + out = compiled_fn(x) + expected = fn(x) + self.assertTrue(mx.array_equal(out, expected)) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 42173ca674..fa1ffa568e 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -508,6 +508,44 @@ def test_qqmm_global_scale_matrix_kernels(self): ) self.assertLess(relative_error, 3e-2) + def test_qqmv_nvfp4_global_scale(self): + if mx.default_device() == mx.gpu: + self.skipTest("nvfp4 global scales are not supported on Metal") + + key = mx.random.key(0) + k1, k2 = mx.random.split(key) + x = mx.random.normal(shape=(1, 256), key=k1) + w = mx.random.normal(shape=(128, 256), key=k2) + x_scale = x.abs().max().astype(mx.float32) + w_scale = w.abs().max().astype(mx.float32) + + x_hat = mx.dequantize( + *mx.quantize(x, mode="nvfp4", global_scale=x_scale), + mode="nvfp4", + dtype=mx.float32, + global_scale=x_scale, + ) + w_q, scales = mx.quantize(w, mode="nvfp4", global_scale=w_scale) + w_hat = mx.dequantize( + w_q, + scales, + mode="nvfp4", + dtype=mx.float32, + global_scale=w_scale, + ) + + y_q = mx.qqmm( + x, + w_q, + scales, + mode="nvfp4", + global_scale_x=x_scale, + global_scale_w=w_scale, + ) + y_hat = x_hat @ mx.swapaxes(w_hat, -1, -2) + self.assertEqual(y_q.shape, y_hat.shape) + self.assertLess((y_q - y_hat).abs().max(), 1e-3) + def test_qmm(self): key = mx.random.key(0) k1, k2 = mx.random.split(key) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 86d791a352..bba9ce77eb 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -35,6 +35,7 @@ target_sources( einsum_tests.cpp export_import_tests.cpp eval_tests.cpp + fast_tests.cpp fft_tests.cpp load_tests.cpp metal_buffer_lifetime_tests.cpp @@ -48,9 +49,33 @@ target_sources( linalg_tests.cpp ${GPU_TEST_SOURCES}) +if(MLX_BUILD_CPU AND MLX_USE_HIGHWAY) + # The CPU thread pool exists only in builds with Highway kernels. + target_sources(tests PRIVATE thread_pool_tests.cpp) + target_sources(tests PRIVATE highway_quantized_tests.cpp) + target_sources(tests PRIVATE highway_kernel_tests.cpp) + target_sources(tests PRIVATE highway_info_tests.cpp) + target_sources(tests PRIVATE highway_threading_tests.cpp) + # highway_simd_tests.cpp includes the Highway facade, which includes + # hwy/highway.h. + target_sources(tests PRIVATE highway_simd_tests.cpp) + target_include_directories( + tests PRIVATE $) + target_compile_definitions(tests PRIVATE HWY_DISABLE_PCLMUL_AES) +endif() + target_link_libraries(tests PRIVATE mlx doctest) target_compile_options(tests PRIVATE ${SANITIZER_COMPILE_FLAGS}) target_link_options(tests PRIVATE ${SANITIZER_LINK_FLAGS}) -doctest_discover_tests(tests) +set(MLX_TEST_WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) +if(WIN32) + # OpenBLAS is copied to the build root on Windows. Run test discovery from + # there so the test executable can find libopenblas.dll at startup. + set(MLX_TEST_WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) +endif() + +doctest_discover_tests(tests WORKING_DIRECTORY ${MLX_TEST_WORKING_DIRECTORY}) add_test(NAME tests COMMAND tests) +set_tests_properties(tests PROPERTIES WORKING_DIRECTORY + ${MLX_TEST_WORKING_DIRECTORY}) diff --git a/tests/blas_tests.cpp b/tests/blas_tests.cpp index 823eb5b44a..c3f78ea46b 100644 --- a/tests/blas_tests.cpp +++ b/tests/blas_tests.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include @@ -109,6 +109,25 @@ TEST_CASE("test matmul") { CHECK(array_equal(out, full({2, 4, 4}, 2.0f)).item()); } +TEST_CASE("test matmul large transposed lhs") { + constexpr int M = 32; + constexpr int N = 32; + constexpr int K = 64; + + auto check = [](Dtype dtype, float rtol, float atol) { + auto a = astype(reshape(arange(K * M, float32) * 0.001f, {K, M}), dtype); + auto b = astype(reshape(arange(K * N, float32) * 0.002f, {K, N}), dtype); + auto lhs = transpose(a); + auto out = matmul(lhs, b); + auto expected = matmul(contiguous(lhs), b); + CHECK(allclose(out, expected, rtol, atol).item()); + }; + + check(complex64, 1e-5f, 1e-5f); + check(float16, 1e-2f, 1e-2f); + check(bfloat16, 2e-2f, 2e-2f); +} + TEST_CASE("test segmented_mm in bfloat16 and float16 on the cpu") { // Each segment must match the matmul of its slices. The reference runs in // float32, through cblas rather than simd_gemm or BNNS. |a·b| <= 6 and diff --git a/tests/fast_tests.cpp b/tests/fast_tests.cpp new file mode 100644 index 0000000000..b3bc56e98d --- /dev/null +++ b/tests/fast_tests.cpp @@ -0,0 +1,538 @@ +// Copyright © 2026 Apple Inc. + +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/precision.h" +#include "mlx/fast.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +void check_rope_float32(bool traditional) { + constexpr int B = 1; + constexpr int H = 1; + constexpr int T = 2; + constexpr int D = 16; + constexpr int dims = 16; + constexpr int half_dims = dims / 2; + constexpr float base = 10000.0f; + constexpr float scale = 1.0f; + + std::vector values(B * H * T * D); + for (int i = 0; i < static_cast(values.size()); ++i) { + values[i] = 0.125f * static_cast(i - 9); + } + + array x(values.data(), {B, H, T, D}); + array y = fast::rope(x, dims, traditional, base, scale, 0); + y.eval(); + + std::vector expected(values.size()); + const float log_base = std::log(base); + for (int t = 0; t < T; ++t) { + for (int j = 0; j < half_dims; ++j) { + const float theta = static_cast(t) * + std::exp(static_cast(-j) * log_base / half_dims); + const float c = std::cos(theta); + const float s = std::sin(theta); + + if (traditional) { + const size_t idx = static_cast(t) * D + 2 * j; + const float x0 = values[idx]; + const float x1 = values[idx + 1]; + expected[idx] = x0 * c - x1 * s; + expected[idx + 1] = x0 * s + x1 * c; + } else { + const size_t idx0 = static_cast(t) * D + j; + const size_t idx1 = static_cast(t) * D + j + half_dims; + const float x0 = values[idx0]; + const float x1 = values[idx1]; + expected[idx0] = x0 * c - x1 * s; + expected[idx1] = x0 * s + x1 * c; + } + } + } + + const float* out = y.data(); + for (int i = 0; i < static_cast(expected.size()); ++i) { + CHECK(out[i] == doctest::Approx(expected[i]).epsilon(1e-5)); + } +} + +template +void check_rope_typed(bool traditional, float tol) { + constexpr int B = 1; + constexpr int H = 1; + constexpr int T_len = 2; + constexpr int D = 16; + constexpr int dims = 16; + constexpr int half_dims = dims / 2; + constexpr float base = 10000.0f; + constexpr float scale = 1.0f; + + std::vector values(B * H * T_len * D); + std::vector values_f32(values.size()); + for (int i = 0; i < static_cast(values.size()); ++i) { + values_f32[i] = 0.125f * static_cast(i - 9); + values[i] = static_cast(values_f32[i]); + } + + array x(values.data(), {B, H, T_len, D}); + array y = fast::rope(x, dims, traditional, base, scale, 0); + y.eval(); + + std::vector expected(values.size()); + const float log_base = std::log(base); + for (int t = 0; t < T_len; ++t) { + for (int j = 0; j < half_dims; ++j) { + const float theta = static_cast(t) * + std::exp(static_cast(-j) * log_base / half_dims); + const float c = std::cos(theta); + const float s = std::sin(theta); + + if (traditional) { + const size_t idx = static_cast(t) * D + 2 * j; + const float x0 = values_f32[idx]; + const float x1 = values_f32[idx + 1]; + expected[idx] = x0 * c - x1 * s; + expected[idx + 1] = x0 * s + x1 * c; + } else { + const size_t idx0 = static_cast(t) * D + j; + const size_t idx1 = static_cast(t) * D + j + half_dims; + const float x0 = values_f32[idx0]; + const float x1 = values_f32[idx1]; + expected[idx0] = x0 * c - x1 * s; + expected[idx1] = x0 * s + x1 * c; + } + } + } + + const T* out = y.data(); + for (int i = 0; i < static_cast(expected.size()); ++i) { + CHECK( + static_cast(out[i]) == + doctest::Approx(expected[i]).epsilon(tol)); + } +} + +void check_rms_norm_float32(bool has_weight) { + constexpr int rows = 2; + constexpr int width = 16; + constexpr float eps = 1e-5f; + + std::vector values(rows * width); + for (int i = 0; i < static_cast(values.size()); ++i) { + values[i] = 0.2f * static_cast(i - 11); + } + + std::vector weights(width); + for (int i = 0; i < width; ++i) { + weights[i] = 0.75f + 0.03f * static_cast(i); + } + + array x(values.data(), {rows, width}); + std::optional weight; + if (has_weight) { + weight = array(weights.data(), {width}); + } + + array y = fast::rms_norm(x, weight, eps); + y.eval(); + + std::vector expected(values.size()); + for (int row = 0; row < rows; ++row) { + const float* row_ptr = values.data() + row * width; + float sum_sq = 0.0f; + for (int i = 0; i < width; ++i) { + sum_sq += row_ptr[i] * row_ptr[i]; + } + const float scale = 1.0f / std::sqrt(sum_sq / width + eps); + for (int i = 0; i < width; ++i) { + float value = row_ptr[i] * scale; + if (has_weight) { + value *= weights[i]; + } + expected[row * width + i] = value; + } + } + + const float* out = y.data(); + for (int i = 0; i < static_cast(expected.size()); ++i) { + CHECK(out[i] == doctest::Approx(expected[i]).epsilon(1e-5)); + } +} + +void check_layer_norm_float32(bool has_weight, bool has_bias) { + constexpr int rows = 2; + constexpr int width = 16; + constexpr float eps = 1e-5f; + + std::vector values(rows * width); + for (int i = 0; i < static_cast(values.size()); ++i) { + values[i] = 0.15f * static_cast(i - 7); + } + + std::vector weights(width); + std::vector biases(width); + for (int i = 0; i < width; ++i) { + weights[i] = 0.8f + 0.025f * static_cast(i); + biases[i] = -0.2f + 0.01f * static_cast(i); + } + + array x(values.data(), {rows, width}); + std::optional weight; + std::optional bias; + if (has_weight) { + weight = array(weights.data(), {width}); + } + if (has_bias) { + bias = array(biases.data(), {width}); + } + + array y = fast::layer_norm(x, weight, bias, eps); + y.eval(); + + std::vector expected(values.size()); + for (int row = 0; row < rows; ++row) { + const float* row_ptr = values.data() + row * width; + float sum = 0.0f; + for (int i = 0; i < width; ++i) { + sum += row_ptr[i]; + } + const float mean = sum / width; + + float variance = 0.0f; + for (int i = 0; i < width; ++i) { + const float diff = row_ptr[i] - mean; + variance += diff * diff; + } + variance /= width; + const float scale = 1.0f / std::sqrt(variance + eps); + + for (int i = 0; i < width; ++i) { + float value = (row_ptr[i] - mean) * scale; + if (has_weight) { + value *= weights[i]; + } + if (has_bias) { + value += biases[i]; + } + expected[row * width + i] = value; + } + } + + const float* out = y.data(); + for (int i = 0; i < static_cast(expected.size()); ++i) { + CHECK(out[i] == doctest::Approx(expected[i]).epsilon(1e-5)); + } +} + +void check_quantized_matmul_float32(int bits) { + constexpr int M = 32; + constexpr int N = 8; + constexpr int K = 64; + constexpr int group_size = 32; + + std::vector x_values(M * K); + for (int i = 0; i < static_cast(x_values.size()); ++i) { + x_values[i] = 0.02f * static_cast((i % 37) - 18); + } + + std::vector w_values(N * K); + for (int i = 0; i < static_cast(w_values.size()); ++i) { + w_values[i] = 0.03f * static_cast((i % 29) - 14); + } + + array x(x_values.data(), {M, K}); + array w(w_values.data(), {N, K}); + auto q = quantize(w, group_size, bits); + array y = quantized_matmul( + x, + q[0], + q[1], + q[2], + /* transpose = */ true, + group_size, + bits); + array expected = + matmul(x, transpose(dequantize(q[0], q[1], q[2], group_size, bits))); + + y.eval(); + expected.eval(); + CHECK(allclose(y, expected, 1e-5, 1e-5).item()); +} + +void check_quantized_matmul_token_float32(int bits, int M) { + constexpr int N = 256; + constexpr int K = 64; + constexpr int group_size = 32; + constexpr int q_pattern[group_size] = { + -127, -119, -111, -103, -95, -87, -79, -71, -63, -55, -47, + -39, -31, -23, -15, -7, 7, 15, 23, 31, 39, 47, + 55, 63, 71, 79, 87, 95, 103, 111, 119, 127}; + + std::vector x_values(M * K); + for (int i = 0; i < static_cast(x_values.size()); ++i) { + x_values[i] = static_cast(q_pattern[i % group_size]) / 127.0f; + } + + std::vector w_values(N * K); + for (int i = 0; i < static_cast(w_values.size()); ++i) { + w_values[i] = 0.015f * static_cast((i % 43) - 21); + } + + array x(x_values.data(), {M, K}); + array w(w_values.data(), {N, K}); + auto q = quantize(w, group_size, bits); + array y = quantized_matmul( + x, + q[0], + q[1], + q[2], + /* transpose = */ true, + group_size, + bits); + array expected = + matmul(x, transpose(dequantize(q[0], q[1], q[2], group_size, bits))); + + y.eval(); + expected.eval(); + CHECK(allclose(y, expected, 1e-4, 1e-4).item()); +} + +uint32_t pack_u8x4(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) { + return static_cast(v0) | (static_cast(v1) << 8) | + (static_cast(v2) << 16) | (static_cast(v3) << 24); +} + +void check_quantized_matmul_8bit_high_values(bool int8_activations) { + constexpr int M = 3; + constexpr int N = 72; + constexpr int K = 64; + constexpr int bits = 8; + constexpr int group_size = 32; + constexpr int pack_factor = 4; + constexpr int packs_per_col = K / pack_factor; + constexpr int groups_per_col = K / group_size; + static constexpr uint8_t q_pattern[16] = { + 0, 1, 2, 3, 7, 31, 63, 95, 127, 128, 129, 191, 223, 240, 254, 255}; + + auto q_value = [](int n, int k) { return q_pattern[(n * 5 + k * 3) & 15]; }; + + std::vector w_values(N * packs_per_col); + for (int n = 0; n < N; ++n) { + for (int p = 0; p < packs_per_col; ++p) { + const int k = p * pack_factor; + w_values[n * packs_per_col + p] = pack_u8x4( + q_value(n, k), + q_value(n, k + 1), + q_value(n, k + 2), + q_value(n, k + 3)); + } + } + + std::vector scales(N * groups_per_col); + std::vector biases(N * groups_per_col); + for (int n = 0; n < N; ++n) { + for (int g = 0; g < groups_per_col; ++g) { + scales[n * groups_per_col + g] = + 0.0015f * static_cast((n % 7) + 1) + + 0.00025f * static_cast(g); + biases[n * groups_per_col + g] = -0.08f + + 0.002f * static_cast(n % 11) + 0.015f * static_cast(g); + } + } + + std::vector x_values(M * K); + for (int i = 0; i < static_cast(x_values.size()); ++i) { + x_values[i] = 0.03125f * static_cast((i * 7) % 31 - 15); + } + + std::vector x_q(M * K); + std::vector x_scales(M * groups_per_col); + std::vector x_group_sums(M * groups_per_col); + for (int m = 0; m < M; ++m) { + for (int g = 0; g < groups_per_col; ++g) { + float sum_x = 0.0f; + float max_value = 0.0f; + for (int k = 0; k < group_size; ++k) { + const int kk = g * group_size + k; + const float x = x_values[m * K + kk]; + sum_x += x; + max_value = std::max(max_value, std::abs(x)); + } + + const float inv_scale = max_value > 0.0f ? 127.0f / max_value : 0.0f; + x_scales[m * groups_per_col + g] = max_value / 127.0f; + x_group_sums[m * groups_per_col + g] = sum_x; + for (int k = 0; k < group_size; ++k) { + const int kk = g * group_size + k; + int q = + static_cast(std::nearbyint(x_values[m * K + kk] * inv_scale)); + q = std::min(127, std::max(-127, q)); + x_q[m * K + kk] = static_cast(q); + } + } + } + + std::vector expected(M * N, 0.0f); + for (int m = 0; m < M; ++m) { + for (int n = 0; n < N; ++n) { + if (!int8_activations) { + // The exact activations: scale * sum_k(x * q) + bias * sum_k(x) per + // group, in double. + double sum = 0.0; + for (int g = 0; g < groups_per_col; ++g) { + double dot = 0.0; + double sum_x = 0.0; + for (int k = 0; k < group_size; ++k) { + const int kk = g * group_size + k; + const double x = x_values[m * K + kk]; + dot += x * static_cast(q_value(n, kk)); + sum_x += x; + } + sum += static_cast(scales[n * groups_per_col + g]) * dot + + static_cast(biases[n * groups_per_col + g]) * sum_x; + } + expected[m * N + n] = static_cast(sum); + continue; + } + float sum = 0.0f; + for (int g = 0; g < groups_per_col; ++g) { + const float scale = scales[n * groups_per_col + g]; + const float bias = biases[n * groups_per_col + g]; + int dot = 0; + for (int k = 0; k < group_size; ++k) { + const int kk = g * group_size + k; + dot += static_cast(x_q[m * K + kk]) * + static_cast(q_value(n, kk)); + } + sum += + scale * x_scales[m * groups_per_col + g] * static_cast(dot) + + bias * x_group_sums[m * groups_per_col + g]; + } + expected[m * N + n] = sum; + } + } + + array x(x_values.data(), {M, K}); + array w(w_values.data(), {N, packs_per_col}); + array scale_arr(scales.data(), {N, groups_per_col}); + array bias_arr(biases.data(), {N, groups_per_col}); + array y = quantized_matmul( + x, w, scale_arr, bias_arr, /* transpose = */ true, group_size, bits); + + y.eval(); + auto expected_arr = array(expected.data(), {M, N}, float32); + CHECK(max(abs(subtract(y, expected_arr))).item() < 2e-4f); +} + +template +void check_quantized_matmul_token_typed(int bits, int M, float tol) { + constexpr int N = 256; + constexpr int K = 64; + constexpr int group_size = 32; + constexpr int q_pattern[group_size] = { + -127, -119, -111, -103, -95, -87, -79, -71, -63, -55, -47, + -39, -31, -23, -15, -7, 7, 15, 23, 31, 39, 47, + 55, 63, 71, 79, 87, 95, 103, 111, 119, 127}; + + std::vector x_values(M * K); + for (int i = 0; i < static_cast(x_values.size()); ++i) { + x_values[i] = + static_cast(static_cast(q_pattern[i % group_size]) / 127.0f); + } + + std::vector w_values(N * K); + for (int i = 0; i < static_cast(w_values.size()); ++i) { + w_values[i] = static_cast(0.015f * static_cast((i % 43) - 21)); + } + + array x(x_values.data(), {M, K}); + array w(w_values.data(), {N, K}); + auto q = quantize(w, group_size, bits); + array y = quantized_matmul( + x, + q[0], + q[1], + q[2], + /* transpose = */ true, + group_size, + bits); + array expected = + matmul(x, transpose(dequantize(q[0], q[1], q[2], group_size, bits))); + + y.eval(); + expected.eval(); + CHECK(allclose(y, expected, tol, tol).item()); +} + +} // namespace + +TEST_CASE("test fast rope traditional float32") { + check_rope_float32(true); +} + +TEST_CASE("test fast rope non-traditional float32") { + check_rope_float32(false); +} + +TEST_CASE("test fast rope float16") { + check_rope_typed(true, 2e-3f); + check_rope_typed(false, 2e-3f); +} + +TEST_CASE("test fast rms_norm float32") { + check_rms_norm_float32(false); + check_rms_norm_float32(true); +} + +TEST_CASE("test fast layer_norm float32") { + check_layer_norm_float32(false, false); + check_layer_norm_float32(true, true); +} + +TEST_CASE("test fast quantized matmul prompt float32") { + check_quantized_matmul_float32(4); + check_quantized_matmul_float32(8); +} + +TEST_CASE("test fast quantized matmul token float32") { + check_quantized_matmul_token_float32(4, 1); + check_quantized_matmul_token_float32(8, 1); + check_quantized_matmul_token_float32(4, 4); + check_quantized_matmul_token_float32(8, 4); + check_quantized_matmul_8bit_high_values(false); +} + +TEST_CASE("test fast quantized matmul token float32 with int8 activations") { + if (!cpu::quantized_int8_available()) { + MESSAGE("no int8 path in this build"); + return; + } + cpu::detail::QuantizedInt8Scope on(true); + check_quantized_matmul_8bit_high_values(true); +} + +TEST_CASE("test fast quantized matmul token float16") { + check_quantized_matmul_token_typed(4, 1, 5e-3f); + check_quantized_matmul_token_typed(8, 1, 5e-3f); +} + +TEST_CASE("test fast quantized matmul token bfloat16") { + if (!cpu::detail::quantized_float32_accumulation()) { + MESSAGE( + "this build sums bf16 quantized matmuls in bf16; the bound is for float32 sums"); + return; + } + check_quantized_matmul_token_typed(4, 1, 8e-3f); + check_quantized_matmul_token_typed(8, 1, 8e-3f); +} diff --git a/tests/highway_info_tests.cpp b/tests/highway_info_tests.cpp new file mode 100644 index 0000000000..8fba2eed1d --- /dev/null +++ b/tests/highway_info_tests.cpp @@ -0,0 +1,188 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/precision.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace hi = mlx::core::cpu::highway_info; + +namespace { +std::vector bits_of(int64_t set) { + std::vector out; + for (int i = 0; i < 63; ++i) { + if (set & (int64_t{1} << i)) { + out.push_back(int64_t{1} << i); + } + } + return out; +} + +// max |got - reference| / max |reference|, both widened to float32. +float relative_error(const array& got, const array& reference) { + auto g = astype(got, float32); + auto r = astype(reference, float32); + return (max(abs(subtract(g, r))) / max(abs(r))).item(); +} + +// Unpins the dispatch targets however a case ends, an exception included, so +// that no later case runs pinned to one target. +struct UnpinTargets { + ~UnpinTargets() { + hi::set_targets_for_test(0); + } +}; +} // namespace + +TEST_CASE("highway info names what was compiled and what the CPU supports") { + hi::set_targets_for_test(0); + REQUIRE(hi::compiled_targets() != 0); + REQUIRE(hi::supported_targets() != 0); + for (auto t : bits_of(hi::compiled_targets())) { + CHECK(std::string(hi::target_name(t)).size() > 0); + } +} + +TEST_CASE("highway rms_norm records the target that ran, on every target") { + UnpinTargets unpin; + hi::set_targets_for_test(0); + auto runnable = hi::compiled_targets() & hi::supported_targets(); + auto x = random::normal({4, 512}, float32, 0.0f, 1.0f, random::key(31)); + auto weight = ones({512}, float32); + for (auto target : bits_of(runnable)) { + CAPTURE( + std::string( + hi::target_name(target))); // doctest prints a char* as an address + hi::set_targets_for_test(target); + hi::reset_stats(); + CHECK(sum(fast::rms_norm(x, weight, 1e-5f)).item() != 0.0f); + auto s = hi::stats(hi::Family::RmsNorm); + CHECK(s.executed == target); + CHECK(s.highway_calls > 0); + CHECK(s.fallback_calls == 0); + } +} + +TEST_CASE("highway mxfp8 matmul decodes every E4M3 code on every target") { + // The kernels widen float16 natively or by emulation, depending on the + // target, and select NaN for 0x7F and 0xFF. + UnpinTargets unpin; + StreamOrDevice cpu = Device::cpu; + auto deq = [&](const array& wq, const array& sc) { + return astype( + transpose( + dequantize( + wq, + sc, + std::nullopt, + 32, + 8, + "mxfp8", + std::nullopt, + std::nullopt, + cpu), + cpu), + float32, + cpu); + }; + // Eight rows of 64 codes, scales of 1 (E8M0 127); 0x7F in row 0, 0xFF in 1. + std::vector codes(8 * 64); + for (int i = 0; i < 8 * 64; ++i) { + codes[i] = static_cast((i * 37) % 0x7E); + } + codes[5] = 0x7F; + codes[64 + 40] = 0xFF; + auto w = view(array(codes.begin(), {8, 64}, uint8), uint32, cpu); + auto scales = full({8, 2}, 127, uint8, cpu); + auto x = ones({1, 64}, float32, cpu); + // Every sum is a multiple of 2^-9 below 2^15: exact in float32. + auto ref = matmul(x, deq(w, scales), cpu); + // Every other code once, at row c / 64 and column c % 64; 0 for 0x7F, 0xFF. + std::vector finite(4 * 64); + for (int c = 0; c < 4 * 64; ++c) { + finite[c] = (c & 0x7F) == 0x7F ? 0 : static_cast(c); + } + auto wf = view(array(finite.begin(), {4, 64}, uint8), uint32, cpu); + auto sf = full({4, 2}, 127, uint8, cpu); + auto rf = deq(wf, sf); + // Compute both references before any target is pinned. + sum(ref, cpu).item(); + sum(rf, cpu).item(); + hi::set_targets_for_test(0); + auto runnable = hi::compiled_targets() & hi::supported_targets(); + for (auto target : bits_of(runnable)) { + CAPTURE( + std::string( + hi::target_name(target))); // doctest prints a char* as an address + MESSAGE(std::string(hi::target_name(target))); + hi::set_targets_for_test(target); + hi::reset_stats(); + auto y = + quantized_matmul(x, w, scales, std::nullopt, true, 32, 8, "mxfp8", cpu); + CHECK(all(isnan(slice(y, {0, 0}, {1, 2}, cpu), cpu), cpu).item()); + CHECK_FALSE( + any(isnan(slice(y, {0, 2}, {1, 8}, cpu), cpu), cpu).item()); + CHECK( + array_equal( + slice(y, {0, 2}, {1, 8}, cpu), slice(ref, {0, 2}, {1, 8}, cpu), cpu) + .item()); + CHECK(hi::stats(hi::Family::QmmFp).executed == target); + hi::reset_stats(); + auto yf = quantized_matmul( + eye(64, float32, cpu), wf, sf, std::nullopt, true, 32, 8, "mxfp8", cpu); + CHECK(array_equal(yf, rf, cpu).item()); + auto s = hi::stats(hi::Family::QmmFp); + CHECK(s.executed == target); + CHECK(s.fallback_calls == 0); + } +} + +TEST_CASE("highway int8 family records only when the int8 path ran") { + // QmmTInt8 is dispatched for every affine 4/8-bit call below 32 rows; it runs + // the int8 kernels only when the switch is on. + auto w = random::normal({64, 256}, float32, 0.0f, 1.0f, random::key(33)); + auto x = random::normal({1, 256}, float32, 0.0f, 1.0f, random::key(34)); + auto q = quantize(w, 64, 4); + hi::reset_stats(); + CHECK( + sum(quantized_matmul(x, q[0], q[1], q[2], true, 64, 4)).item() != + 0.0f); + CHECK(hi::stats(hi::Family::QmmAffineInt8).highway_calls == 0); + { + cpu::detail::QuantizedInt8Scope on(true); + CHECK( + sum(quantized_matmul(x, q[0], q[1], q[2], true, 64, 4)).item() != + 0.0f); + } + CHECK(hi::stats(hi::Family::QmmAffineInt8).highway_calls > 0); +} + +TEST_CASE("highway norms and rope compose float64 through the fallback") { + // #3019's kernels implement float32, float16 and bfloat16; float64 threw. + auto x = random::normal({2, 4, 3, 64}, float32, 0.0f, 1.0f, random::key(32)); + auto x64 = astype(x, float64); + auto w64 = ones({64}, float64); + hi::reset_stats(); + auto rms = fast::rms_norm(x64, w64, 1e-5f); + auto layer = fast::layer_norm(x64, w64, zeros({64}, float64), 1e-5f); + auto rope = fast::rope(x64, 64, false, 10000.0f, 1.0f, 3); + CHECK( + relative_error(rms, fast::rms_norm(x, ones({64}, float32), 1e-5f)) < + 1e-5f); + CHECK( + relative_error( + layer, + fast::layer_norm( + x, ones({64}, float32), zeros({64}, float32), 1e-5f)) < 1e-5f); + CHECK( + relative_error(rope, fast::rope(x, 64, false, 10000.0f, 1.0f, 3)) < + 1e-5f); + for (auto family : + {hi::Family::RmsNorm, hi::Family::LayerNorm, hi::Family::Rope}) { + CHECK(hi::stats(family).fallback_calls > 0); + } +} diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp new file mode 100644 index 0000000000..b0709865a9 --- /dev/null +++ b/tests/highway_kernel_tests.cpp @@ -0,0 +1,421 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include +#include +#include + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/scratch.h" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +// |got - a b| <= c * eps32 * sum_k |a_ik b_kj|, both computed in float64 by +// MLX's ops: rigorous for fp32 at c = K + 2, in any summation order. +bool within_sum_bound( + const array& got, + const array& a, + const array& b, + double c) { + auto a64 = astype(a, float64); + auto b64 = astype(b, float64); + auto reference = matmul(a64, b64); + auto magnitude = matmul(abs(a64), abs(b64)); + auto bound = multiply( + array(c * std::numeric_limits::epsilon(), float64), magnitude); + return all(less_equal(abs(subtract(astype(got, float64), reference)), bound)) + .item(); +} + +// max |got - reference| / max |reference|, both widened to float32. +float relative_error(const array& got, const array& reference) { + auto g = astype(got, float32); + auto r = astype(reference, float32); + return (max(abs(subtract(g, r))) / max(abs(r))).item(); +} + +} // namespace + +namespace { + +array sdpa_reference( + const array& q, + const array& k, + const array& v, + float scale) { + auto scores = + multiply(matmul(q, transpose(k, {0, 1, 3, 2})), array(scale, q.dtype())); + return matmul(softmax(scores, -1, /* precise = */ true), v); +} + +} // namespace + +TEST_CASE("highway sdpa declines shapes and types its kernel cannot hold") { + // (query/key head dim, value head dim, dtype): unequal head dims, one above + // the kernel's 256, and float64, which the kernel does not implement. + struct Case { + int dqk, dv; + Dtype dtype; + }; + for (auto c : std::vector{ + {192, 128, float32}, + {128, 192, float32}, + {320, 320, float32}, + {64, 64, float64}}) { + CAPTURE(c.dqk); + CAPTURE(c.dv); + auto q = astype( + random::normal({1, 4, 8, c.dqk}, float32, 0.0f, 1.0f, random::key(1)), + c.dtype); + auto k = astype( + random::normal({1, 4, 16, c.dqk}, float32, 0.0f, 1.0f, random::key(2)), + c.dtype); + auto v = astype( + random::normal({1, 4, 16, c.dv}, float32, 0.0f, 1.0f, random::key(3)), + c.dtype); + const float scale = 1.0f / std::sqrt(static_cast(c.dqk)); + auto y = fast::scaled_dot_product_attention(q, k, v, scale); + CHECK(relative_error(y, sdpa_reference(q, k, v, scale)) < 1e-5f); + } +} + +TEST_CASE("highway float64 elementwise math computes in double") { + // Values whose float and double results differ in the double's low bits. + std::vector a = { + 1.1, + 2.2, + 3.3, + 10.5, + 123.456, + 0.01, + 7.77, + 1e5, + 2.5, + 9.75, + 0.3, + 42.0, + 5.5, + 8.25, + 1.9, + 6.6, + 3.7}; + std::vector b = { + 0.7, + 1.3, + -2.9, + 3.1, + -0.45, + 2.2, + 1.7, + -3.3, + 0.9, + 1.1, + -1.7, + 2.6, + 0.35, + -4.1, + 1.05, + 2.9, + -0.8}; + const int n = static_cast(a.size()); + auto x = array(a.data(), {n}, float64); + auto y = array(b.data(), {n}, float64); + auto logs = log(x); + auto powers = power(x, y); + auto angles = arctan2(x, y); + auto remainders = remainder(x, y); + for (int i = 0; i < n; ++i) { + CAPTURE(a[i]); + CAPTURE(b[i]); + CHECK(slice(logs, {i}, {i + 1}).item() == std::log(a[i])); + CHECK(slice(powers, {i}, {i + 1}).item() == std::pow(a[i], b[i])); + CHECK(slice(angles, {i}, {i + 1}).item() == std::atan2(a[i], b[i])); + // base_simd's rule: std::remainder's result, moved into b's sign. + double r = std::remainder(a[i], b[i]); + if (r != 0 && (r < 0) != (b[i] < 0)) { + r += b[i]; + } + CHECK(slice(remainders, {i}, {i + 1}).item() == r); + } +} + +TEST_CASE("highway integer power with a negative exponent") { + // base_simd.h's rule: a signed integer to a negative power is 0, for every + // base, 1 included. #3019's facade looped forever here. + std::vector bases = { + 2, 3, -2, 5, 7, 1, 4, 6, 2, -3, 1, 0, 9, 2, -1, 3, 5}; + std::vector exponents = { + -1, -2, -3, 2, 0, -1, 3, -5, 10, 3, 7, 0, 2, -8, 5, 4, 1}; + std::vector expected = { + 0, 0, 0, 25, 1, 0, 64, 0, 1024, -27, 1, 1, 81, 0, -1, 81, 5}; + const int n = static_cast(bases.size()); + auto y = power( + array(bases.begin(), {n}, int32), array(exponents.begin(), {n}, int32)); + for (int i = 0; i < n; ++i) { + CAPTURE(bases[i]); + CAPTURE(exponents[i]); + CHECK(slice(y, {i}, {i + 1}).item() == expected[i]); + } +} + +TEST_CASE("highway fp16 sum keeps each thread's partial in float") { + // 2^18 + 3 elements of 2^-4, then -2^14: the sum is exactly 0.1875. Each + // thread's partial, rounded to float16, would lose its 2^-4 parts. + StreamOrDevice cpu = Device::cpu; + auto x = concatenate( + {full({(1 << 18) + 3}, 0.0625f, float16, cpu), + full({1}, -16384.0f, float16, cpu)}, + cpu); + CHECK(astype(sum(x, cpu), float32, cpu).item() == 0.1875f); +} + +TEST_CASE("highway fp16 strided sum and prod accumulate in float") { + // Down each column, float16 steps stop at 2048 (2049 is no float16) and + // 256 * 256 overflows; in float the sums are 4096 and the products 1. + StreamOrDevice cpu = Device::cpu; + auto x = ones({4096, 8}, float16, cpu); + auto s = sum(x, 0, false, cpu); + CHECK(s.shape() == Shape{8}); + CHECK(array_equal( + astype(s, float32, cpu), + sum(astype(x, float32, cpu), 0, false, cpu), + cpu) + .item()); + std::vector v; + for (float r : {256.0f, 256.0f, 1.0f / 256, 1.0f / 256}) { + v.insert(v.end(), 8, r); + } + auto y = astype(array(v.begin(), {4, 8}), float16, cpu); + auto p = prod(y, 0, false, cpu); + CHECK(p.shape() == Shape{8}); + CHECK(array_equal( + astype(p, float32, cpu), + prod(astype(y, float32, cpu), 0, false, cpu), + cpu) + .item()); +} + +TEST_CASE("highway bf16 sum does not depend on the thread count") { + // 2^20 + 3 ones, then -2^20: exactly 3. Partials rounded to bf16 gave 0 with + // 8 threads, and -8192 with 9 or 12. Widen before item. + auto x = concatenate( + {ones({(1 << 20) + 3}, bfloat16), full({1}, -1048576.0f, bfloat16)}); + CHECK(astype(sum(x), float32).item() == 3.0f); +} + +TEST_CASE("highway facade fma rounds once on every target") { + // erfinv computes fma(a, -a, 1): rounding a * a first left 64 units in the + // last place at 0.99983, where one rounding keeps the worst near 2.1. + const int n = 1001; + std::vector xs(n); + for (int i = 0; i < n; ++i) { + xs[i] = 0.999f + 0.000000999f * static_cast(i); // 0.999 to 0.999999 + } + auto y = erfinv(array(xs.data(), {n}, float32)); + double worst = 0; + for (int i = 0; i < n; ++i) { + // erf^-1 in double, by bisection on std::erf. + double low = 0, high = 6; + for (int k = 0; k < 80; ++k) { + const double mid = (low + high) / 2; + (std::erf(mid) < xs[i] ? low : high) = mid; + } + const double truth = (low + high) / 2; + const float t32 = static_cast(truth); + const double unit = std::nextafter(t32, INFINITY) - t32; + const double got = slice(y, {i}, {i + 1}).item(); + REQUIRE(std::isfinite(got)); + worst = std::max(worst, std::abs(got - truth) / unit); + } + CAPTURE(worst); + CHECK(worst <= 8.0); +} + +TEST_CASE("highway float16 keeps inf and nan") { + // Where Highway emulates float16 -> float32, it decodes exponent 31 as a + // finite exponent: inf as 65536. + const uint16_t pattern[4] = { + 0x7C00, 0xFC00, 0x7E00, 0x3C00}; // inf -inf nan 1 + std::vector bits(64); + for (int i = 0; i < 64; ++i) { + bits[i] = pattern[i % 4]; + } + auto x = view(array(bits.data(), {64}, uint16), float16); + auto half_at = [](const array& a, int i) { + return static_cast(slice(a, {i}, {i + 1}).item()); + }; + auto bool_at = [](const array& a, int i) { + return slice(a, {i}, {i + 1}).item(); + }; + auto difference = subtract(x, x); // NaN for inf, -inf and NaN + auto sine = sin(x); // NaN for inf, -inf and NaN + auto nan = isnan(x); + auto inf = isinf(x); + // The other direction, float32 -> float16: an overflow, and a NaN. + auto overflow = multiply(full({64}, 65504.0f, float16), array(2.0f, float16)); + auto root = sqrt(full({64}, -1.0f, float16)); + for (int i = 0; i < 64; ++i) { + CAPTURE(i); + const bool special = i % 4 != 3; + CHECK(std::isnan(half_at(difference, i)) == special); + CHECK(std::isnan(half_at(sine, i)) == special); + CHECK(bool_at(nan, i) == (i % 4 == 2)); + CHECK(bool_at(inf, i) == (i % 4 < 2)); + CHECK(half_at(overflow, i) == INFINITY); + CHECK(std::isnan(half_at(root, i))); + } +} + +TEST_CASE("highway bf16 sin and cos of lanes past 2^23") { + // A vector with a lane past 2^23 takes std::sin and std::cos lane by lane, + // written through Simd's operator[]. Every vector here holds one. + std::vector xs(64); + for (int i = 0; i < 32; ++i) { + xs[2 * i] = std::ldexp(128.0f + 4 * i, 17); // 2^24 and up, exact in bf16 + xs[2 * i + 1] = 0.25f * (i + 1); + } + auto x = astype(array(xs.data(), {64}, float32), bfloat16); + auto sine = astype(sin(x), float32); + auto cosine = astype(cos(x), float32); + for (int i = 0; i < 64; ++i) { + CAPTURE(xs[i]); + const float s = slice(sine, {i}, {i + 1}).item(); + const float c = slice(cosine, {i}, {i + 1}).item(); + CHECK(std::abs(s - std::sin(xs[i])) < 1.0f / 64); + CHECK(std::abs(c - std::cos(xs[i])) < 1.0f / 64); + } +} + +TEST_CASE("highway floor, ceil, trunc and round keep the sign of zero") { + // As in C, each result has its input's sign, zeros included. 16 values fill + // whole vectors at every target, so no lane takes the scalar path. + std::vector xs; + for (float v : {0.0f, 0.25f, 0.5f, 0.75f, 1.0f, 1.5f, 2.5f, 3.75f}) { + xs.push_back(-v); + xs.push_back(v); + } + struct Rounding { + std::string name; + array (*mlx)(const array&); + double (*c)(double); + }; + const Rounding roundings[] = { + {"floor", + [](const array& a) { return floor(a); }, + [](double v) { return std::floor(v); }}, + {"ceil", + [](const array& a) { return ceil(a); }, + [](double v) { return std::ceil(v); }}, + {"trunc", + [](const array& a) { return trunc(a); }, + [](double v) { return std::trunc(v); }}, + {"round", + [](const array& a) { return round(a); }, + [](double v) { return std::rint(v); }}}; + auto element = [](const array& a, int i) -> double { + auto e = slice(a, {i}, {i + 1}); + if (a.dtype() == float16) { + return static_cast(e.item()); + } else if (a.dtype() == bfloat16) { + return static_cast(e.item()); + } else if (a.dtype() == float32) { + return e.item(); + } + return e.item(); + }; + const int n = static_cast(xs.size()); + for (auto dtype : {float32, float64, bfloat16, float16}) { + auto x = array(xs.begin(), {n}, dtype); + for (const auto& r : roundings) { + auto y = r.mlx(x); + for (int i = 0; i < n; ++i) { + const double got = element(y, i); + const double want = r.c(xs[i]); + CAPTURE(r.name); + CAPTURE(dtype); + CAPTURE(xs[i]); + CAPTURE(got); + CAPTURE(want); + CHECK(got == want); + CHECK(std::signbit(got) == std::signbit(want)); + } + } + } +} + +TEST_CASE("highway fp32 matmul splits short inputs by columns, exactly") { + namespace hi = mlx::core::cpu::highway_info; + const int k = 256; + // M * N * K >= 65536 for every m below. 1003 columns do not divide evenly + // among 8 threads, so the last slice is short. + const int n = 1003; + for (int m : {1, 3, 8, 15}) { + for (bool a_t : {false, true}) { + for (bool b_t : {false, true}) { + CAPTURE(m); + CAPTURE(a_t); + CAPTURE(b_t); + auto a = random::normal( + a_t ? Shape{k, m} : Shape{m, k}, + float32, + 0.0f, + 1.0f, + random::key(m)); + auto b = random::normal( + b_t ? Shape{n, k} : Shape{k, n}, + float32, + 0.0f, + 1.0f, + random::key(100 + m)); + auto lhs = a_t ? transpose(a) : a; + auto rhs = b_t ? transpose(b) : b; + hi::reset_stats(); + auto y = matmul(lhs, rhs); + CHECK(within_sum_bound(y, lhs, rhs, k + 2)); + if (cpu::ThreadPool::instance().max_threads() > 1) { + CHECK(hi::sgemm_column_splits() > 0); + } + } + } + } +} + +TEST_CASE("highway scratch past 64 MiB is freed after its operation") { + // M >= 32 dequantizes W to float32 scratch. 9216 x 2048 floats are 75.5 MB on + // their own, above the 64 MiB the lease keeps, whatever else the path stages. + auto w = random::normal({9216, 2048}, float32, 0.0f, 0.02f, random::key(41)); + auto q = quantize(w, 64, 4); + auto x = random::normal({64, 2048}, float32, 0.0f, 1.0f, random::key(42)); + const size_t before = cpu::scratch_retained_bytes(); + CHECK( + sum(quantized_matmul(x, q[0], q[1], q[2], true, 64, 4)).item() != + 0.0f); + const size_t after_large = cpu::scratch_retained_bytes(); + CHECK(after_large <= before); + + // A small one keeps its buffer for the next call. + auto ws = random::normal({64, 256}, float32, 0.0f, 1.0f, random::key(43)); + auto qs = quantize(ws, 64, 4); + auto xs = random::normal({32, 256}, float32, 0.0f, 1.0f, random::key(44)); + CHECK( + sum(quantized_matmul(xs, qs[0], qs[1], qs[2], true, 64, 4)) + .item() != 0.0f); + CHECK(cpu::scratch_retained_bytes() > after_large); +} + +TEST_CASE("highway scratch leases do not nest on one thread") { + std::vector buffer; + { + cpu::ScratchLease first(buffer, 16); + // A second lease could reallocate the buffer under the first. + CHECK_THROWS_AS(cpu::ScratchLease(buffer, 1 << 20), std::logic_error); + CHECK(buffer.size() == 16); + } + CHECK_NOTHROW(cpu::ScratchLease(buffer, 16)); +} diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp new file mode 100644 index 0000000000..2d51a699e2 --- /dev/null +++ b/tests/highway_quantized_tests.cpp @@ -0,0 +1,162 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/precision.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +// |got - x w^T| <= c * eps32 * sum |x| (|s| q + |b|), in float64: the kernels +// sum s * sum(x q) + b * sum(x) per group, so |s| and |b| bound their rounding. +bool within_quantized_bound( + const array& got, + const array& x, + const std::vector& q, + int group_size, + int bits, + double c) { + auto x64 = astype(x, float64); + auto w64 = astype(dequantize(q[0], q[1], q[2], group_size, bits), float64); + auto w_abs = + astype(dequantize(q[0], abs(q[1]), abs(q[2]), group_size, bits), float64); + auto reference = matmul(x64, transpose(w64)); + auto magnitude = matmul(abs(x64), transpose(w_abs)); + auto bound = multiply( + array(c * std::numeric_limits::epsilon(), float64), magnitude); + return all(less_equal(abs(subtract(astype(got, float64), reference)), bound)) + .item(); +} + +// max |got - reference| / max |reference|, both widened to float32. +float relative_error(const array& got, const array& reference) { + auto g = astype(got, float32); + auto r = astype(reference, float32); + return (max(abs(subtract(g, r))) / max(abs(r))).item(); +} + +} // namespace + +TEST_CASE("highway affine 3, 5 and 6-bit matmul at every row count") { + // #3019 sent every transposed call with M >= 32 to a dequantize-then-SGEMM + // path that reads 32 / bits values per word: wrong for byte-packed widths. + auto w = random::normal({256, 512}, float32, 0.0f, 1.0f, random::key(5)); + for (int bits : {3, 5, 6}) { + for (int group_size : {32, 64, 128}) { + auto q = quantize(w, group_size, bits); + for (int rows : {1, 31, 32, 33, 64}) { + CAPTURE(bits); + CAPTURE(group_size); + CAPTURE(rows); + auto x = + random::normal({rows, 512}, float32, 0.0f, 1.0f, random::key(rows)); + auto y = quantized_matmul(x, q[0], q[1], q[2], true, group_size, bits); + CHECK(within_quantized_bound(y, x, q, group_size, bits, 512 + 2)); + } + } + } +} + +TEST_CASE("highway gather_qmm merges experts without the byte-packing bug") { + // _bs_qmm_dispatch_typed merges consecutive rows of one expert into a single + // call with M * batch rows, which reaches the M >= 32 path. + auto w = random::normal({2, 64, 256}, float32, 0.0f, 1.0f, random::key(11)); + auto q = quantize(w, 64, 6); + auto w_hat = dequantize(q[0], q[1], q[2], 64, 6); + auto x = random::normal({40, 1, 256}, float32, 0.0f, 1.0f, random::key(12)); + auto experts = zeros({40}, uint32); + auto y = gather_qmm(x, q[0], q[1], q[2], std::nullopt, experts, true, 64, 6); + auto reference = matmul(x, transpose(take(w_hat, experts, 0), {0, 2, 1})); + CHECK(relative_error(y, reference) < 1e-5f); +} + +namespace { + +// `values` through qqmm against a quantized identity, which quantizes exactly, +// so it returns them as QQMatmul rounded them. +std::vector through_qqmm( + const std::vector& values, + const std::string& mode, + int bits) { + const int k = static_cast(values.size()); + auto x = array(values.data(), {1, k}, float32); + auto identity = eye(k, float32); + auto qw = quantize(identity, 32, bits, mode); + auto y = qqmm(x, qw[0], qw[1], 32, bits, mode); + std::vector out(k); + for (int i = 0; i < k; ++i) { + out[i] = slice(y, {0, i}, {1, i + 1}).item(); + } + return out; +} + +} // namespace + +TEST_CASE("highway mxfp8 reads an E8M0 scale of 0xFF as NaN") { + auto s = Device::cpu; + auto w = view(full({8, 64}, 1, uint8, s), uint32, s); + auto scales = full({8, 2}, 0xFF, uint8, s); + auto d = dequantize( + w, scales, std::nullopt, 32, 8, "mxfp8", std::nullopt, std::nullopt, s); + CHECK(all(isnan(d, s), s).item()); + auto x = ones({1, 64}, float32, s); + auto y = + quantized_matmul(x, w, scales, std::nullopt, true, 32, 8, "mxfp8", s); + CHECK(all(isnan(y, s), s).item()); +} + +TEST_CASE("highway qqmm mxfp4 rounds half to even on the e2m1 grid") { + // amax 6.0 gives an exact E8M0 scale of 1, so each value is rounded alone. + // Ties go to the even mantissa, as upstream's to_fp4_e2m1 does. + std::vector values = { + 0.25f, 0.75f, 1.25f, 1.75f, 2.5f, 3.5f, 5.0f, 6.0f}; + values.resize(32, 0.0f); + auto out = through_qqmm(values, "mxfp4", 4); + std::vector expected = { + 0.0f, 1.0f, 1.0f, 2.0f, 2.0f, 4.0f, 4.0f, 6.0f}; + for (int i = 0; i < 8; ++i) { + CAPTURE(values[i]); + CHECK(out[i] == expected[i]); + } +} + +TEST_CASE("highway qqmm mxfp8 rounds the block scale up") { + // amax / 448 = 1.3: scale 1 would saturate 582.4 to 448. Scale 2 gives 291.2, + // which E4M3 rounds to 288, so it returns as 576. + std::vector values(32, 1.0f); + values[0] = 582.4f; + auto out = through_qqmm(values, "mxfp8", 8); + CHECK(out[0] == 576.0f); +} + +TEST_CASE("highway quantized matmul is exact unless int8 is switched on") { + // One activation row, affine 4-bit, group 64, K 256: every condition of the + // int8 path holds, so only the switch decides. + auto w = random::normal({64, 256}, float32, 0.0f, 1.0f, random::key(21)); + auto x = random::normal({1, 256}, float32, 0.0f, 1.0f, random::key(22)); + auto q = quantize(w, 64, 4); + + REQUIRE_FALSE(cpu::quantized_int8()); + auto exact = quantized_matmul(x, q[0], q[1], q[2], true, 64, 4); + CHECK(within_quantized_bound(exact, x, q, 64, 4, 256 + 2)); + + cpu::detail::QuantizedInt8Scope on(true); + auto rounded = quantized_matmul(x, q[0], q[1], q[2], true, 64, 4); + // Rounding activations to int8 costs about 1/254 per element: far outside + // the fp32 bound. If this passes, the int8 path did not run. + CHECK_FALSE(within_quantized_bound(rounded, x, q, 64, 4, 256 + 2)); +} + +TEST_CASE("highway int8 switch parses its variable") { + // As env::get_var reads MLX's variables: an integer, and nonzero is on. + CHECK(cpu::detail::parse_quantized_int8("1")); + CHECK(cpu::detail::parse_quantized_int8("2")); + CHECK_FALSE(cpu::detail::parse_quantized_int8(nullptr)); + CHECK_FALSE(cpu::detail::parse_quantized_int8("0")); + CHECK_FALSE(cpu::detail::parse_quantized_int8("")); + CHECK_FALSE(cpu::detail::parse_quantized_int8("yes")); + CHECK(cpu::quantized_int8_available()); +} diff --git a/tests/highway_simd_tests.cpp b/tests/highway_simd_tests.cpp new file mode 100644 index 0000000000..95fe571902 --- /dev/null +++ b/tests/highway_simd_tests.cpp @@ -0,0 +1,98 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/simd/simd.h" + +using namespace mlx::core; + +// Called by the block sum tests in ops_tests.cpp. +int highway_float_lanes() { + return simd::max_size; +} + +float highway_reduce_sum(const float* lanes) { + return simd::sum(simd::load>(lanes)); +} + +namespace { + +// A lane's bits in hexadecimal; a float as hexfloat, subnormals included. +template +std::string text(T value) { + std::ostringstream out; + if constexpr (std::is_floating_point_v) { + out << std::hexfloat << value; + } else { + out << "0x" << std::hex << +static_cast>(value); + } + return out.str(); +} + +// Vector r holds values[(r + i) % 8] in lane i, so each value meets each lane. +template +void check_each_lane(const std::string& type, const T (&values)[8]) { + for (int r = 0; r < 8; ++r) { + T lanes[N]; + for (int i = 0; i < N; ++i) { + lanes[i] = values[(r + i) % 8]; + } + const simd::Simd got(simd::load(lanes)); + for (int i = 0; i < N; ++i) { + CAPTURE(type); + CAPTURE(N); + CAPTURE(i); + CAPTURE(text(lanes[i])); + CHECK(got[i] == static_cast(lanes[i])); + } + } +} + +} // namespace + +TEST_CASE("highway Simd of an integer vector reads each lane as bool") { + const uint8_t u8[8] = {0x01, 0x80, 0x7F, 0x00, 0x02, 0x40, 0xFF, 0x10}; + // Every width of Simd the facade defines. + check_each_lane("uint8_t", u8); + check_each_lane("uint8_t", u8); + check_each_lane>("uint8_t", u8); + check_each_lane("uint8_t", u8); + const uint32_t u32[8] = { + 1, 0x80000000, 0x7FFFFFFF, 0, 2, 0x40000000, 0xFFFFFFFF, 0x10}; + check_each_lane>("uint32_t", u32); + const int32_t i32[8] = {1, INT32_MIN, INT32_MAX, 0, 2, 0x40000000, -1, 0x10}; + check_each_lane>("int32_t", i32); +} + +TEST_CASE("highway Simd of a float vector reads each lane as bool") { + // As in C++, -0.0 is false and NaN is true. + using F = std::numeric_limits; + const float f32[8] = { + 1.0f, + -0.0f, + F::quiet_NaN(), + 0.0f, + 2.0f, + -1.0f, + F::infinity(), + F::denorm_min()}; + check_each_lane>("float", f32); + using D = std::numeric_limits; + const double f64[8] = { + 1.0, + -0.0, + D::quiet_NaN(), + 0.0, + 2.0, + -1.0, + D::infinity(), + D::denorm_min()}; + check_each_lane>("double", f64); +} diff --git a/tests/highway_threading_tests.cpp b/tests/highway_threading_tests.cpp new file mode 100644 index 0000000000..7e093963bd --- /dev/null +++ b/tests/highway_threading_tests.cpp @@ -0,0 +1,482 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/mlx.h" + +using namespace mlx::core; + +#if defined(__linux__) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/backend/cpu/threading/config.h" + +namespace d = mlx::core::cpu::detail; + +TEST_CASE("highway MLX_CPU_THREADS takes a positive integer") { + std::string error; + CHECK(d::parse_thread_count("8", error) == 8); + CHECK(error.empty()); + for (const char* bad : {"0", "-3", "eight", "", "4x", "99999"}) { + CAPTURE(std::string(bad)); + std::string e; + CHECK_FALSE(d::parse_thread_count(bad, e).has_value()); + CHECK_FALSE(e.empty()); + } + std::string unset; + CHECK_FALSE(d::parse_thread_count(nullptr, unset).has_value()); + CHECK(unset.empty()); +} + +TEST_CASE("highway cgroup cpu.max becomes whole CPUs, rounded down") { + CHECK_FALSE(d::parse_cpu_max("max 100000").has_value()); + CHECK(d::parse_cpu_max("200000 100000") == 2); + CHECK(d::parse_cpu_max("150000 100000") == 1); + CHECK(d::parse_cpu_max("50000 100000") == 1); + CHECK(d::parse_cpu_max("400000 100000\n") == 4); + CHECK_FALSE(d::parse_cpu_max("garbage").has_value()); +} + +TEST_CASE( + "highway cgroup limit: the tightest cpu.max on the path to the root") { + namespace fs = std::filesystem; + const auto stamp = + std::chrono::steady_clock::now().time_since_epoch().count(); + const auto root = + fs::temp_directory_path() / ("mlx-cgroup-" + std::to_string(stamp)); + fs::create_directories(root / "a" / "b"); + std::ofstream(root / "a" / "cpu.max") << "300000 100000\n"; + std::ofstream(root / "a" / "b" / "cpu.max") << "max 100000\n"; + CHECK(d::cgroup_cpu_limit(root.string(), "0::/a/b\n") == 3); + CHECK_FALSE(d::cgroup_cpu_limit(root.string(), "0::/\n").has_value()); + // Not absolute, and cgroup v1 only: no limit, and no endless walk. + CHECK_FALSE(d::cgroup_cpu_limit(root.string(), "0::a/b\n").has_value()); + CHECK_FALSE(d::cgroup_cpu_limit(root.string(), "12:cpu:/a\n").has_value()); + std::ofstream(root / "a" / "b" / "cpu.max") << "150000 100000\n"; + CHECK(d::cgroup_cpu_limit(root.string(), "0::/a/b\n") == 1); + fs::remove_all(root); +} + +TEST_CASE("highway physical cores are counted within the affinity mask") { + // Two cores with two SMT siblings each: CPUs 0 and 1 share a core. + d::Topology smt = [](int cpu) -> std::optional> { + return std::make_pair(0, cpu / 2); + }; + CHECK(d::count_physical_cores({0, 1, 2, 3}, smt) == 2); + CHECK(d::count_physical_cores({0, 2}, smt) == 2); + CHECK(d::count_physical_cores({0, 1}, smt) == 1); + d::Topology unknown = [](int) -> std::optional> { + return std::nullopt; + }; + CHECK(d::count_physical_cores({0, 1, 2}, unknown) == 3); +} + +TEST_CASE("highway cores are told apart by the CPUs they hold") { + namespace fs = std::filesystem; + const auto stamp = + std::chrono::steady_clock::now().time_since_epoch().count(); + const auto root = + fs::temp_directory_path() / ("mlx-topology-" + std::to_string(stamp)); + // cpu/topology/ holds , as sysfs shows it. + auto write = [&](int cpu, const char* file, const std::string& value) { + const auto dir = root / ("cpu" + std::to_string(cpu)) / "topology"; + fs::create_directories(dir); + std::ofstream(dir / file) << value << "\n"; + }; + // Two clusters of four cores; core_id restarts in each. + for (int cpu = 0; cpu < 8; ++cpu) { + write(cpu, "physical_package_id", "0"); + write(cpu, "cluster_id", std::to_string(cpu / 4)); + write(cpu, "core_id", std::to_string(cpu % 4)); + write(cpu, "core_cpus_list", std::to_string(cpu)); + } + d::Topology topology = [&](int cpu) { + return d::sysfs_topology(root.string(), cpu); + }; + CHECK(d::count_physical_cores({0, 1, 2, 3, 4, 5, 6, 7}, topology) == 8); + CHECK(d::count_physical_cores({0, 4}, topology) == 2); + CHECK(d::sysfs_topology(root.string(), 4) == std::make_pair(0, 4)); + // SMT siblings share a list, which may be a range or a set. + for (int cpu : {8, 9}) { + write(cpu, "physical_package_id", "0"); + write(cpu, "core_id", "0"); + write(cpu, "core_cpus_list", "8-9"); + } + CHECK(d::count_physical_cores({8, 9}, topology) == 1); + CHECK(d::sysfs_topology(root.string(), 9) == std::make_pair(0, 8)); + // Before Linux 5.3 the list is thread_siblings_list. + for (int cpu : {10, 12}) { + write(cpu, "physical_package_id", "0"); + write(cpu, "core_id", "5"); + write(cpu, "thread_siblings_list", "10,12"); + } + CHECK(d::count_physical_cores({10, 12}, topology) == 1); + CHECK(d::sysfs_topology(root.string(), 12) == std::make_pair(0, 10)); + // No list: a core of its own, even with a core_id. + write(14, "physical_package_id", "0"); + write(14, "core_id", "0"); + CHECK_FALSE(d::sysfs_topology(root.string(), 14).has_value()); + CHECK_FALSE(d::sysfs_topology(root.string(), 42).has_value()); + // A real kernel's sysfs gives CPU 0 a key. + if (fs::exists( + "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list")) { + CHECK(d::sysfs_topology("/sys/devices/system/cpu", 0).has_value()); + } + fs::remove_all(root); +} + +TEST_CASE("highway pool size: the override, else the tighter limit") { + d::Topology cores = [](int cpu) -> std::optional> { + return std::make_pair(0, cpu); + }; + std::vector eight = {0, 1, 2, 3, 4, 5, 6, 7}; + auto overridden = d::resolve_thread_config("3", eight, cores, 2); + CHECK(overridden.threads == 3); + CHECK(std::string(overridden.reason) == "MLX_CPU_THREADS"); + auto quota = d::resolve_thread_config(nullptr, eight, cores, 2); + CHECK(quota.threads == 2); + CHECK(std::string(quota.reason) == "cgroup cpu.max"); + auto unlimited = + d::resolve_thread_config(nullptr, eight, cores, std::nullopt); + CHECK(unlimited.threads == 8); + CHECK(std::string(unlimited.reason) == "physical cores"); + auto bad = d::resolve_thread_config("zero", eight, cores, std::nullopt); + CHECK(bad.threads == 8); + CHECK_FALSE(bad.error.empty()); +} + +TEST_CASE("highway pool rethrows a worker's exception and stays usable") { + auto& pool = cpu::ThreadPool::instance(); + const int n = pool.max_threads(); + if (n < 2) { + return; // with one thread, no task runs on a worker + } + CHECK_THROWS_WITH_AS( + pool.parallel_for( + n, + [](int tid, int nth) { + if (tid == nth - 1) { + throw std::runtime_error("worker failed"); + } + }), + "worker failed", + std::runtime_error); + std::atomic slots{0}; + pool.parallel_for(n, [&](int, int) { slots.fetch_add(1); }); + CHECK(slots.load() == n); +} + +TEST_CASE("highway pool waits for every slot when slot 0 throws") { + auto& pool = cpu::ThreadPool::instance(); + const int n = pool.max_threads(); + if (n < 2) { + return; + } + // Slot 0 runs on the calling thread. If its exception unwinds at once, the + // workers are still running the task, and `finished` is short. + std::atomic finished{0}; + CHECK_THROWS_AS( + pool.parallel_for( + n, + [&](int tid, int) { + if (tid == 0) { + throw std::runtime_error("slot 0 failed"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + finished.fetch_add(1); + }), + std::runtime_error); + CHECK(finished.load() == n - 1); +} + +TEST_CASE("highway nested parallel_for runs its range inline") { + auto& pool = cpu::ThreadPool::instance(); + const int n = std::max(2, pool.max_threads()); + const int outer_slots = std::min(n, pool.max_threads()); + std::vector> hits(64); + pool.parallel_for(n, [&](int, int) { + pool.parallel_for(n, [&](int tid, int nth) { + for (int i = tid; i < 64; i += nth) { + hits[i].fetch_add(1); + } + }); + }); + for (auto& h : hits) { + CHECK(h.load() == outer_slots); + } +} + +TEST_CASE("highway pool pins OpenBLAS at every pool size") { + const int pool = cpu::ThreadPool::instance().max_threads(); + if (!cpu::openblas_present()) { + MESSAGE("skipped: the linked BLAS has no openblas_set_num_threads"); + return; + } + CAPTURE(pool); + CHECK(cpu::openblas_pinned()); +#if defined(__linux__) + // Ask OpenBLAS itself, not the flag stored next to the call. + using GetThreads = int (*)(); + auto get = reinterpret_cast( + dlsym(RTLD_DEFAULT, "openblas_get_num_threads")); + REQUIRE(get != nullptr); + CHECK(get() == 1); +#endif +} + +TEST_CASE("highway pool size agrees with the thread configuration") { + const auto& config = cpu::thread_config(); + const int pool = cpu::ThreadPool::instance().max_threads(); + MESSAGE( + "threads " << config.threads << " (" << std::string(config.reason) + << "), pool " << pool); + // The pool clamps to MAX_WORKERS + 1 (thread_pool.h; 129 in #3019). + CHECK(pool == std::min(config.threads, 129)); +} + +namespace { + +using Clock = std::chrono::steady_clock; +using std::chrono::milliseconds; +using std::chrono::seconds; + +// Runs `call` on a new thread and waits at most `limit` for it. If the call +// does not return, its thread stays: what the call uses must stay too. +bool returns_within(std::function call, seconds limit) { + auto returned = std::make_shared>(); + auto future = returned->get_future(); + std::thread caller([call = std::move(call), returned] { + call(); + returned->set_value(); + }); + if (future.wait_for(limit) != std::future_status::ready) { + caller.detach(); + return false; + } + caller.join(); + return true; +} + +// Holds a worker after it told the pool that it is ready, until the first +// call runs its slot 0. +struct LateWorker { + std::mutex mtx; + std::condition_variable cv; + bool first_call = false; + int held = 0; + std::atomic slots{0}; +} late; + +void hold_after_ready(d::PoolTestPoint point, int) { + if (point != d::PoolTestPoint::AfterReady) { + return; + } + std::unique_lock lk(late.mtx); + ++late.held; + late.cv.wait_for(lk, seconds(2), [] { return late.first_call; }); +} + +// The slots of one call, as they ran. Static: a call that returns too early +// must not free what its slots still use. +struct SlotLog { + void reset(int slots) { + n = slots; + for (auto& r : runs) { + r = 0; + } + wrong = 0; + wrong_tid = -1; + wrong_nth = -1; + finished = 0; + at_return = -1; + } + void ran(int tid, int nth) { + if (tid < 0 || tid >= n || nth != n) { + wrong_tid = tid; + wrong_nth = nth; + wrong.fetch_add(1); + } else { + runs[tid].fetch_add(1); + } + finished.fetch_add(1); + } + int n = 0; + std::atomic runs[8]; + std::atomic wrong{0}; + std::atomic wrong_tid{-1}; + std::atomic wrong_nth{-1}; + std::atomic finished{0}; + int at_return = -1; +} first_log, second_log; + +// Worker 2 gets no wake flag for either call below: it wakes from its sleep +// for the first call, and the hook holds its claim until the second call runs. +constexpr int kStaleWorker = 2; +struct StaleClaim { + std::mutex mtx; + std::condition_variable cv; + // 0: off. 1: first call. 2: second call next. 3: worker 2 may go. 4: all. + int phase = 0; + bool held = false; + Clock::time_point deadline; +} stale; + +void set_phase(int phase) { + std::lock_guard lk(stale.mtx); + stale.phase = phase; + stale.cv.notify_all(); +} + +void hold_stale_claim(d::PoolTestPoint point, int worker) { + if (point != d::PoolTestPoint::BeforeClaim) { + return; + } + std::unique_lock lk(stale.mtx); + if (stale.phase == 1 && worker == kStaleWorker && !stale.held) { + stale.held = true; + stale.cv.notify_all(); + stale.cv.wait_for( + lk, seconds(5), [] { return stale.phase == 0 || stale.phase >= 3; }); + } else if (stale.phase == 1 && worker != kStaleWorker) { + // Worker 2 must see a free slot of the first call. + stale.cv.wait_until( + lk, stale.deadline, [] { return stale.held || stale.phase != 1; }); + } else if ((stale.phase == 2 || stale.phase == 3) && worker != kStaleWorker) { + // The second call's other claims come after the held claim. + stale.cv.wait_for( + lk, seconds(5), [] { return stale.phase == 0 || stale.phase >= 4; }); + } +} + +void check_log(const SlotLog& log, const std::string& call) { + INFO("the " << call << " call, " << log.n << " slots"); + CHECK_MESSAGE( + log.wrong.load() == 0, + "slot " << log.wrong_tid.load() << " ran with nth " + << log.wrong_nth.load()); + for (int t = 0; t < log.n; ++t) { + CHECK_MESSAGE( + log.runs[t].load() == 1, + "slot " << t << " ran " << log.runs[t].load() << " times"); + } + CHECK_MESSAGE( + log.at_return == log.n, + "parallel_for returned after " << log.at_return << " slots finished"); +} + +} // namespace + +TEST_CASE( + "highway pool worker delayed after announcing ready takes the first call") { + { + std::lock_guard lk(late.mtx); + late.first_call = false; + late.held = 0; + } + late.slots = 0; + d::set_pool_test_hook(hold_after_ready); + auto pool = d::make_thread_pool(2); // One worker. + auto* p = pool.get(); + const bool returned = returns_within( + [p] { + p->parallel_for(2, [](int tid, int) { + if (tid == 0) { + std::lock_guard lk(late.mtx); + late.first_call = true; + late.cv.notify_all(); + } + late.slots.fetch_add(1); + }); + }, + seconds(5)); + d::set_pool_test_hook(nullptr); + CHECK_MESSAGE(returned, "the first parallel_for did not return in 5 s"); + if (!returned) { + (void)pool.release(); // Its call still waits for the worker. + return; + } + CHECK(late.slots.load() == 2); + std::lock_guard lk(late.mtx); + CHECK(late.held == 1); +} + +TEST_CASE("highway pool claim delayed past its call does not run in the next") { + const int calls[2][2] = {{3, 2}, {2, 3}}; + for (const auto& c : calls) { + const int n1 = c[0]; + const int n2 = c[1]; + CAPTURE(n1); + CAPTURE(n2); + bool held = false; + for (int attempt = 0; attempt < 5 && !held; ++attempt) { + auto pool = d::make_thread_pool(4); // Workers 0, 1 and 2. + std::this_thread::sleep_for(milliseconds(100)); // Let them all sleep. + { + std::lock_guard lk(stale.mtx); + stale.phase = 1; + stale.held = false; + stale.deadline = Clock::now() + seconds(1); + } + first_log.reset(n1); + second_log.reset(n2); + d::set_pool_test_hook(hold_stale_claim); + auto* p = pool.get(); + bool returned = returns_within( + [p, n1] { + p->parallel_for( + n1, [](int tid, int nth) { first_log.ran(tid, nth); }); + first_log.at_return = first_log.finished.load(); + }, + seconds(10)); + { + std::lock_guard lk(stale.mtx); + held = stale.held; + } + if (returned && held) { + set_phase(2); + returned = returns_within( + [p, n2] { + p->parallel_for(n2, [](int tid, int nth) { + if (tid == 0) { + set_phase(3); // The held claim goes first. + std::this_thread::sleep_for(milliseconds(50)); + set_phase(4); + } else { + std::this_thread::sleep_for(milliseconds(20)); + } + second_log.ran(tid, nth); + }); + second_log.at_return = second_log.finished.load(); + }, + seconds(10)); + } + d::set_pool_test_hook(nullptr); + set_phase(0); + CHECK_MESSAGE(returned, "a parallel_for did not return in 10 s"); + if (!returned) { + (void)pool.release(); // A call still waits in it. + return; + } + check_log(first_log, "first"); + if (held) { + check_log(second_log, "second"); + } + } + CHECK_MESSAGE(held, "no attempt held a claim of the first call"); + } +} diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index ea39d95cf1..9f7b38f3db 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -17,6 +17,12 @@ using namespace mlx::core; +#if defined(MLX_USE_HIGHWAY_KERNELS) +// In highway_simd_tests.cpp: simd.h declares a global bfloat16_t on arm64. +int highway_float_lanes(); +float highway_reduce_sum(const float* lanes); +#endif + TEST_CASE("test copy") { array x(1.0); auto y = copy(x); @@ -7152,6 +7158,468 @@ TEST_CASE("roll and tile shape overflow") { CHECK(array_equal(rolled, x).item()); } +TEST_CASE("test integer floor_divide and remainder by zero in whole vectors") { + // 67 elements give whole vectors at the build's static target, then a + // scalar tail; 67 covers widths up to 16. Zero divisors sit in both. + StreamOrDevice cpu = Device::cpu; + std::vector an(67), as(67), bs(67); + for (int i = 0; i < 67; ++i) { + an[i] = (7 * i + 3) % 100; + as[i] = (i % 2 == 0 ? 1 : -1) * an[i]; + bs[i] = (i % 8 == 5 || i == 65) ? 0 : (i % 3 == 0 ? -3 : 5); + } + auto apply = [cpu](int op, const array& a, const array& b) { + return op == 0 ? floor_divide(a, b, cpu) : remainder(a, b, cpu); + }; + // The integer types that have Highway vectors. + std::vector> types = { + {"int32", int32}, {"uint32", uint32}, {"uint8", uint8}}; + for (const auto& type : types) { + const std::string& name = type.first; + Dtype t = type.second; + CAPTURE(name); + auto a = astype(array(as.begin(), {67}), t, cpu); + auto n = astype(array(an.begin(), {67}), t, cpu); + auto b = astype(array(bs.begin(), {67}), t, cpu); + auto zero = equal(b, array(0, t), cpu); + // As base_simd.h: a remainder by zero is the dividend, and a quotient by + // zero is 0 (floor_divide adjusts it for a negative dividend). + CHECK(array_equal(where(zero, remainder(a, b, cpu), a, cpu), a, cpu) + .item()); + CHECK(array_equal( + where(zero, floor_divide(n, b, cpu), array(0, t), cpu), + zeros({67}, t, cpu), + cpu) + .item()); + for (int op = 0; op < 2; ++op) { + auto whole = apply(op, a, b); + for (int i = 0; i < 67; ++i) { + CAPTURE(op); + CAPTURE(i); + auto one = + apply(op, slice(a, {i}, {i + 1}, cpu), slice(b, {i}, {i + 1}, cpu)); + CHECK(array_equal(slice(whole, {i}, {i + 1}, cpu), one, cpu) + .item()); + } + } + } +} + +TEST_CASE( + "test fp8 weights and nvfp4 scales give NaN for 0x7F and 0xFF in matmuls") { + StreamOrDevice cpu = Device::cpu; + // mxfp8: eight rows of 64 E4M3 codes (two groups of 32), scales of 1 (E8M0 + // 127). Row 0 holds 0x7F at column 5, row 1 holds 0xFF at column 40. + std::vector codes(8 * 64); + for (int i = 0; i < 8 * 64; ++i) { + codes[i] = static_cast((i * 37) % 0x7E); + } + codes[5] = 0x7F; + codes[64 + 40] = 0xFF; + auto w = view(array(codes.begin(), {8, 64}, uint8), uint32, cpu); + auto scales = full({8, 2}, 127, uint8, cpu); + for (int m : {1, 32}) { + CAPTURE(m); + auto y = quantized_matmul( + ones({m, 64}, float32, cpu), + w, + scales, + std::nullopt, + true, + 32, + 8, + "mxfp8", + cpu); + CHECK(all(isnan(slice(y, {0, 0}, {m, 2}, cpu), cpu), cpu).item()); + CHECK_FALSE( + any(isnan(slice(y, {0, 2}, {m, 8}, cpu), cpu), cpu).item()); + // dequantize does not read FP8_LUT. Every sum is a multiple of 2^-9 below + // 2^15, so float32 gives it exactly in any order. + auto ref = matmul( + ones({m, 64}, float32, cpu), + transpose( + dequantize( + w, + scales, + std::nullopt, + 32, + 8, + "mxfp8", + std::nullopt, + std::nullopt, + cpu), + cpu), + cpu); + CHECK( + array_equal( + slice(y, {0, 2}, {m, 8}, cpu), slice(ref, {0, 2}, {m, 8}, cpu), cpu) + .item()); + } + // nvfp4: E2M1 1.0 everywhere, E4M3 scales of 1 (0x38) in groups of 16, but + // 0x7F for row 0's second group and 0xFF for row 1's first. + std::vector s4(8 * 4, 0x38); + s4[1] = 0x7F; + s4[4] = 0xFF; + auto w4 = full({8, 8}, 0x22222222u, uint32, cpu); + auto sc4 = array(s4.begin(), {8, 4}, uint8); + auto y4 = quantized_matmul( + ones({1, 64}, float32, cpu), + w4, + sc4, + std::nullopt, + true, + 16, + 4, + "nvfp4", + cpu); + CHECK(all(isnan(slice(y4, {0, 0}, {1, 2}, cpu), cpu), cpu).item()); + CHECK_FALSE( + any(isnan(slice(y4, {0, 2}, {1, 8}, cpu), cpu), cpu).item()); + CHECK( + array_equal(slice(y4, {0, 2}, {1, 8}, cpu), full({1, 6}, 64.0f, cpu), cpu) + .item()); + // mxfp8: every E4M3 code but 0x7F and 0xFF (0 in their places), code c at + // row c / 64, column c % 64. Identity activations output each weight once. + std::vector finite(4 * 64); + for (int c = 0; c < 4 * 64; ++c) { + finite[c] = (c & 0x7F) == 0x7F ? 0 : static_cast(c); + } + auto wf = view(array(finite.begin(), {4, 64}, uint8), uint32, cpu); + auto sf = full({4, 2}, 127, uint8, cpu); + auto rf = astype( + dequantize( + wf, + sf, + std::nullopt, + 32, + 8, + "mxfp8", + std::nullopt, + std::nullopt, + cpu), + float32, + cpu); + auto yf = quantized_matmul( + eye(64, float32, cpu), wf, sf, std::nullopt, true, 32, 8, "mxfp8", cpu); + CHECK(array_equal(yf, transpose(rf, cpu), cpu).item()); + // Not transposed: fp_qmm decodes the weights through FP8_LUT. + auto yn = quantized_matmul( + eye(4, float32, cpu), wf, sf, std::nullopt, false, 32, 8, "mxfp8", cpu); + CHECK(array_equal(yn, rf, cpu).item()); +} + +TEST_CASE( + "test from_fp8 decodes 0x7F and 0xFF as NaN in vectors and the tail") { + // 256 codes fill whole vectors at every width up to 16; 0x7F, 0xFF and 0x80 + // follow in the scalar tail. + StreamOrDevice cpu = Device::cpu; + std::vector codes(256); + for (int i = 0; i < 256; ++i) { + codes[i] = static_cast(i); + } + codes.insert(codes.end(), {0x7F, 0xFF, 0x80}); + // E4M3: a sign, four exponent bits (bias 7), three mantissa bits. + std::vector want; + for (auto c : codes) { + int e = (c >> 3) & 15; + int m = c & 7; + float v = + e == 0 ? std::ldexp(m / 8.0f, -6) : std::ldexp(1.0f + m / 8.0f, e - 7); + if (e == 15 && m == 7) { + v = NAN; + } + want.push_back((c & 0x80) ? -v : v); + } + auto x = array(codes.begin(), {259}, uint8); + auto expected = array(want.begin(), {259}); + auto bits = [cpu](const array& a) { + return where(isnan(a, cpu), array(0u, uint32), view(a, uint32, cpu), cpu); + }; + for (auto t : {float32, float16, bfloat16}) { + auto got = astype(from_fp8(x, t, cpu), float32, cpu); + for (int i : {0x7F, 0xFF, 256, 257}) { + CAPTURE(t); + CAPTURE(i); + CHECK(std::isnan(slice(got, {i}, {i + 1}, cpu).item())); + } + // Every other code exactly, the sign of zero included. + CHECK(array_equal(isnan(got, cpu), isnan(expected, cpu), cpu).item()); + CHECK(array_equal(bits(got), bits(expected), cpu).item()); + } + // dequantize composes from_fp8: mxfp8 weights, and nvfp4 scales. + std::vector w8(8 * 64); + for (int i = 0; i < 8 * 64; ++i) { + w8[i] = static_cast((i * 37) % 0x7E); + } + w8[5] = 0x7F; + w8[64 + 40] = 0xFF; + auto deq = dequantize( + view(array(w8.begin(), {8, 64}, uint8), uint32, cpu), + full({8, 2}, 127, uint8, cpu), + std::nullopt, + 32, + 8, + "mxfp8", + std::nullopt, + float32, + cpu); + CHECK(std::isnan(slice(deq, {0, 5}, {1, 6}, cpu).item())); + CHECK(std::isnan(slice(deq, {1, 40}, {2, 41}, cpu).item())); + CHECK(astype(sum(isnan(deq, cpu), cpu), int32, cpu).item() == 2); + std::vector s4(8 * 4, 0x38); + s4[1] = 0x7F; + s4[4] = 0xFF; + auto deq4 = dequantize( + full({8, 8}, 0x22222222u, uint32, cpu), + array(s4.begin(), {8, 4}, uint8), + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + cpu); + CHECK(all(isnan(slice(deq4, {0, 16}, {1, 32}, cpu), cpu), cpu).item()); + CHECK(all(isnan(slice(deq4, {1, 0}, {2, 16}, cpu), cpu), cpu).item()); + CHECK(astype(sum(isnan(deq4, cpu), cpu), int32, cpu).item() == 32); +} + +TEST_CASE("test empty arrays in the Highway CPU kernels") { + // Each input keeps a zero-sized dimension through the collapse, or ends + // in one, so the kernels' inner extent is 0. Each pair of checks forces + // one kernel, in this order: binary, copy, rms_norm, layer_norm. + StreamOrDevice cpu = Device::cpu; + auto a = + add(transpose(zeros({0, 3, 3, 3}, float32, cpu), {2, 1, 0, 3}, cpu), + zeros({3, 3, 0, 3}, float32, cpu), + cpu); + CHECK(a.shape() == Shape{3, 3, 0, 3}); + CHECK(array_equal(a, zeros({3, 3, 0, 3}, float32, cpu), cpu).item()); + auto c = contiguous( + transpose(zeros({0, 3, 3}, float32, cpu), {1, 0, 2}, cpu), false, cpu); + CHECK(c.shape() == Shape{3, 0, 3}); + CHECK(array_equal(c, zeros({3, 0, 3}, float32, cpu), cpu).item()); + auto x = zeros({3, 0}, float32, cpu); + auto r = fast::rms_norm(x, std::nullopt, 1e-5f, cpu); + CHECK(r.shape() == Shape{3, 0}); + CHECK(array_equal(r, x, cpu).item()); + auto l = fast::layer_norm(x, std::nullopt, std::nullopt, 1e-5f, cpu); + CHECK(l.shape() == Shape{3, 0}); + CHECK(array_equal(l, x, cpu).item()); +} + +namespace { +// Sets the buffer cache limit back. With the cache off, a copy freed before +// its tasks run is freed for real, which ASan reports. +struct RestoreCacheLimit { + size_t limit; + ~RestoreCacheLimit() { + set_cache_limit(limit); + } +}; +} // namespace + +TEST_CASE("test norms of a non-contiguous input") { + // A transposed input makes the native norms copy it. + RestoreCacheLimit restore{set_cache_limit(0)}; + StreamOrDevice cpu = Device::cpu; + // Values -3 to 3 keep every sum exact, so both layouts give the same bits. + auto input = [cpu]() { + auto v = + subtract(remainder(arange(6144, cpu), array(7), cpu), array(3), cpu); + return transpose(reshape(astype(v, float32, cpu), {64, 96}, cpu), cpu); + }; + for (int i = 0; i < 50; i++) { + auto x = input(); + CHECK( + array_equal( + fast::rms_norm(x, std::nullopt, 1e-5f, cpu), + fast::rms_norm(contiguous(x, false, cpu), std::nullopt, 1e-5f, cpu), + cpu) + .item()); + auto y = input(); + CHECK(array_equal( + fast::layer_norm(y, std::nullopt, std::nullopt, 1e-5f, cpu), + fast::layer_norm( + contiguous(y, false, cpu), + std::nullopt, + std::nullopt, + 1e-5f, + cpu), + cpu) + .item()); + } +} + +TEST_CASE("test norms of a strided weight and bias") { + // A strided weight or bias must match its contiguous copy. The broadcast + // repeats one element of w2, so a stride-1 read stays in w2. + RestoreCacheLimit restore{set_cache_limit(0)}; + StreamOrDevice cpu = Device::cpu; + int width = 64; + auto v = + subtract(remainder(arange(8 * width, cpu), array(7), cpu), array(3), cpu); + auto x = reshape(astype(v, float32, cpu), {8, width}, cpu); + auto w2 = astype( + add(remainder(arange(2 * width, cpu), array(5), cpu), array(1), cpu), + float32, + cpu); + std::vector params = { + broadcast_to(slice(w2, {1}, {2}, cpu), {width}, cpu), + slice(w2, {0}, {2 * width}, {2}, cpu)}; + for (auto& p : params) { + CAPTURE(p.strides()); + auto pc = contiguous(p, false, cpu); + CHECK(array_equal( + fast::rms_norm(x, p, 1e-5f, cpu), + fast::rms_norm(x, pc, 1e-5f, cpu), + cpu) + .item()); + CHECK(array_equal( + fast::layer_norm(x, p, std::nullopt, 1e-5f, cpu), + fast::layer_norm(x, pc, std::nullopt, 1e-5f, cpu), + cpu) + .item()); + CHECK(array_equal( + fast::layer_norm(x, std::nullopt, p, 1e-5f, cpu), + fast::layer_norm(x, std::nullopt, pc, 1e-5f, cpu), + cpu) + .item()); + } +} + +TEST_CASE("test rope with strided offsets and freqs") { + // Strided offsets or freqs must match their contiguous copy. Each broadcast + // repeats one element of a wider array, so a stride-1 read stays in it. + RestoreCacheLimit restore{set_cache_limit(0)}; + StreamOrDevice cpu = Device::cpu; + auto v = subtract(remainder(arange(1024, cpu), array(7), cpu), array(3), cpu); + auto x = reshape(astype(v, float32, cpu), {4, 2, 8, 16}, cpu); + std::vector offsets = { + broadcast_to(slice(arange(8, cpu), {3}, {4}, cpu), {4}, cpu), + slice(arange(8, cpu), {0}, {8}, {2}, cpu)}; + for (auto& off : offsets) { + CAPTURE(off.strides()); + auto oc = contiguous(off, false, cpu); + CHECK(array_equal( + fast::rope(x, 16, false, 10000.0f, 1.0f, off, std::nullopt, cpu), + fast::rope(x, 16, false, 10000.0f, 1.0f, oc, std::nullopt, cpu), + cpu) + .item()); + } + auto f2 = astype( + add(remainder(arange(16, cpu), array(5), cpu), array(1), cpu), + float32, + cpu); + std::vector freqs = { + broadcast_to(slice(f2, {1}, {2}, cpu), {8}, cpu), + slice(f2, {0}, {16}, {2}, cpu)}; + for (auto& f : freqs) { + CAPTURE(f.strides()); + auto fc = contiguous(f, false, cpu); + CHECK(array_equal( + fast::rope(x, 16, false, std::nullopt, 1.0f, 0, f, cpu), + fast::rope(x, 16, false, std::nullopt, 1.0f, 0, fc, cpu), + cpu) + .item()); + } +} + +TEST_CASE("test sdpa with strided sinks") { + // Strided sinks must match their contiguous copy. The broadcast repeats one + // element of s8, so a stride-1 read stays in s8. + RestoreCacheLimit restore{set_cache_limit(0)}; + StreamOrDevice cpu = Device::cpu; + auto input = [cpu](int start, int len) { + auto a = remainder(arange(start, start + 64 * len, cpu), array(7), cpu); + auto b = astype(subtract(a, array(3), cpu), float32, cpu); + return reshape(b, {1, 4, len, 16}, cpu); + }; + auto q = input(0, 8); + auto k = input(1, 16); + auto v = input(2, 16); + auto s8 = astype(arange(-4, 4, cpu), float32, cpu); + std::vector sinks = { + broadcast_to(slice(s8, {1}, {2}, cpu), {4}, cpu), + slice(s8, {0}, {8}, {2}, cpu)}; + for (auto& sink : sinks) { + CAPTURE(sink.strides()); + auto sc = contiguous(sink, false, cpu); + CHECK(array_equal( + fast::scaled_dot_product_attention( + q, k, v, 0.0625f, "", std::nullopt, sink, false, cpu), + fast::scaled_dot_product_attention( + q, k, v, 0.0625f, "", std::nullopt, sc, false, cpu), + cpu) + .item()); + } +} + +TEST_CASE("test qqmm with an unquantized weight") { + // An unquantized w must raise quantized.cpp's error, also with scales, + // which qqmm accepts since it checks scales only for a quantized w. + StreamOrDevice cpu = Device::cpu; + int K = 64; + int N = 32; + auto x = ones({1, K}, float32, cpu); + auto w = ones({N, K}, float32, cpu); + auto with_scales = qqmm( + x, + w, + zeros({N, K / 16}, uint8, cpu), + std::nullopt, + std::nullopt, + "nvfp4", + std::nullopt, + std::nullopt, + cpu); + CHECK_THROWS_WITH_AS( + sum(with_scales, cpu).item(), + "[QQMatmul] NYI for the general case", + std::runtime_error); + auto with_global_scales = qqmm( + x, + w, + std::nullopt, + std::nullopt, + std::nullopt, + "nvfp4", + array(1.0f), + array(1.0f), + cpu); + CHECK_THROWS_WITH_AS( + sum(with_global_scales, cpu).item(), + "[QQMatmul] NYI for the general case", + std::runtime_error); + auto without_scales = qqmm( + x, + w, + std::nullopt, + std::nullopt, + std::nullopt, + "nvfp4", + std::nullopt, + std::nullopt, + cpu); + CHECK_THROWS_WITH_AS( + sum(without_scales, cpu).item(), + "[QQMatmul] NYI for the general case", + std::runtime_error); +} + +TEST_CASE("test sdpa with keys and values of different lengths") { + // Values shorter than the keys must raise the composed path's error, on a + // shape the native kernel otherwise takes. + StreamOrDevice cpu = Device::cpu; + auto q = zeros({1, 4, 8, 16}, float32, cpu); + auto k = zeros({1, 4, 16, 16}, float32, cpu); + auto v = zeros({1, 4, 12, 16}, float32, cpu); + CHECK_THROWS_AS( + fast::scaled_dot_product_attention( + q, k, v, 0.0625f, "", std::nullopt, std::nullopt, false, cpu), + std::invalid_argument); +} + namespace { // The i-th of a fixed sequence of floats in [0, 1), each with 24 random bits. @@ -7175,7 +7643,9 @@ double max_relative_error(const array& y, const std::vector& truth) { // The lanes of the CPU's float32 sums (simd::max_size): 8 with // Accelerate on arm64, else 1. -#if defined(MLX_USE_ACCELERATE) && !defined(__x86_64__) +#if defined(MLX_USE_HIGHWAY_KERNELS) +const int sum_lanes = highway_float_lanes(); +#elif defined(MLX_USE_ACCELERATE) && !defined(__x86_64__) constexpr int sum_lanes = 8; #else constexpr int sum_lanes = 1; @@ -7184,7 +7654,7 @@ constexpr int sum_lanes = 1; // The CPU's float32 sum of up to 4096 elements: one sum per lane, the lanes // halved as Apple's simd_reduce_add does, then the tail. float lane_order_sum(const std::vector& x) { - constexpr int N = sum_lanes; + const int N = sum_lanes; std::vector lanes(N, 0.0f); size_t i = 0; for (; i + N <= x.size(); i += N) { @@ -7192,12 +7662,16 @@ float lane_order_sum(const std::vector& x) { lanes[j] = lanes[j] + x[i + j]; } } +#if defined(MLX_USE_HIGHWAY_KERNELS) + float total = highway_reduce_sum(lanes.data()); +#else for (int n = N / 2; n >= 1; n /= 2) { for (int j = 0; j < n; j++) { lanes[j] = lanes[j] + lanes[j + n]; } } float total = lanes[0]; +#endif for (; i < x.size(); i++) { total = total + x[i]; } @@ -7315,6 +7789,25 @@ TEST_CASE("test layer_norm fallback over a long row on the cpu") { CHECK_LE(max_relative_error(y, truth), 1e-5); } +TEST_CASE("test rms_norm over a long row on the cpu") { + auto s = Device::cpu; + constexpr int n = 3 << 23; + std::vector v(n); + double mean_sq = 0; + for (int i = 0; i < n; i++) { + v[i] = unit_value(i) + 0.25f; + mean_sq += double(v[i]) * v[i]; + } + mean_sq /= n; + std::vector truth(n); + for (int i = 0; i < n; i++) { + truth[i] = v[i] / std::sqrt(mean_sq + 1e-5); + } + auto x = array(v.begin(), {1, n}, float32); + auto y = fast::rms_norm(x, std::nullopt, 1e-5f, s); + CHECK_LE(max_relative_error(y, truth), 1e-5); +} + TEST_CASE("test float sums of 4096 elements keep their order on the cpu") { // Each expected value takes the order of the sum before the blocks. auto s = Device::cpu; diff --git a/tests/thread_pool_tests.cpp b/tests/thread_pool_tests.cpp new file mode 100644 index 0000000000..8ccdb2b82c --- /dev/null +++ b/tests/thread_pool_tests.cpp @@ -0,0 +1,332 @@ +// Copyright © 2026 Apple Inc. + +#include +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" + +#include "mlx/backend/cpu/threading/common.h" + +using namespace mlx::core::cpu; + +TEST_CASE("thread_pool max_threads is positive") { + auto& pool = ThreadPool::instance(); + CHECK(pool.max_threads() >= 1); +} + +TEST_CASE("thread_pool parallel_for with 1 thread") { + auto& pool = ThreadPool::instance(); + int called = 0; + pool.parallel_for(1, [&](int tid, int nth) { + CHECK_EQ(tid, 0); + CHECK_EQ(nth, 1); + called++; + }); + CHECK_EQ(called, 1); +} + +TEST_CASE("thread_pool parallel_for covers all elements") { + auto& pool = ThreadPool::instance(); + const int N = 10000; + std::vector> counts(N); + for (int i = 0; i < N; i++) { + counts[i].store(0); + } + + int nth = pool.max_threads(); + pool.parallel_for(nth, [&](int tid, int nth) { + int chunk = (N + nth - 1) / nth; + int start = chunk * tid; + int end = std::min(start + chunk, N); + for (int i = start; i < end; i++) { + counts[i].fetch_add(1, std::memory_order_relaxed); + } + }); + + for (int i = 0; i < N; i++) { + CHECK_EQ(counts[i].load(), 1); + } +} + +TEST_CASE("thread_pool parallel_for with max threads") { + auto& pool = ThreadPool::instance(); + int nth_req = pool.max_threads(); + std::vector> seen(nth_req); + for (int i = 0; i < nth_req; i++) { + seen[i].store(0); + } + + pool.parallel_for(nth_req, [&](int tid, int nth) { + CHECK_EQ(nth, nth_req); + CHECK(tid >= 0); + CHECK(tid < nth); + seen[tid].fetch_add(1, std::memory_order_relaxed); + }); + + for (int i = 0; i < nth_req; i++) { + CHECK_EQ(seen[i].load(), 1); + } +} + +TEST_CASE("thread_pool parallel_for clamps n_threads to max_threads") { + auto& pool = ThreadPool::instance(); + int max_t = pool.max_threads(); + std::atomic max_nth{0}; + + pool.parallel_for(max_t + 100, [&](int tid, int nth) { + // nth should be clamped to max_threads + int cur = max_nth.load(std::memory_order_relaxed); + while (nth > cur && !max_nth.compare_exchange_weak(cur, nth)) { + } + }); + + CHECK_EQ(max_nth.load(), max_t); +} + +TEST_CASE("thread_pool parallel_for with n_threads 0 returns immediately") { + auto& pool = ThreadPool::instance(); + std::atomic called{0}; + pool.parallel_for(0, [&](int tid, int nth) { + called.fetch_add(1, std::memory_order_relaxed); + }); + // ThreadPool::parallel_for returns immediately for n_threads <= 0 + CHECK_EQ(called.load(), 0); +} + +TEST_CASE("thread_pool rapid serial parallel_for") { + auto& pool = ThreadPool::instance(); + int nth = std::min(pool.max_threads(), 4); + std::atomic total{0}; + + for (int iter = 0; iter < 10000; iter++) { + pool.parallel_for(nth, [&](int tid, int nth) { + total.fetch_add(1, std::memory_order_relaxed); + }); + } + + CHECK_EQ(total.load(), 10000 * nth); +} + +TEST_CASE("thread_pool rapid max-thread parallel_for") { + auto& pool = ThreadPool::instance(); + int nth = pool.max_threads(); + const int ITERS = 5000; + std::atomic total{0}; + + for (int iter = 0; iter < ITERS; iter++) { + pool.parallel_for(nth, [&](int tid, int nth) { + total.fetch_add(1, std::memory_order_relaxed); + }); + } + + CHECK_EQ(total.load(), ITERS * nth); +} + +TEST_CASE("thread_pool rapid varying max-thread counts") { + auto& pool = ThreadPool::instance(); + int max_t = pool.max_threads(); + if (max_t < 2) { + return; + } + + int counts[] = { + max_t, + std::min(max_t, 2), + max_t, + std::max(2, max_t / 2), + max_t, + std::min(max_t, 3), + max_t}; + const int ITERS = 2000; + std::atomic total{0}; + std::vector> seen(max_t); + + for (int iter = 0; iter < ITERS; iter++) { + for (int nth : counts) { + for (int i = 0; i < max_t; i++) { + seen[i].store(0, std::memory_order_relaxed); + } + pool.parallel_for(nth, [&](int tid, int nth) { + seen[tid].fetch_add(1, std::memory_order_relaxed); + total.fetch_add(1, std::memory_order_relaxed); + }); + for (int i = 0; i < max_t; i++) { + int expected_seen = i < nth ? 1 : 0; + int actual_seen = seen[i].load(std::memory_order_relaxed); + if (actual_seen != expected_seen) { + INFO("iter=", iter, " nth=", nth, " tid=", i); + CHECK_EQ(actual_seen, expected_seen); + return; + } + } + } + } + + int expected = 0; + for (int nth : counts) { + expected += nth; + } + CHECK_EQ(total.load(), ITERS * expected); +} + +TEST_CASE("thread_pool lopsided work") { + auto& pool = ThreadPool::instance(); + int nth = std::min(pool.max_threads(), 4); + if (nth < 2) { + return; // Need at least 2 threads for this test + } + + std::atomic done_count{0}; + + pool.parallel_for(nth, [&](int tid, int nth) { + if (tid == 0) { + // Simulate heavy work on thread 0 + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + done_count.fetch_add(1, std::memory_order_relaxed); + }); + + CHECK_EQ(done_count.load(), nth); +} + +TEST_CASE("thread_pool concurrent parallel_for from multiple threads") { + auto& pool = ThreadPool::instance(); + const int N_CALLERS = 4; + const int ITERS = 1000; + int nth = std::min(pool.max_threads(), 4); + + std::atomic total{0}; + + std::vector callers; + callers.reserve(N_CALLERS); + for (int c = 0; c < N_CALLERS; c++) { + callers.emplace_back([&] { + for (int i = 0; i < ITERS; i++) { + pool.parallel_for(nth, [&](int tid, int nth) { + total.fetch_add(1, std::memory_order_relaxed); + }); + } + }); + } + + for (auto& t : callers) { + t.join(); + } + + CHECK_EQ(total.load(), N_CALLERS * ITERS * nth); +} + +TEST_CASE( + "thread_pool concurrent max-thread parallel_for from multiple threads") { + auto& pool = ThreadPool::instance(); + const int N_CALLERS = 4; + const int ITERS = 250; + int nth = pool.max_threads(); + + std::atomic total{0}; + + std::vector callers; + callers.reserve(N_CALLERS); + for (int c = 0; c < N_CALLERS; c++) { + callers.emplace_back([&] { + for (int i = 0; i < ITERS; i++) { + pool.parallel_for(nth, [&](int tid, int nth) { + total.fetch_add(1, std::memory_order_relaxed); + }); + } + }); + } + + for (auto& t : callers) { + t.join(); + } + + CHECK_EQ(total.load(), N_CALLERS * ITERS * nth); +} + +TEST_CASE("thread_pool parallel_for with exceptions does not deadlock") { + // Current impl only propagates slot-0 exceptions, but it must not hang. + auto& pool = ThreadPool::instance(); + int nth = std::min(pool.max_threads(), 4); + + std::mutex watchdog_mtx; + std::condition_variable watchdog_cv; + bool finished = false; + + std::thread watchdog([&] { + std::unique_lock lock(watchdog_mtx); + if (!watchdog_cv.wait_for( + lock, std::chrono::seconds(5), [&] { return finished; })) { + FAIL("parallel_for deadlocked after exception"); + } + }); + + // Only throw from slot 0 (main thread) so it propagates directly + try { + pool.parallel_for(nth, [&](int tid, int nth) { + if (tid == 0) { + throw std::runtime_error("test exception"); + } + }); + } catch (const std::runtime_error&) { + // Expected + } + + { + std::lock_guard lock(watchdog_mtx); + finished = true; + } + watchdog_cv.notify_one(); + watchdog.join(); + + // Verify pool still works after exception + std::atomic count{0}; + pool.parallel_for(nth, [&](int tid, int nth) { + count.fetch_add(1, std::memory_order_relaxed); + }); + CHECK_EQ(count.load(), nth); +} + +TEST_CASE("thread_pool parallel_for with varying thread counts") { + auto& pool = ThreadPool::instance(); + int max_t = pool.max_threads(); + std::atomic total{0}; + + // Alternate between different thread counts to exercise worker wakeup + // across small and saturated dispatches. + int counts[] = {1, max_t, 2, max_t, 1, max_t}; + for (int nth : counts) { + nth = std::min(nth, max_t); + pool.parallel_for(nth, [&](int tid, int nth) { + total.fetch_add(1, std::memory_order_relaxed); + }); + } + + int expected = 0; + for (int nth : counts) { + expected += std::min(nth, max_t); + } + CHECK_EQ(total.load(), expected); +} + +TEST_CASE("thread_pool effective_threads") { + int max_t = 16; + + // Below MIN_TOTAL_ELEMENTS -> 1 thread + CHECK_EQ(effective_threads(100, max_t), 1); + CHECK_EQ(effective_threads(0, max_t), 1); + + // At threshold + CHECK_EQ( + effective_threads(MIN_TOTAL_ELEMENTS, max_t), + std::min( + static_cast(MIN_TOTAL_ELEMENTS / MIN_ELEMENTS_PER_THREAD), + max_t)); + + // Large workload -> capped by max_threads + CHECK_EQ(effective_threads(1000000000, max_t), max_t); +} diff --git a/tests/upstream_metal_kernel_tests.cpp b/tests/upstream_metal_kernel_tests.cpp index d8983198f9..90453d2ba4 100644 --- a/tests/upstream_metal_kernel_tests.cpp +++ b/tests/upstream_metal_kernel_tests.cpp @@ -84,7 +84,6 @@ TEST_CASE("test upstream Metal FP4 half and bfloat fallback numerical parity") { } TEST_CASE("test one-bit affine endpoints CPU GPU and small-K dispatch") { - REQUIRE(is_available(Device::gpu)); for (auto dtype : {float32, float16, bfloat16}) { for (int width : {64, 128}) { for (int group : {32, 64, 128}) { @@ -103,6 +102,9 @@ TEST_CASE("test one-bit affine endpoints CPU GPU and small-K dispatch") { auto input = ones({1, width}, dtype, Device::cpu); auto expected = matmul(astype(input, float32, Device::cpu), transpose(astype(weights, float32, Device::cpu), Device::cpu), Device::cpu); for (auto device : {Device::cpu, Device::gpu}) { + if (!is_available(device)) { + continue; + } CAPTURE(device); auto quantized = quantize(astype(weights, dtype, device), group, 1, "affine", std::nullopt, device); auto decoded = dequantize(quantized[0], quantized[1], quantized[2], group, 1, "affine", std::nullopt, dtype, Device::cpu);