From d921319279442672f762b819e6d6f0d55ca8d70c Mon Sep 17 00:00:00 2001 From: Daniel Hiltgen Date: Wed, 27 May 2026 18:23:46 -0700 Subject: [PATCH 01/65] Add Highway-backed x86 CPU SIMD and threading Add an x86 CPU acceleration path behind MLX_ENABLE_AVX2. The implementation uses Google Highway for the AVX2 SIMD layer, clamps the emitted x86 target set to AVX2, and links Highway statically into MLX with CMake support for either a local source checkout or FetchContent. Add a shared CPU threading abstraction with an OpenBLAS-backed persistent thread pool on Linux/Windows and an Accelerate/GCD backend on Apple platforms. The thread pool defaults to physical cores, honors MLX_CPU_THREADS, and coordinates OpenBLAS to avoid oversubscription. Vectorize the CPU paths that matter for small-model inference: affine and FP quantized matmul, dequantization, norms, RoPE, SDPA, compiled CPU kernels, softmax, reductions, unary/binary ops, copies, indexing, and fp16/bf16 GEMM helpers. CPU JIT preamble generation and runtime compiler flags include the same AVX2/BMI2/FMA/F16C and Highway definitions so fused kernels use the accelerated SIMD layer when the host supports it. Add focused tests for CPU fast paths, quantized global-scale handling, compile coverage, and thread pool behavior. (cherry picked from commit 92175519729f4f938a34ed26df979f8313b58b80) --- CMakeLists.txt | 14 + mlx.pc.in | 5 + mlx/backend/cpu/CMakeLists.txt | 97 +- mlx/backend/cpu/binary.h | 139 +- mlx/backend/cpu/compiled.cpp | 420 +++- mlx/backend/cpu/copy.cpp | 66 +- mlx/backend/cpu/gemms/cblas.cpp | 309 ++- mlx/backend/cpu/gemms/simd_bf16.cpp | 399 +++- mlx/backend/cpu/gemms/simd_fp16.cpp | 396 +++- mlx/backend/cpu/indexing.cpp | 182 +- mlx/backend/cpu/jit_compiler.cpp | 31 +- mlx/backend/cpu/make_compiled_preamble.ps1 | 18 +- mlx/backend/cpu/make_compiled_preamble.sh | 19 +- mlx/backend/cpu/norms.cpp | 765 +++++++ mlx/backend/cpu/norms_highway.cpp | 240 ++ mlx/backend/cpu/norms_highway.h | 27 + mlx/backend/cpu/quantized.cpp | 1953 ++++++++++++++--- mlx/backend/cpu/quantized.h | 64 + mlx/backend/cpu/quantized_highway.cpp | 906 ++++++++ mlx/backend/cpu/quantized_highway.h | 296 +++ mlx/backend/cpu/reduce.cpp | 118 +- mlx/backend/cpu/rope.cpp | 565 +++++ mlx/backend/cpu/rope_highway.cpp | 387 ++++ mlx/backend/cpu/rope_highway.h | 101 + mlx/backend/cpu/sdpa.cpp | 943 ++++++++ mlx/backend/cpu/simd/base_simd.h | 69 +- mlx/backend/cpu/simd/highway_simd.h | 877 ++++++++ mlx/backend/cpu/simd/math.h | 109 +- mlx/backend/cpu/simd/type.h | 7 + mlx/backend/cpu/softmax.cpp | 201 +- mlx/backend/cpu/threading/CMakeLists.txt | 21 + .../cpu/threading/accelerate/thread_pool.h | 33 + .../cpu/threading/accelerate/thread_pool.mm | 65 + mlx/backend/cpu/threading/base.h | 49 + mlx/backend/cpu/threading/common.cpp | 30 + mlx/backend/cpu/threading/common.h | 90 + .../cpu/threading/openblas/thread_pool.cpp | 380 ++++ .../cpu/threading/openblas/thread_pool.h | 79 + mlx/backend/cpu/unary.h | 99 +- mlx/backend/cpu/unary_ops.h | 25 +- mlx/backend/no_gpu/primitives.cpp | 24 +- mlx/fast_primitives.h | 27 +- python/tests/test_compile.py | 184 +- python/tests/test_quantized.py | 38 + tests/CMakeLists.txt | 2 + tests/fast_tests.cpp | 506 +++++ tests/thread_pool_tests.cpp | 324 +++ 47 files changed, 10952 insertions(+), 747 deletions(-) create mode 100644 mlx/backend/cpu/norms.cpp create mode 100644 mlx/backend/cpu/norms_highway.cpp create mode 100644 mlx/backend/cpu/norms_highway.h create mode 100644 mlx/backend/cpu/quantized.h create mode 100644 mlx/backend/cpu/quantized_highway.cpp create mode 100644 mlx/backend/cpu/quantized_highway.h create mode 100644 mlx/backend/cpu/rope.cpp create mode 100644 mlx/backend/cpu/rope_highway.cpp create mode 100644 mlx/backend/cpu/rope_highway.h create mode 100644 mlx/backend/cpu/sdpa.cpp create mode 100644 mlx/backend/cpu/simd/highway_simd.h create mode 100644 mlx/backend/cpu/threading/CMakeLists.txt create mode 100644 mlx/backend/cpu/threading/accelerate/thread_pool.h create mode 100644 mlx/backend/cpu/threading/accelerate/thread_pool.mm create mode 100644 mlx/backend/cpu/threading/base.h create mode 100644 mlx/backend/cpu/threading/common.cpp create mode 100644 mlx/backend/cpu/threading/common.h create mode 100644 mlx/backend/cpu/threading/openblas/thread_pool.cpp create mode 100644 mlx/backend/cpu/threading/openblas/thread_pool.h create mode 100644 tests/fast_tests.cpp create mode 100644 tests/thread_pool_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 01b329b2f2..62f9a61784 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,20 @@ 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) +if(MLX_BUILD_CPU AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") + set(_AVX2_DEFAULT ON) +else() + set(_AVX2_DEFAULT OFF) +endif() +option(MLX_ENABLE_AVX2 "Enable AVX2 SIMD on x86 (includes BMI2, FMA, and F16C)" + ${_AVX2_DEFAULT}) +set(MLX_HIGHWAY_SOURCE_DIR + "" + CACHE PATH "Path to a local Highway source checkout for MLX_ENABLE_AVX2") +set(MLX_HIGHWAY_GIT_TAG + "1.4.0" + CACHE STRING + "Highway git tag or commit used when MLX_ENABLE_AVX2 fetches 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..0f4ac7b8d2 100644 --- a/mlx.pc.in +++ b/mlx.pc.in @@ -11,6 +11,11 @@ @PACKAGE_INIT@ +if (@MLX_BUILD_CPU@ AND @MLX_ENABLE_AVX2@) + 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 6192a189a4..1e372c9e31 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -6,6 +6,88 @@ else() set(CLANG FALSE) endif() +set(MLX_HIGHWAY_INCLUDE_DIR "") + +if(MLX_ENABLE_AVX2) + if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") + message(FATAL_ERROR "MLX_ENABLE_AVX2 requires an x86 target") + endif() + + include(CheckCXXCompilerFlag) + if(MSVC) + check_cxx_compiler_flag("/arch:AVX2" MLX_COMPILER_SUPPORTS_AVX2) + if(NOT MLX_COMPILER_SUPPORTS_AVX2) + message(FATAL_ERROR "MLX_ENABLE_AVX2 requires /arch:AVX2 support") + endif() + set(MLX_AVX2_COMPILE_OPTIONS /arch:AVX2) + set(PREAMBLE_SIMD_FLAGS "/arch:AVX2") + else() + # Highway's AVX2 target assumes the x86 feature set shipped with mainstream + # Intel/AMD AVX2 CPUs. VMs that mask BMI2/FMA/F16C need a separate, stricter + # baseline. + check_cxx_compiler_flag("-mavx2 -mbmi2 -mfma -mf16c" + MLX_COMPILER_SUPPORTS_AVX2) + if(NOT MLX_COMPILER_SUPPORTS_AVX2) + message( + FATAL_ERROR + "MLX_ENABLE_AVX2 requires -mavx2 -mbmi2 -mfma -mf16c support") + endif() + set(MLX_AVX2_COMPILE_OPTIONS -mavx2 -mbmi2 -mfma -mf16c) + set(PREAMBLE_SIMD_FLAGS "-mavx2 -mbmi2 -mfma -mf16c") + endif() + + # MLX_ENABLE_AVX2 deliberately builds one Highway x86 target: AVX2. + # HWY_DISABLED_TARGETS masks wider AVX-512-class targets, and + # HWY_COMPILE_ONLY_STATIC keeps lower fallback targets out of the MLX binary. + # Future AVX512 support could update this target set explicitly. + set(MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS + "HWY_DISABLED_TARGETS=(HWY_AVX2-1)" HWY_DISABLE_PCLMUL_AES + HWY_COMPILE_ONLY_STATIC) + + 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_ENABLE_AVX2 requires Highway target hwy") + endif() + if(NOT TARGET hwy::hwy) + add_library(hwy::hwy ALIAS hwy) + endif() + + target_compile_definitions(hwy PRIVATE ${MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS}) + target_compile_options(hwy PRIVATE ${MLX_AVX2_COMPILE_OPTIONS}) + target_compile_definitions(mlx PRIVATE MLX_USE_HIGHWAY + ${MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS}) + target_compile_options(mlx PRIVATE ${MLX_AVX2_COMPILE_OPTIONS}) + target_link_libraries(mlx PRIVATE hwy::hwy) + message(STATUS "x86 SIMD: AVX2 enabled (${PREAMBLE_SIMD_FLAGS})") +endif() + set(COMPILE_DEPS ${PROJECT_SOURCE_DIR}/mlx/types/half_types.h ${PROJECT_SOURCE_DIR}/mlx/types/fp16.h @@ -13,6 +95,7 @@ set(COMPILE_DEPS ${PROJECT_SOURCE_DIR}/mlx/types/complex.h simd/simd.h simd/base_simd.h + simd/highway_simd.h simd/math.h simd/type.h unary_ops.h @@ -32,7 +115,7 @@ add_custom_command( ${SHELL_CMD} ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp ${COMPILER} ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} - "${PREAMBLE_SIMD_FLAGS}" + "${PREAMBLE_SIMD_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h ${COMPILE_DEPS}) @@ -72,9 +155,18 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/inverse.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cholesky.cpp ${CMAKE_CURRENT_SOURCE_DIR}/unary.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/norms.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sdpa.cpp ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) +if(MLX_ENABLE_AVX2) + 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) +endif() + if(MLX_BUILD_ACCELERATE) target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/gemms/bnns.cpp) else() @@ -88,3 +180,6 @@ else() target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp ${CMAKE_CURRENT_SOURCE_DIR}/jit_compiler.cpp) endif() + +# Include threading backend (platform-specific implementation) +add_subdirectory(threading) diff --git a/mlx/backend/cpu/binary.h b/mlx/backend/cpu/binary.h index fb7db76f93..0fcec72369 100644 --- a/mlx/backend/cpu/binary.h +++ b/mlx/backend/cpu/binary.h @@ -1,4 +1,4 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #pragma once #include @@ -10,6 +10,7 @@ #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" namespace mlx::core { @@ -18,6 +19,11 @@ struct VectorScalar { template void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *b; + process_chunk(a, scalar, dst, static_cast(size)); + } + + template + static void process_chunk(const T* a, T scalar, U* dst, size_t size) { constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::load(a), simd::Simd(scalar))); @@ -38,6 +44,11 @@ struct ScalarVector { template void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *a; + process_chunk(scalar, b, dst, static_cast(size)); + } + + template + static void process_chunk(T scalar, const T* b, U* dst, size_t size) { constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::Simd(scalar), simd::load(b))); @@ -57,6 +68,11 @@ template struct VectorVector { template void operator()(const T* a, const T* b, U* dst, size_t size) { + process_chunk(a, b, dst, static_cast(size)); + } + + template + static void process_chunk(const T* a, const T* b, U* dst, size_t size) { constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::load(a), simd::load(b))); @@ -132,21 +148,61 @@ void binary_op_dispatch_dims( return; } - ContiguousIterator a_it(shape, a_strides, dim - 3); - ContiguousIterator b_it(shape, b_strides, dim - 3); auto stride = out_strides[dim - 4]; - 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(); + 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(); + } } } @@ -164,19 +220,66 @@ 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) { - ScalarVector{}(a_ptr, b_ptr, out_ptr, b.data_size()); + 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); + } return; } // The full computation is vector scalar so delegate to the op if (bopt == BinaryOpType::VectorScalar) { - VectorScalar{}(a_ptr, b_ptr, out_ptr, a.data_size()); + 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); + } return; } // The full computation is vector vector so delegate to the op if (bopt == BinaryOpType::VectorVector) { - VectorVector{}(a_ptr, b_ptr, out_ptr, a.size()); + 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); + } return; } diff --git a/mlx/backend/cpu/compiled.cpp b/mlx/backend/cpu/compiled.cpp index f5b516e44b..b5607397e3 100644 --- a/mlx/backend/cpu/compiled.cpp +++ b/mlx/backend/cpu/compiled.cpp @@ -12,6 +12,7 @@ #include "mlx/backend/common/compiled.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/jit_compiler.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/device.h" #include "mlx/graph_utils.h" #include "mlx/version.h" @@ -207,69 +208,236 @@ inline void build_kernel( } if (contiguous) { - os << " for (size_t i = 0; i < size; ++i) {" << std::endl; + auto out_tstr = get_type_string(outputs[0].dtype()); + + // SIMD main loop (processes max_size elements per iteration) + os << " constexpr int _S = simd::max_size<" << out_tstr << ">;" + << std::endl; + os << " size_t _vi = 0;" << std::endl; + os << " if constexpr (_S > 1) {" << std::endl; + os << " for (; _vi + _S <= size; _vi += _S) {" << std::endl; + + // SIMD loads + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& x = inputs[i]; + auto& xname = namer.get_name(x); + auto tstr = get_type_string(x.dtype()); + + if (is_constant(i)) { + os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>((" << tstr + << ")"; + print_constant(os, x); + os << ");" << std::endl; + } else if (is_scalar(x)) { + os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>(" << xname + << "[0]);" << std::endl; + } else { + os << " auto tmp_" << xname << " = simd::load<" << tstr << ", _S>(" + << xname << " + _vi);" << std::endl; + } + } + + // SIMD computation + for (auto& x : tape) { + os << " auto tmp_" << namer.get_name(x) << " = "; + if (is_static_cast(x.primitive())) { + auto tstr = get_type_string(x.dtype()); + os << "Simd<" << tstr << ", _S>(tmp_" << namer.get_name(x.inputs()[0]) + << ");" << std::endl; + } else { + os << x.primitive().name(); + os << "()("; + for (int i = 0; i < x.inputs().size() - 1; i++) { + os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; + } + os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; + } + } + + // SIMD stores + for (auto& x : outputs) { + os << " simd::store(" << namer.get_name(x) << " + _vi, tmp_" + << namer.get_name(x) << ");" << std::endl; + } + + os << " }" << std::endl; // close SIMD for + os << " }" << std::endl; // close if constexpr + + // Scalar tail loop + os << " for (size_t i = _vi; i < size; ++i) {" << std::endl; + + // Scalar reads (contiguous) + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& x = inputs[i]; + auto& xname = namer.get_name(x); + if (is_constant(i)) { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = "; + print_constant(os, x); + os << ";" << std::endl; + } else if (is_scalar(x)) { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " + << xname << "[0];" << std::endl; + } else { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " + << xname << "[i];" << std::endl; + } + } + + // Scalar computation (contiguous tail) + for (auto& x : tape) { + os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) + << " = "; + if (is_static_cast(x.primitive())) { + os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" + << namer.get_name(x.inputs()[0]) << ");" << std::endl; + } else { + os << x.primitive().name() << "()("; + for (int i = 0; i < x.inputs().size() - 1; i++) { + os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; + } + os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; + } + } + + // Scalar writes (contiguous tail) + for (auto& x : outputs) { + os << " " << namer.get_name(x) << "[i] = tmp_" << namer.get_name(x) + << ";" << std::endl; + } + + os << " }" << std::endl; // close scalar tail + } else { - for (int d = 0; d < ndim; ++d) { + // ===== STRIDED PATH WITH SIMD ===== + auto out_tstr = get_type_string(outputs[0].dtype()); + int inner_d = ndim - 1; + + os << " constexpr int _S = simd::max_size<" << out_tstr << ">;" + << std::endl; + + // Open outer loops (d=0 to d=ndim-2) + for (int d = 0; d < ndim - 1; ++d) { os << " for (int i" << d << " = 0; i" << d << " < shape[" << d << "]; ++i" << d << ") {" << std::endl; } - } - // Read the inputs in tmps - for (size_t i = 0; i < inputs.size(); ++i) { - const auto& x = inputs[i]; - auto& xname = namer.get_name(x); + // ---- SIMD inner loop ---- + os << " int i" << inner_d << " = 0;" << std::endl; + os << " if constexpr (_S > 1) {" << std::endl; + os << " for (; i" << inner_d << " + _S <= shape[" << inner_d << "]; i" + << inner_d << " += _S) {" << std::endl; + + // SIMD loads (with stride check for gather) + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& x = inputs[i]; + auto& xname = namer.get_name(x); + auto tstr = get_type_string(x.dtype()); + + if (is_constant(i)) { + os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>((" << tstr + << ")"; + print_constant(os, x); + os << ");" << std::endl; + } else if (is_scalar(x)) { + os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>(" << xname + << "[0]);" << std::endl; + } else { + // Runtime stride check: contiguous inner dim -> simd::load, else gather + os << " Simd<" << tstr << ", _S> tmp_" << xname << ";" << std::endl; + os << " if (" << xname << "_strides[" << inner_d << "] == 1) {" + << std::endl; + os << " tmp_" << xname << " = simd::load<" << tstr << ", _S>(" + << xname << " + i" << inner_d << ");" << std::endl; + os << " } else {" << std::endl; + os << " " << tstr << " _gather_" << xname << "[_S];" << std::endl; + os << " for (int _k = 0; _k < _S; _k++)" << std::endl; + os << " _gather_" << xname << "[_k] = " << xname << "[(i" + << inner_d << " + _k) * " << xname << "_strides[" << inner_d << "]];" + << std::endl; + os << " tmp_" << xname << " = simd::load<" << tstr + << ", _S>(_gather_" << xname << ");" << std::endl; + os << " }" << std::endl; + } + } - if (is_constant(i)) { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = "; - print_constant(os, x); - os << ";" << std::endl; - } else if (is_scalar(x)) { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " - << xname << "[0];" << std::endl; - } else if (contiguous) { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " - << xname << "[i];" << std::endl; - } else { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = *" - << xname << ";" << std::endl; + // SIMD computation (strided) + for (auto& x : tape) { + os << " auto tmp_" << namer.get_name(x) << " = "; + if (is_static_cast(x.primitive())) { + auto tstr = get_type_string(x.dtype()); + os << "Simd<" << tstr << ", _S>(tmp_" << namer.get_name(x.inputs()[0]) + << ");" << std::endl; + } else { + os << x.primitive().name() << "()("; + for (int i = 0; i < x.inputs().size() - 1; i++) { + os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; + } + os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; + } } - } - // Actually write the computation - for (auto& x : tape) { - os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) - << " = "; - if (is_static_cast(x.primitive())) { - os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" - << namer.get_name(x.inputs()[0]) << ");" << std::endl; - } else { - os << x.primitive().name(); - os << "()("; - for (int i = 0; i < x.inputs().size() - 1; i++) { - os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; + // SIMD stores (output is always contiguous) + for (auto& x : outputs) { + os << " simd::store(" << namer.get_name(x) << ", tmp_" + << namer.get_name(x) << ");" << std::endl; + os << " " << namer.get_name(x) << " += _S;" << std::endl; + } + + os << " }" << std::endl; // close SIMD for + os << " }" << std::endl; // close if constexpr + + // ---- Scalar tail (strided) ---- + os << " for (; i" << inner_d << " < shape[" << inner_d << "]; ++i" + << inner_d << ") {" << std::endl; + + // Scalar reads (indexed by inner dim) + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& x = inputs[i]; + auto& xname = namer.get_name(x); + auto tstr = get_type_string(x.dtype()); + + if (is_constant(i)) { + os << " " << tstr << " tmp_" << xname << " = "; + print_constant(os, x); + os << ";" << std::endl; + } else if (is_scalar(x)) { + os << " " << tstr << " tmp_" << xname << " = " << xname << "[0];" + << std::endl; + } else { + os << " " << tstr << " tmp_" << xname << " = " << xname << "[i" + << inner_d << " * " << xname << "_strides[" << inner_d << "]];" + << std::endl; } - os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; } - } - // Write the outputs from tmps - for (auto& x : outputs) { - if (contiguous) { - os << " " << namer.get_name(x) << "[i] = tmp_" << namer.get_name(x) - << ";" << std::endl; - } else { + // Scalar computation (strided tail) + for (auto& x : tape) { + os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) + << " = "; + if (is_static_cast(x.primitive())) { + os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" + << namer.get_name(x.inputs()[0]) << ");" << std::endl; + } else { + os << x.primitive().name() << "()("; + for (int i = 0; i < x.inputs().size() - 1; i++) { + os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; + } + os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; + } + } + + // Scalar writes (output contiguous, pointer auto-advances) + for (auto& x : outputs) { os << " *" << namer.get_name(x) << "++ = tmp_" << namer.get_name(x) << ";" << std::endl; } - } - // Close loops - if (contiguous) { - os << " }" << std::endl; - } else { - for (int d = ndim - 1; d >= 0; --d) { - // Update pointers + os << " }" << std::endl; // close scalar tail + + // Close outer loops (d=ndim-2 down to 0) + // Inner dim uses indexed access (no pointer accumulation), so outer loops + // only undo accumulation from dimensions > inner_d (i.e., d+1 < inner_d). + for (int d = ndim - 2; d >= 0; --d) { for (size_t i = 0; i < inputs.size(); ++i) { const auto& x = inputs[i]; if (is_constant(i) || is_scalar(x)) { @@ -278,9 +446,9 @@ inline void build_kernel( auto& xname = namer.get_name(x); os << " " << xname << " += " << xname << "_strides[" << d << "];" << std::endl; - if (d < ndim - 1) { - os << " " << xname << " -= " << xname << "_strides[" << d + 1 << "]" - << " * shape[" << d + 1 << "];" << std::endl; + if (d < ndim - 2) { + os << " " << xname << " -= " << xname << "_strides[" << d + 1 + << "] * shape[" << d + 1 << "];" << std::endl; } } os << " }" << std::endl; @@ -358,20 +526,152 @@ void Compiled::eval_cpu( args.push_back(x.data()); encoder.set_output_array(x); } + // Metadata for parallel dispatch + SmallVector arg_itemsize; + SmallVector arg_is_scalar; + size_t num_data_args = 0; // input + output args (excludes trailing size arg) + + for (size_t i = 0; i < inputs.size(); ++i) { + if (is_constant_(i)) + continue; + arg_itemsize.push_back(inputs[i].itemsize()); + arg_is_scalar.push_back(is_scalar(inputs_[i])); + num_data_args++; + } + for (auto& x : outputs) { + arg_itemsize.push_back(x.itemsize()); + arg_is_scalar.push_back(false); + num_data_args++; + } + if (contiguous) { args.push_back((void*)outputs[0].data_size()); } + auto fun = reinterpret_cast(fn_ptr); - encoder.dispatch([fun, - args = std::move(args), - strides = std::move(strides), - shape = std::move(shape)]() mutable { - SmallVector strides_ptrs; - for (auto& s : strides) { - strides_ptrs.push_back(s.data()); + + if (contiguous) { + size_t total_size = outputs[0].data_size(); + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(total_size, pool.max_threads()); + + if (n_threads > 1) { + // Multi-threaded: parallel_for splits work across threads + encoder.dispatch([fun, + args, + arg_itemsize, + arg_is_scalar, + num_data_args, + total_size, + n_threads]() mutable { + auto& pool = cpu::ThreadPool::instance(); + pool.parallel_for(n_threads, [&](int tid, int nth) { + size_t chunk = (total_size + nth - 1) / nth; + size_t start = chunk * tid; + size_t end = std::min(start + chunk, total_size); + if (start >= end) + return; + + SmallVector thread_args(args.size()); + for (size_t j = 0; j < num_data_args; ++j) { + if (arg_is_scalar[j]) { + thread_args[j] = args[j]; + } else { + thread_args[j] = + static_cast(args[j]) + start * arg_itemsize[j]; + } + } + thread_args[num_data_args] = (void*)(end - start); + fun(nullptr, nullptr, thread_args.data()); + }); + }); + } else { + // Single-threaded contiguous + encoder.dispatch([fun, args = std::move(args)]() mutable { + fun(nullptr, nullptr, args.data()); + }); } - fun(shape.data(), strides_ptrs.data(), args.data()); - }); + } else { + // Strided path with threading + size_t total_size = outputs[0].data_size(); + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(total_size, pool.max_threads()); + if (!shape.empty()) { + n_threads = std::min(n_threads, (int)shape[0]); + } + + if (n_threads > 1 && !shape.empty() && shape[0] > 1) { + // Compute outermost stride for each arg (for pointer offsetting) + SmallVector arg_outer_stride(num_data_args); + { + int si = 1; // strides[0] is output, inputs start at 1 + size_t arg_j = 0; + for (size_t i = 0; i < inputs.size(); ++i) { + if (is_constant_(i)) + continue; + if (arg_is_scalar[arg_j]) { + arg_outer_stride[arg_j] = 0; + } else { + arg_outer_stride[arg_j] = strides[si][0]; + si++; + } + arg_j++; + } + // Output args use strides[0] (output strides) + for (size_t i = arg_j; i < num_data_args; ++i) { + arg_outer_stride[i] = strides[0][0]; + } + } + + encoder.dispatch([fun, + args, + strides = std::move(strides), + shape = std::move(shape), + arg_outer_stride, + arg_itemsize, + num_data_args, + n_threads]() mutable { + SmallVector strides_ptrs; + for (auto& s : strides) { + strides_ptrs.push_back(s.data()); + } + auto& pool = cpu::ThreadPool::instance(); + pool.parallel_for(n_threads, [&](int tid, int nth) { + int chunk = (shape[0] + nth - 1) / nth; + int start = chunk * tid; + int end = std::min(start + chunk, shape[0]); + if (start >= end) + return; + + SmallVector thread_args(args.begin(), args.end()); + for (size_t j = 0; j < num_data_args; ++j) { + if (arg_outer_stride[j] != 0) { + thread_args[j] = static_cast(args[j]) + + start * arg_outer_stride[j] * + static_cast(arg_itemsize[j]); + } + } + + auto thread_shape = shape; + thread_shape[0] = end - start; + + fun(thread_shape.data(), strides_ptrs.data(), thread_args.data()); + }); + }); + } else { + // Single-threaded strided + encoder.dispatch([fun, + args = std::move(args), + strides = std::move(strides), + shape = std::move(shape)]() mutable { + SmallVector strides_ptrs; + for (auto& s : strides) { + strides_ptrs.push_back(s.data()); + } + fun(shape.data(), strides_ptrs.data(), args.data()); + }); + } + } } } // namespace mlx::core diff --git a/mlx/backend/cpu/copy.cpp b/mlx/backend/cpu/copy.cpp index 381719eb0c..6311d0ecd7 100644 --- a/mlx/backend/cpu/copy.cpp +++ b/mlx/backend/cpu/copy.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include @@ -7,6 +7,7 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/dtype_utils.h" namespace mlx::core { @@ -109,20 +110,59 @@ void copy_general_general( auto size = std::accumulate( shape.begin(), shape.end(), int64_t{1}, std::multiplies()); - ContiguousIterator in(shape, strides[0], ndim - 3); - ContiguousIterator out(shape, strides[1], ndim - 3); auto stride = std::accumulate( shape.end() - 3, shape.end(), 1, std::multiplies()); - 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(); + 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(); + } } } diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 765e9f539a..5a9b8102b1 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -1,11 +1,16 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include "mlx/backend/common/utils.h" #include "mlx/backend/cpu/gemm.h" #include "mlx/backend/cpu/lapack.h" +#include "mlx/backend/cpu/threading/common.h" namespace mlx::core { +// 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; + template <> void matmul( const float* a, @@ -28,22 +33,97 @@ void matmul( size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; - for (int i = 0; i < batch_size; ++i) { - cblas_sgemm( - CblasRowMajor, - a_transposed ? CblasTrans : CblasNoTrans, // transA - b_transposed ? CblasTrans : CblasNoTrans, // transB - 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); + // 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))); + } + + 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); + } + } } } @@ -69,22 +149,88 @@ void matmul( size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; - for (int i = 0; i < batch_size; ++i) { - cblas_dgemm( - CblasRowMajor, - a_transposed ? CblasTrans : CblasNoTrans, // transA - b_transposed ? CblasTrans : CblasNoTrans, // transB - 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); + 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); + } + } } } @@ -112,22 +258,87 @@ void matmul( auto calpha = static_cast(alpha); auto cbeta = static_cast(beta); - for (int i = 0; i < batch_size; ++i) { - cblas_cgemm( - CblasRowMajor, - a_transposed ? CblasTrans : CblasNoTrans, // transA - b_transposed ? CblasTrans : CblasNoTrans, // transB - 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); + 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) { + cblas_cgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + &calpha, + a_ptr + m_start * lda, + 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); + } + } } } diff --git a/mlx/backend/cpu/gemms/simd_bf16.cpp b/mlx/backend/cpu/gemms/simd_bf16.cpp index 58f5964b6e..f400d40d85 100644 --- a/mlx/backend/cpu/gemms/simd_bf16.cpp +++ b/mlx/backend/cpu/gemms/simd_bf16.cpp @@ -1,11 +1,227 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #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/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" + +#include +#include namespace mlx::core { +constexpr int BF16_MIN_BATCHES_PER_THREAD = 4; + +namespace { + +// Thread-local scratch buffer for bf16->f32 conversion. +// Avoids mmap/munmap cycles and page faults from repeated large allocations. +float* get_scratch(size_t n) { + thread_local std::vector buf; + if (buf.size() < n) { + buf.resize(n); + } + return buf.data(); +} + +void bf16_to_f32(const bfloat16_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]); + } +} + +void f32_to_bf16(const float* src, bfloat16_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 bf16 GEMV: reads bf16 weights directly, converts in-register, FMAs. +// Eliminates 3x memory traffic of separate bf16->f32 conversion + BLAS. +// b_transposed=true: B is [N][K] (row = output), most common for LLM linear +// layers. b_transposed=false: B is [K][N] (row = input). +void bf16_gemv( + const bfloat16_t* a, + const bfloat16_t* b, + bfloat16_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. + // Compute: out[n] = alpha * dot(A, B[n]) + beta * out[n] + // A stays in cache, stream B rows sequentially. + for (size_t n = 0; n < N; n++) { + const bfloat16_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][:] + // Allocate f32 accumulator for N outputs (fits in L1 for typical N) + float* accum = get_scratch(N); + 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 bfloat16_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]); + } + } +} + +// Multi-threaded wrapper for bf16_gemv: splits N across threads. +void bf16_gemv_threaded( + const bfloat16_t* a, + const bfloat16_t* b, + bfloat16_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) { + // For b_transposed, each output n is independent -- trivially parallel. + 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) { + bf16_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) { + // For not-transposed, split N into ranges. Each thread accumulates its own + // slice of accumulators, 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; + float* accum = get_scratch(n_len); + 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 bfloat16_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 { + bf16_gemv(a, b, out, b_transposed, N, K, ldb, alpha, beta); + } +} + +} // namespace + template <> void matmul( const bfloat16_t* a, @@ -27,18 +243,175 @@ void matmul( size_t M = a_shape[ndim - 2]; size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; - for (int i = 0; i < batch_size; ++i) { - simd_gemm( - a + elem_to_loc(M * K * i, a_shape, a_strides), - b + elem_to_loc(K * N * i, b_shape, b_strides), - out + M * N * i, - a_transposed, - b_transposed, - M, - N, - K, - alpha, - beta); + + if (batch_size > 1) { + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + 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; + + bf16_to_f32(a_ptr, a_f32, a_elems); + bf16_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + bf16_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_bf16(out_f32, out_ptr, out_elems); + } + }; + + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / BF16_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) { + float* base = get_scratch(buf_size); + 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 { + float* scratch = get_scratch(a_elems + b_elems + out_elems); + run_batches( + 0, + batch_size, + scratch, + scratch + a_elems, + scratch + a_elems + b_elems); + } + } else { + // Single batch + 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 && N * K >= 65536) { + // M=1 GEMV: fused bf16 read + convert + FMA in one pass. + // For a_transposed, M=1 means a is K elements either way. + const bfloat16_t* a_vec = + a_transposed ? a_ptr : a_ptr; // both sequential for M=1 + bf16_gemv_threaded( + a_vec, b_ptr, out_ptr, b_transposed, N, K, ldb, alpha, beta); + } else if (M * N * K >= 65536) { + // Larger GEMM: cast to f32 + use BLAS + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + float* a_f32 = get_scratch(a_elems + b_elems + out_elems); + float* b_f32 = a_f32 + a_elems; + float* out_f32 = b_f32 + b_elems; + + bf16_to_f32(a_ptr, a_f32, a_elems); + bf16_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + bf16_to_f32(out_ptr, out_f32, out_elems); + } + + // For large M, split rows across threads + 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) { + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + alpha, + a_f32 + m_start * lda, + 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_bf16(out_f32, out_ptr, out_elems); + } else { + // Small GEMM: use simd_gemm directly (no cast overhead) + simd_gemm( + a_ptr, + b_ptr, + out_ptr, + a_transposed, + b_transposed, + M, + N, + K, + alpha, + beta); + } + } } } diff --git a/mlx/backend/cpu/gemms/simd_fp16.cpp b/mlx/backend/cpu/gemms/simd_fp16.cpp index 93467da868..312e75cee2 100644 --- a/mlx/backend/cpu/gemms/simd_fp16.cpp +++ b/mlx/backend/cpu/gemms/simd_fp16.cpp @@ -1,11 +1,224 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #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/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" + +#include +#include namespace mlx::core { +// Minimum batches per thread before parallelizing the BLAS path. +constexpr int FP16_MIN_BATCHES_PER_THREAD = 4; + +namespace { + +// Thread-local scratch buffer for f16->f32 conversion. +// Avoids mmap/munmap cycles and page faults from repeated large allocations. +float* get_scratch(size_t n) { + thread_local std::vector buf; + if (buf.size() < n) { + buf.resize(n); + } + return buf.data(); +} + +void f16_to_f32(const float16_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]); + } +} + +void f32_to_f16(const float* src, float16_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 f16 GEMV: reads f16 weights directly, converts in-register via F16C, +// FMAs. Eliminates 3x memory traffic of separate f16->f32 conversion + BLAS. +// b_transposed=true: B is [N][K] (row = output), most common for LLM linear +// layers. b_transposed=false: B is [K][N] (row = input). +void f16_gemv( + const float16_t* a, + const float16_t* b, + float16_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. + // Compute: out[n] = alpha * dot(A, B[n]) + beta * out[n] + // A stays in cache, stream B rows sequentially. + for (size_t n = 0; n < N; n++) { + const float16_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][:] + float* accum = get_scratch(N); + 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 float16_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]); + } + } +} + +// Multi-threaded wrapper for f16_gemv: splits N across threads. +void f16_gemv_threaded( + const float16_t* a, + const float16_t* b, + float16_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) { + // For b_transposed, each output n is independent -- trivially parallel. + 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) { + f16_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) { + // For not-transposed, split N into ranges. Each thread accumulates its own + // slice of accumulators, 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; + float* accum = get_scratch(n_len); + 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 float16_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 { + f16_gemv(a, b, out, b_transposed, N, K, ldb, alpha, beta); + } +} + +} // namespace + template <> void matmul( const float16_t* a, @@ -27,18 +240,175 @@ void matmul( size_t M = a_shape[ndim - 2]; size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; - for (int i = 0; i < batch_size; ++i) { - simd_gemm( - a + elem_to_loc(M * K * i, a_shape, a_strides), - b + elem_to_loc(K * N * i, b_shape, b_strides), - out + M * N * i, - a_transposed, - b_transposed, - M, - N, - K, - alpha, - beta); + + // For batched operations (e.g. multi-head attention with 32+ heads), + // cast to float32 and use threaded BLAS -- much faster than naive simd_gemm. + // For single-batch ops (e.g. linear projections with huge weight matrices), + // use simd_gemm to avoid copying the entire weight matrix to float32. + if (batch_size > 1) { + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + 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; + + f16_to_f32(a_ptr, a_f32, a_elems); + f16_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + f16_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_f16(out_f32, out_ptr, out_elems); + } + }; + + auto& pool = cpu::ThreadPool::instance(); + int n_threads = std::min( + pool.max_threads(), + static_cast(batch_size / FP16_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) { + float* base = get_scratch(buf_size); + 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 { + float* scratch = get_scratch(a_elems + b_elems + out_elems); + run_batches( + 0, + batch_size, + scratch, + scratch + a_elems, + scratch + a_elems + b_elems); + } + } else { + // Single batch + 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 && N * K >= 65536) { + // M=1 GEMV: fused f16 read + F16C convert + FMA in one pass. + f16_gemv_threaded( + a_ptr, b_ptr, out_ptr, b_transposed, N, K, ldb, alpha, beta); + } else if (M * N * K >= 65536) { + // Larger GEMM: cast to f32 + use BLAS + 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))); + } + + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + float* a_f32 = get_scratch(a_elems + b_elems + out_elems); + float* b_f32 = a_f32 + a_elems; + float* out_f32 = b_f32 + b_elems; + + f16_to_f32(a_ptr, a_f32, a_elems); + f16_to_f32(b_ptr, b_f32, b_elems); + if (beta != 0) { + f16_to_f32(out_ptr, out_f32, out_elems); + } + + 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) { + cblas_sgemm( + CblasRowMajor, + a_transposed ? CblasTrans : CblasNoTrans, + b_transposed ? CblasTrans : CblasNoTrans, + m_end - m_start, + N, + K, + alpha, + a_f32 + m_start * lda, + 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_f16(out_f32, out_ptr, out_elems); + } else { + // Small GEMM: use simd_gemm directly (no cast overhead) + simd_gemm( + a_ptr, + b_ptr, + out_ptr, + a_transposed, + b_transposed, + M, + N, + K, + alpha, + beta); + } + } } } diff --git a/mlx/backend/cpu/indexing.cpp b/mlx/backend/cpu/indexing.cpp index 15a2af3cb9..7a97066538 100644 --- a/mlx/backend/cpu/indexing.cpp +++ b/mlx/backend/cpu/indexing.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include #include #include @@ -10,6 +10,7 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/slicing.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/dtype_utils.h" #include "mlx/primitives.h" @@ -87,36 +88,92 @@ void gather( const T* src_ptr = src.data(); T* dst_ptr = out.data(); - 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()); - } + auto& pool = cpu::ThreadPool::instance(); + int n_threads = cpu::effective_threads(out.size(), pool.max_threads()); + + 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 = 0; - for (int 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]); + 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()); } - 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(); + 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]); + } + + 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(); } - src_it.reset(); } } } @@ -196,10 +253,8 @@ void gather_axis( array& out, const int axis) { auto shape = remove_index(ind.shape(), axis); - ContiguousIterator ind_it( - shape, remove_index(ind.strides(), axis), src.ndim() - 1); - ContiguousIterator src_it( - shape, remove_index(src.strides(), axis), src.ndim() - 1); + auto ind_strides_no_ax = remove_index(ind.strides(), axis); + auto src_strides_no_ax = remove_index(src.strides(), axis); auto ind_ptr = ind.data(); auto src_ptr = src.data(); @@ -220,18 +275,63 @@ void gather_axis( } size_t stride_pre = size_post * ind_ax_size; - 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_ptr[k + j * dst_ax_stride] = - src_ptr[src_it.loc + ind_val * src_ax_stride]; + 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(); + } + + 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; } - ind_it.step(); - src_it.step(); + }); + } 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; } - dst_ptr += stride_pre; } } diff --git a/mlx/backend/cpu/jit_compiler.cpp b/mlx/backend/cpu/jit_compiler.cpp index 530637e551..8e61b78b54 100644 --- a/mlx/backend/cpu/jit_compiler.cpp +++ b/mlx/backend/cpu/jit_compiler.cpp @@ -148,7 +148,9 @@ bool supports_avx2_target() { return false; } __cpuidex(info, 7, 0); - return info[1] & (1 << 5); + bool avx2 = info[1] & (1 << 5); + bool bmi2 = info[1] & (1 << 8); + return avx2 && bmi2; #else return false; #endif // defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) @@ -157,8 +159,8 @@ bool supports_avx2_target() { #if defined(__x86_64__) || defined(__i386__) || defined(__amd64__) __builtin_cpu_init(); - return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && - __builtin_cpu_supports("f16c"); + return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("bmi2") && + __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c"); #else return false; #endif @@ -225,10 +227,17 @@ std::string JitCompiler::build_command( if (use_include) { compiler_flags += fmt::format(" /I \"{}\"", include_dir); } +#ifdef MLX_USE_HIGHWAY + compiler_flags += + " /DMLX_USE_HIGHWAY /DHWY_DISABLED_TARGETS=HWY_AVX2-1 " + "/DHWY_DISABLE_PCLMUL_AES /DHWY_COMPILE_ONLY_STATIC"; +#endif const VisualStudioInfo& info = GetVisualStudioInfo(); std::string compiler = info.compiler(use_include); - for (const std::string& include : info.includepaths) { - compiler_flags += fmt::format(" /I \"{}\"", include); + for (const std::string& inc : info.includepaths) { + if (!inc.empty()) { + compiler_flags += fmt::format(" /I \"{}\"", inc); + } } std::string libpaths; for (const std::string& lib : info.libpaths) { @@ -267,8 +276,18 @@ std::string JitCompiler::build_command( if (!extra_flags.empty()) { extra_flags += " "; } - extra_flags += "-mavx2 -mfma -mf16c"; + // Match the build-time Highway AVX2 target. This assumes the BMI2/FMA/F16C + // feature set present on mainstream Intel/AMD AVX2 CPUs. + extra_flags += "-mavx2 -mbmi2 -mfma -mf16c"; + } +#endif +#ifdef MLX_USE_HIGHWAY + if (!extra_flags.empty()) { + extra_flags += " "; } + extra_flags += + "-DMLX_USE_HIGHWAY -DHWY_DISABLED_TARGETS=HWY_AVX2-1 " + "-DHWY_DISABLE_PCLMUL_AES -DHWY_COMPILE_ONLY_STATIC"; #endif return fmt::format( "g++ -std=c++17 -O3 -Wall -fPIC -shared {} \"{}\" -o \"{}\" 2>&1", diff --git a/mlx/backend/cpu/make_compiled_preamble.ps1 b/mlx/backend/cpu/make_compiled_preamble.ps1 index e9fa7afba6..5aa30fef61 100644 --- a/mlx/backend/cpu/make_compiled_preamble.ps1 +++ b/mlx/backend/cpu/make_compiled_preamble.ps1 @@ -10,7 +10,8 @@ $SRCDIR = $args[2] # on macOS it controls -nobuiltininc and -arch flags for the preprocessor. # MSVC and clang-cl both accept the same preprocessor flags so no distinction needed.) # args[4] = CMAKE_SYSTEM_PROCESSOR (unused on Windows) -$SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mfma -mf16c" +$SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mbmi2 -mfma -mf16c" +$HIGHWAY_INCLUDE_DIR = $args[6] # Optional, used when MLX_ENABLE_AVX2 uses Highway # Detect compiler type: MSVC/clang-cl use /EP, GCC/clang++ use -E -P $CL_NAME = [System.IO.Path]::GetFileNameWithoutExtension($CL) @@ -32,10 +33,25 @@ if ($SIMD_FLAGS) { } if ($IS_MSVC_LIKE) { [void]$CL_ARGS.Add("/I$SRCDIR") + if ($HIGHWAY_INCLUDE_DIR) { + [void]$CL_ARGS.Add("/I$HIGHWAY_INCLUDE_DIR") + [void]$CL_ARGS.Add('/DMLX_USE_HIGHWAY') + [void]$CL_ARGS.Add('/DHWY_DISABLED_TARGETS=HWY_AVX2-1') + [void]$CL_ARGS.Add('/DHWY_DISABLE_PCLMUL_AES') + [void]$CL_ARGS.Add('/DHWY_COMPILE_ONLY_STATIC') + } [void]$CL_ARGS.Add('/Tp') } else { [void]$CL_ARGS.Add('-I') [void]$CL_ARGS.Add("$SRCDIR") + if ($HIGHWAY_INCLUDE_DIR) { + [void]$CL_ARGS.Add('-I') + [void]$CL_ARGS.Add("$HIGHWAY_INCLUDE_DIR") + [void]$CL_ARGS.Add('-DMLX_USE_HIGHWAY') + [void]$CL_ARGS.Add('-DHWY_DISABLED_TARGETS=HWY_AVX2-1') + [void]$CL_ARGS.Add('-DHWY_DISABLE_PCLMUL_AES') + [void]$CL_ARGS.Add('-DHWY_COMPILE_ONLY_STATIC') + } } [void]$CL_ARGS.Add("$SRCDIR/mlx/backend/cpu/compiled_preamble.h") diff --git a/mlx/backend/cpu/make_compiled_preamble.sh b/mlx/backend/cpu/make_compiled_preamble.sh index dc53bb8b53..156a307c8b 100644 --- a/mlx/backend/cpu/make_compiled_preamble.sh +++ b/mlx/backend/cpu/make_compiled_preamble.sh @@ -11,7 +11,8 @@ GCC=$2 SRCDIR=$3 CLANG=$4 ARCH=$5 -SIMD_FLAGS=$6 # Optional, e.g. "-mavx2 -mfma -mf16c" +SIMD_FLAGS=$6 # Optional, e.g. "-mavx2 -mbmi2 -mfma -mf16c" +HIGHWAY_INCLUDE_DIR=$7 # Optional, used when MLX_ENABLE_AVX2 uses Highway if [ "$CLANG" = "TRUE" ]; then read -r -d '' INCLUDES <<- EOM @@ -28,7 +29,21 @@ else CC_FLAGS="-std=c++17" fi -CONTENT=$("$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" -E -P "$SRCDIR/mlx/backend/cpu/compiled_preamble.h" 2>/dev/null) +HIGHWAY_INCLUDE_FLAG=() +if [ -n "$HIGHWAY_INCLUDE_DIR" ]; then + HIGHWAY_INCLUDE_FLAG=( + -I "$HIGHWAY_INCLUDE_DIR" + -DMLX_USE_HIGHWAY + -DHWY_DISABLED_TARGETS=HWY_AVX2-1 + -DHWY_DISABLE_PCLMUL_AES + -DHWY_COMPILE_ONLY_STATIC + ) +fi + +CONTENT=$( + "$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" "${HIGHWAY_INCLUDE_FLAG[@]}" \ + -E -P "$SRCDIR/mlx/backend/cpu/compiled_preamble.h" 2>/dev/null +) cat << EOF > "$OUTPUT_FILE" const char* get_prebuilt_preamble() { diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp new file mode 100644 index 0000000000..1bdcb30f38 --- /dev/null +++ b/mlx/backend/cpu/norms.cpp @@ -0,0 +1,765 @@ +// Copyright © 2026 Apple Inc. + +#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" +#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) +#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) + 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) + 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 +} + +} // namespace + +void RMSNorm::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + auto& in_x = inputs[0]; + auto& 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()); + } + + // 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()); + + 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()); + 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); + + for (int row = row_start; row < row_end; row++) { + rms_norm_row_half( + x_ptr + row * width, + w_ptr, + out_ptr + row * width, + width, + eps, + has_weight); + } + }); + }); + } else { + encoder.dispatch([=]() { + for (int row = 0; row < num_rows; row++) { + rms_norm_row_half( + x_ptr + row * width, + w_ptr, + out_ptr + row * width, + width, + 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); + + for (int row = row_start; row < row_end; row++) { + rms_norm_row_half( + x_ptr + row * width, + w_ptr, + out_ptr + row * width, + width, + eps, + has_weight); + } + }); + }); + } else { + encoder.dispatch([=]() { + for (int row = 0; row < num_rows; row++) { + rms_norm_row_half( + x_ptr + row * width, + w_ptr, + out_ptr + row * width, + width, + 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) { + auto& in_x = inputs[0]; + auto& weight = inputs[1]; + auto& 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()); + } + + // 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()); + + 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()); + 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); + + for (int row = row_start; row < row_end; row++) { + layer_norm_row_half( + x_ptr + row * width, + w_ptr, + b_ptr, + out_ptr + row * width, + width, + eps, + has_weight, + has_bias); + } + }); + }); + } else { + encoder.dispatch([=]() { + for (int row = 0; row < num_rows; row++) { + layer_norm_row_half( + x_ptr + row * width, + w_ptr, + b_ptr, + out_ptr + row * width, + width, + 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); + + for (int row = row_start; row < row_end; row++) { + layer_norm_row_half( + x_ptr + row * width, + w_ptr, + b_ptr, + out_ptr + row * width, + width, + eps, + has_weight, + has_bias); + } + }); + }); + } else { + encoder.dispatch([=]() { + for (int row = 0; row < num_rows; row++) { + layer_norm_row_half( + x_ptr + row * width, + w_ptr, + b_ptr, + out_ptr + row * width, + width, + 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 diff --git a/mlx/backend/cpu/norms_highway.cpp b/mlx/backend/cpu/norms_highway.cpp new file mode 100644 index 0000000000..a944359514 --- /dev/null +++ b/mlx/backend/cpu/norms_highway.cpp @@ -0,0 +1,240 @@ +// Copyright © 2026 Apple Inc. + +#include + +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/norms_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep + +#include "hwy/highway.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::fast { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; + +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)); + V sum_sq0 = hn::Zero(d); + V sum_sq1 = hn::Zero(d); + + int i = 0; + for (; i + 2 * lanes <= width; i += 2 * lanes) { + const V vals0 = hn::LoadU(d, x + i); + const V vals1 = hn::LoadU(d, x + i + lanes); + sum_sq0 = hn::MulAdd(vals0, vals0, sum_sq0); + sum_sq1 = hn::MulAdd(vals1, vals1, sum_sq1); + } + V sum_sq = hn::Add(sum_sq0, sum_sq1); + for (; i + lanes <= width; i += lanes) { + const V vals = hn::LoadU(d, x + i); + sum_sq = hn::MulAdd(vals, vals, sum_sq); + } + + float total = hn::ReduceSum(d, sum_sq); + for (; i < width; ++i) { + total += x[i] * x[i]; + } + + 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; + } + } +} + +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)); + V sum0 = hn::Zero(d); + V sum1 = hn::Zero(d); + + int i = 0; + for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { + sum = hn::Add(sum, hn::LoadU(d, x + i)); + } + + float total = hn::ReduceSum(d, sum); + for (; i < width; ++i) { + total += x[i]; + } + const float mean = total / width; + + const V vmean = hn::Set(d, mean); + V variance_sum0 = hn::Zero(d); + V variance_sum1 = hn::Zero(d); + + i = 0; + for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { + const V diff = hn::Sub(hn::LoadU(d, x + i), vmean); + variance_sum = hn::MulAdd(diff, diff, variance_sum); + } + + float variance = hn::ReduceSum(d, variance_sum); + for (; i < width; ++i) { + const float diff = x[i] - mean; + variance += diff * diff; + } + 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; + } +} + +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) { + for (int row = 0; row < rows; ++row) { + rms_norm_row_f32( + x + row * width, weight, out + row * width, width, 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) { + 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); + } +} + +} // namespace +} // namespace HWY_NAMESPACE +} // namespace mlx::core::fast +HWY_AFTER_NAMESPACE(); + +#if HWY_ONCE +namespace mlx::core::fast { + +HWY_EXPORT(RmsNormF32); +HWY_EXPORT(LayerNormF32); + +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 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); +} + +} // namespace mlx::core::fast +#endif // HWY_ONCE diff --git a/mlx/backend/cpu/norms_highway.h b/mlx/backend/cpu/norms_highway.h new file mode 100644 index 0000000000..86c7ad582d --- /dev/null +++ b/mlx/backend/cpu/norms_highway.h @@ -0,0 +1,27 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +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 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); + +} // namespace mlx::core::fast diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 15e00cd913..9eb6b3924e 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -1,32 +1,105 @@ // Copyright © 2023-2026 Apple Inc. #include "mlx/backend/common/quantized.h" +#include +#include +#include #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/lapack.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). +// When AVX2 is enabled on this branch, Highway is the implementation substrate. +#if defined(MLX_USE_HIGHWAY) +#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 { -namespace { +constexpr bool has_simd_qmm = false; -array ensure_row_contiguous( - const array& arr, - cpu::CommandEncoder& encoder, - Stream s) { - if (arr.flags().row_contiguous) { - return arr; - } else { - auto arr_cpy = contiguous_copy_cpu(arr, s); - encoder.add_temporary(arr_cpy); - return arr_cpy; +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, @@ -46,10 +119,51 @@ const static float FP4_LUT[16] = { -4.0f, -6.0f}; +// FP8 E4M3 -> float32 lookup table (256 entries, 1KB). +// Precomputed from the FromFP8 decode: strip sign, interpret lower 7 bits +// as float16 mantissa/exponent (<<7), multiply by 256, apply sign. +// Used by FP quantized matmul for O(1) FP8 weight decoding. +// 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, 480.0f, + -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, -480.0f, +}; +// clang-format on + template static inline T dequantize_scale(uint8_t s) { if constexpr (group_size == 16) { - return static_cast(detail::FromFP8{}(s)); + return static_cast(FP8_LUT[s]); } else { using FOrI = union { bfloat16_t f; @@ -151,82 +265,238 @@ void _qmm( } } +// Helper for computing a range of output columns in _qmm_t (used by threaded +// version) template -void _qmm_t( +void _qmm_t_cols( T* result, const T* x, const uint32_t* w, const T* scales, const T* biases, - int M, - int N, + 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; - 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; - - 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 = *scales_local++; - T bias = *biases_local++; - - for (int kw = 0; kw < packs_in_group; kw++) { - if constexpr (bits == 3 || bits == 5 || bits == 6) { - T wl[pack_factor]; - extract_bits(w_local, wl); + // 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; + T sum = 0; + + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T wl[pack_factor]; + extract_bits(w_local, wl); #pragma clang loop unroll(full) - for (int p = 0; p < pack_factor; p++) { - sum += x_local[p] * (scale * wl[p] + bias); + for (int p = 0; p < pack_factor; p++) { + sum += 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 += (*x_local++) * (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; } - w_local += bytes_per_pack; - x_local += pack_factor; + } + } + } + } + result[n - n_start] = sum; - } else { - uint8_t wi = *w_local++; + // 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; + T sum = 0; + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T wl[pack_factor]; + extract_bits(w_local, wl); #pragma clang loop unroll(full) - for (int p = 0; p < pack_factor; p++) { - sum += - (*x_local++) * (scale * static_cast(wi & bitmask) + bias); - if (bits != 8) { - wi >>= bits; + for (int p = 0; p < pack_factor; p++) { + sum += 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 += (*x_local++) * + (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; + } } } } } + *result = sum; + result++; } - *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) { +simd::Simd extract_bits_simd(const uint32_t* w, int elem_off = 0) { constexpr int bitmask = (1 << bits) - 1; simd::Simd wi; - if constexpr (bits == 4 && S == 8) { + 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_); - auto l = simd::Simd(*w++); - auto r = simd::Simd(*w); - wi = simd::Simd(l, r); + 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 { @@ -236,6 +506,309 @@ simd::Simd extract_bits_simd(const uint32_t* w) { 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, @@ -247,42 +820,334 @@ void _qmm_t_simd( int N, 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 S = simd::max_size; static_assert( - S % pack_factor == 0, "SIMD size must be divisible by pack factor"); - constexpr int packs_per_simd = S / pack_factor; + 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 + // 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); + } - for (int m = 0; m < M; m++) { - const uint32_t* w_local = w; - const T* scales_local = scales; - const T* biases_local = biases; + 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 buffer for dequant+BLAS path. +float* _qmm_get_scratch(size_t n) { + thread_local std::vector buf; + if (buf.size() < n) { + buf.resize(n); + } + return buf.data(); +} + +// 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) + 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; + float* w_f32 = _qmm_get_scratch(w_f32_size + x_f32_size + r_f32_size); + 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++) { - simd::Simd acc(0); - auto x_local = x; - for (int k = 0; k < K; k += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; + _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); + } + } - for (int kw = 0; kw < packs_in_group; kw += packs_per_simd) { - auto wf = simd::Simd(extract_bits_simd(w_local)); - w_local += packs_per_simd; - wf = wf * scale; - wf = wf + bias; - simd::Simd x_simd = simd::load(x_local); - acc = acc + x_simd * wf; - x_local += S; - } + // 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); + } - *result = T(simd::sum(acc)); - result++; + // 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]); } - x += K; } } +// 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, @@ -295,8 +1160,20 @@ void _qmm_dispatch_transpose( int K, bool transposed_w) { if (transposed_w) { - // the simd size must be a multiple of the number of elements per word - if constexpr (32 % bits == 0 && simd::max_size % (32 / bits) == 0) { + // 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. + if (M >= QMM_BLAS_M_THRESHOLD) { + _qmm_t_blas(result, x, w, scales, biases, M, N, K); + return; + } + // 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); @@ -454,7 +1331,8 @@ void fp_qmm( const uint8_t* scales, int M, int N, - int K) { + int K, + float scale_factor) { constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; @@ -469,7 +1347,10 @@ void fp_qmm( T xi = *x++; for (int n = 0; n < N; n += group_size) { - T scale = dequantize_scale(*scales_local++); + 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++) += @@ -478,7 +1359,7 @@ void fp_qmm( xi * scale * static_cast(FP4_LUT[(w_local[0] >> 4) & 0xf]); } else { (*result_local++) += - xi * scale * static_cast(detail::FromFP8{}(w_local[0])); + xi * scale * static_cast(FP8_LUT[w_local[0]]); } w_local++; } @@ -488,72 +1369,355 @@ void fp_qmm( } } +// Helper for computing a range of output columns in fp_qmm_t (used by threaded +// version) template -void fp_qmm_t( +void fp_qmm_t_cols( T* result, const T* x, const uint32_t* w, const uint8_t* scales, - int M, - int N, - int K) { + 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; - for (int m = 0; m < M; m++) { - const uint8_t* w_local = (const uint8_t*)w; - const uint8_t* scales_local = scales; + // 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; - 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 = dequantize_scale(*scales_local++); + // Move to next column + w_base += bytes_per_col; + scales_base += groups_per_col; + } +} - 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(detail::FromFP8{}(w_local[0])); +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++; } - w_local++; + sum += scale * gsum; } - sum += scale * gsum; + *result = sum; + result++; } - *result = sum; - result++; } - x += K; } } +#if !defined(MLX_USE_HIGHWAY) template -simd::Simd fp_extract_bits_simd(const uint32_t* w) { - if constexpr (S == 8 && bits == 4) { +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; - simd::Simd w_out; - for (int i = 0; i < S; ++i) { - w_out[i] = FP4_LUT[wi[i]]; - } - return w_out; + return fp4_lut_lookup_simd(wi, FP4_LUT); } else if constexpr (S == 8 && bits == 8) { - auto w_out = simd::load(reinterpret_cast(w)); - return detail::FromFP8{}(w_out); + // 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) + 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, @@ -562,40 +1726,58 @@ void fp_qmm_t_simd( const uint8_t* scales, int M, int N, - int K) { + int K, + float scale_factor) { 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 S = simd::max_size; static_assert( - S % pack_factor == 0, "SIMD size must be divisible by pack factor"); - constexpr int packs_per_simd = S / pack_factor; - - for (int m = 0; m < M; m++) { - const uint32_t* w_local = w; - const uint8_t* scales_local = scales; - - for (int n = 0; n < N; n++) { - simd::Simd acc(0); - auto x_local = x; - for (int k = 0; k < K; k += group_size) { - T scale = dequantize_scale(*scales_local++); - - simd::Simd g_acc(0); - for (int kw = 0; kw < packs_in_group; kw += packs_per_simd) { - // Extract bits - auto wf = fp_extract_bits_simd(w_local); - w_local += packs_per_simd; - simd::Simd x_simd = simd::load(x_local); - g_acc = g_acc + x_simd * wf; - x_local += S; + 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); + } } - acc = acc + scale * g_acc; + my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); } - - *result = T(simd::sum(acc)); - result++; + }); + } 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); } - x += K; } } @@ -608,16 +1790,23 @@ void fp_qmm_dispatch_transpose( int M, int N, int K, - bool transposed_w) { + bool transposed_w, + float scale_factor) { if (transposed_w) { - // the simd size must be a multiple of the number of elements per word - if constexpr (simd::max_size % 8 == 0) { - fp_qmm_t_simd(result, x, w, scales, M, N, K); + // 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); + fp_qmm_t( + result, x, w, scales, M, N, K, scale_factor); } } else { - fp_qmm(result, x, w, scales, M, N, K); + fp_qmm(result, x, w, scales, M, N, K, scale_factor); } } @@ -627,7 +1816,8 @@ void fp_qmm_dispatch_mode( const array& x, const array& w, const array& scales, - bool transposed_w) { + 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); @@ -648,7 +1838,8 @@ void fp_qmm_dispatch_mode( M, N, K, - transposed_w); + transposed_w, + scale_factor); } } @@ -660,13 +1851,17 @@ void fp_qmm_dispatch_typed( const array& scales, int group_size, int bits, - bool transposed_w) { + bool transposed_w, + float scale_factor) { if (bits == 8) { - fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); + 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); + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, scale_factor); } else { - fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, scale_factor); } } @@ -677,19 +1872,20 @@ void fp_qmm_dispatch( const array& scales, int group_size, int bits, - bool transposed_w) { + 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); + 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); + 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); + out, x, w, scales, group_size, bits, transposed_w, scale_factor); break; default: throw std::invalid_argument( @@ -724,25 +1920,44 @@ void _bs_qmm_dispatch_typed( auto lhs_indices_ptr = lhs_indices.data(); auto rhs_indices_ptr = rhs_indices.data(); - for (int i = 0; i < lhs_indices.size(); i++) { + // 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())]; - int w_idx = rhs_indices_ptr[elem_to_loc( + 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 + elem_to_loc(x_idx * M * K, x.shape(), x.strides()), + 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, + M * batch_count, N, K, bits, group_size, transposed_w); + i += batch_count; } } @@ -825,21 +2040,73 @@ void fp_bs_qmm_dispatch_mode( auto lhs_indices_ptr = lhs_indices.data(); auto rhs_indices_ptr = rhs_indices.data(); - for (int i = 0; i < lhs_indices.size(); i++) { + 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 + elem_to_loc(x_idx * M * K, x.shape(), x.strides()), - 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()), - M, + x_ptr + x_offsets[i], + w_ptr + w_offsets[i], + scales_ptr + s_offsets[i], + M * batch_count, N, K, - transposed_w); + transposed_w, + 1.0f); + i += batch_count; } } @@ -919,6 +2186,111 @@ void fp_bs_qmm_dispatch( } } +// 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 { + // mxfp8: fp8_e8m0 scale (pure exponent, 2^round(log2(x))) + if (raw_scale == 0.0f) { + scale = 1.0f; // 2^0 when all values are zero + } else { + float exp = std::round(std::log2(raw_scale)); + scale = std::pow(2.0f, exp); + } + } + + 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; + int best_idx = 0; + float best_dist = std::abs(normalized - FP4_LUT[0]); + for (int j = 1; j < 16; j++) { + float dist = std::abs(normalized - FP4_LUT[j]); + if (dist < best_dist) { + best_dist = dist; + best_idx = j; + } + } + gp[i] = static_cast(FP4_LUT[best_idx] * 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 QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { @@ -927,9 +2299,20 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { auto& scales_pre = inputs[2]; auto& encoder = cpu::get_command_encoder(stream()); - auto x = ensure_row_contiguous(x_pre, encoder, stream()); - auto w = ensure_row_contiguous(w_pre, encoder, stream()); - auto scales = ensure_row_contiguous(scales_pre, 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())); @@ -938,7 +2321,7 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { encoder.set_input_array(scales); encoder.set_output_array(out); if (mode_ == QuantizationMode::Affine) { - auto biases = ensure_row_contiguous(inputs[3], encoder, stream()); + 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), @@ -1046,114 +2429,6 @@ void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { } } -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; -} - -template -void fp_quantize_dequantize( - const array& w_arr, - array& out_arr, - int bits, - int group_size, - size_t w_size) { - auto w = w_arr.data(); - auto out = out_arr.data(); - - size_t n_groups = w_size / group_size; - - for (size_t i = 0; i < n_groups; ++i) { - size_t idx = i * group_size; - float scale = -std::numeric_limits::infinity(); - for (int j = 0; j < group_size; ++j) { - scale = std::max(scale, std::abs(w[idx + j])); - } - scale /= bits == 4 ? 6.0f : 448.0f; - if (group_size == 16) { - scale = dequantize_scale(detail::ToFP8()(scale)); - } else { - scale = dequantize_scale(to_fp8_e8m0_round_up(scale)); - } - - for (int j = 0; j < group_size; ++j) { - float w_el = scale == 0 ? 0.0f : w[idx + j] / scale; - float output; - if (bits == 8) { - output = detail::FromFP8()(detail::ToFP8()(w_el)); - } else { - output = FP4_LUT[to_fp4_e2m1(w_el)]; - } - out[idx + j] = static_cast(scale * output); - } - } -} - -void dispatch_quantize_dequantize( - const array& w, - array& out, - int bits, - int group_size) { - if (w.dtype() == float16) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); - } else if (w.dtype() == bfloat16) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); - } else if (w.dtype() == float32) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); - } else { - throw std::runtime_error( - "[quantize_dequantize] Only supports floating point inputs"); - } -} - template void quantize( const T* w, @@ -1238,8 +2513,15 @@ void dispatch_quantize( void fast::Quantize::eval_cpu( const std::vector& inputs, std::vector& outputs) { - auto& encoder = cpu::get_command_encoder(stream()); - auto w = ensure_row_contiguous(inputs[0], encoder, stream()); + 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())); @@ -1247,6 +2529,10 @@ void fast::Quantize::eval_cpu( 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); @@ -1330,42 +2616,67 @@ void fast::ConvertFP8::eval_cpu( void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { auto& encoder = cpu::get_command_encoder(stream()); - - bool w_quantized = (inputs[1].dtype() == uint32); - if (w_quantized && inputs[0].shape(-2) == 1) { - bool donate_x = inputs[0].is_donatable(); - auto x = ensure_row_contiguous(inputs[0], encoder, stream()); - auto w = ensure_row_contiguous(inputs[1], encoder, stream()); - auto scales = ensure_row_contiguous(inputs[2], encoder, stream()); - - out.set_data(allocator::malloc(out.nbytes())); - - // If x is a copy it should be donatable - donate_x |= x.is_donatable(); - auto xhat = donate_x - ? x - : array(allocator::malloc(x.nbytes()), x.shape(), x.dtype()); - if (!donate_x) { - encoder.add_temporary(xhat); + 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; } - encoder.set_input_array(x); - encoder.set_input_array(w); - encoder.set_input_array(scales); - encoder.set_output_array(out); - encoder.dispatch([out = array::unsafe_weak_copy(out), - x = array::unsafe_weak_copy(x), - xhat = array::unsafe_weak_copy(xhat), - w = array::unsafe_weak_copy(w), - scales = array::unsafe_weak_copy(scales), - group_size_ = group_size_, - bits_ = bits_]() mutable { - dispatch_quantize_dequantize(x, xhat, bits_, group_size_); - fp_qmm_dispatch(out, xhat, w, scales, group_size_, bits_, true); - }); - return; - } else { - throw std::runtime_error("[QQMatmul] NYI for the general case"); + }; + + 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) { 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..05b59ef396 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -0,0 +1,906 @@ +// Copyright © 2026 Apple Inc. + +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/quantized_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep + +#include "mlx/backend/cpu/quantized_highway.h" + +#include "hwy/highway.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; + +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 hn::PromoteTo( + 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 +hn::Vec unpack_4bit_lanes(DU8 du8, const uint32_t* words) { + const auto packed = hn::LoadN( + du8, reinterpret_cast(words), hn::Lanes(du8) / 2); + 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); + return hn::ConcatLowerLower( + du8, hn::InterleaveUpper(du8, lo, hi), hn::InterleaveLower(lo, hi)); +} + +template +void qmm_t_int8_cols( + 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, + 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; + + const hn::CappedTag di8; + const hn::RebindToUnsigned du8; + const hn::Repartition di16; + const hn::Repartition di32; + const size_t lanes = hn::Lanes(di8); + const auto ones16 = hn::Set(di16, int16_t{1}); + + float accum[NC] = {}; + + for (int g = 0; g < groups_per_col; ++g) { + hn::Vec dot_acc[NC]; + for (int c = 0; c < NC; ++c) { + dot_acc[c] = hn::Zero(di32); + } + + const int8_t* x_group = x_q + g * group_size; + for (int elem = 0; elem < group_size; elem += static_cast(lanes)) { + const auto x_vec = hn::LoadU(di8, x_group + elem); + for (int c = 0; c < NC; ++c) { + const uint32_t* w_group = + w + (n + c) * packs_per_col + g * packs_in_group; + hn::Vec w_vec; + if constexpr (bits == 4) { + w_vec = unpack_4bit_lanes(du8, w_group + elem / pack_factor); + const auto prod16 = hn::SatWidenMulPairwiseAdd(di16, w_vec, x_vec); + dot_acc[c] = hn::Add( + dot_acc[c], hn::WidenMulPairwiseAdd(di32, prod16, ones16)); + } else { + const auto* w_bytes = + reinterpret_cast(w_group) + elem; + w_vec = hn::LoadU(du8, w_bytes); + const auto low7 = hn::And(w_vec, hn::Set(du8, uint8_t{0x7F})); + const auto high_bit = hn::ShiftRight<7>(w_vec); + const auto low16 = hn::SatWidenMulPairwiseAdd(di16, low7, x_vec); + const auto high16 = hn::SatWidenMulPairwiseAdd(di16, high_bit, x_vec); + dot_acc[c] = hn::Add( + dot_acc[c], + hn::Add( + hn::WidenMulPairwiseAdd(di32, low16, ones16), + hn::ShiftLeft<7>( + hn::WidenMulPairwiseAdd(di32, high16, ones16)))); + } + } + } + + 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 float dot = static_cast(hn::ReduceSum(di32, dot_acc[c])); + accum[c] += scale_f * xs * dot + bias_f * xgs; + } + } + + for (int c = 0; c < NC; ++c) { + result[c] = 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 = 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]); + + 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 == 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::StoreU( + 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) { + 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 bits, + int group_size, + int n_start, + int n_end, + int K) { + int out = 0; + int n = n_start; + for (; n + 8 <= n_end; n += 8, out += 8) { + if (bits == 4) { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } else { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } + } + for (; n + 4 <= n_end; n += 4, out += 4) { + if (bits == 4) { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } else { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } + } + for (; n < n_end; ++n, ++out) { + if (bits == 4) { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } else { + qmm_t_int8_cols( + result + out, + x_q, + x_scales, + x_group_sums, + w, + scales, + biases, + group_size, + n, + K); + } + } +} + +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) { + switch (dtype) { + case QuantizedHighwayDType::Float32: + QmmTInt8RowTyped( + 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: + QmmTInt8RowTyped( + 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: + QmmTInt8RowTyped( + result, + x_q, + x_scales, + x_group_sums, + w, + static_cast(scales), + static_cast(biases), + bits, + group_size, + n_start, + n_end, + K); + break; + } +} + +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); + + const hn::Rebind du32; + if (lanes == 8) { + 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 di32; + const hn::Rebind du8; + const size_t lanes = hn::Lanes(df); + const auto* bytes = reinterpret_cast(w); + const int base = elem_off * static_cast(lanes); + const auto indices = hn::PromoteTo(di32, hn::LoadU(du8, bytes + base)); + return hn::GatherIndex(df, fp8_lut, indices); +} + +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 : (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); + + 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 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); + } +} + +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) { + 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 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) { + 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) { + 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 { + +HWY_EXPORT(DequantRow4Bit); +HWY_EXPORT(DequantRow8Bit); +HWY_EXPORT(QuantizeActivationInt8); +HWY_EXPORT(QmmTInt8Row); +HWY_EXPORT(FpQmmTHighwayRow); + +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); +} + +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); +} + +} // namespace mlx::core +#endif // HWY_ONCE diff --git a/mlx/backend/cpu/quantized_highway.h b/mlx/backend/cpu/quantized_highway.h new file mode 100644 index 0000000000..596f47808e --- /dev/null +++ b/mlx/backend/cpu/quantized_highway.h @@ -0,0 +1,296 @@ +// Copyright © 2026 Apple Inc. +// +// Highway implementations for quantized CPU helpers. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#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 { + +constexpr bool has_simd_qmm = true; + +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"); + } +} + +template <> +struct LoadAsFloat { + static inline simd::Simd apply(const float16_t* ptr) { + return simd::Simd(simd::load(ptr)); + } +}; + +template <> +struct LoadAsFloat { + static inline simd::Simd apply(const bfloat16_t* ptr) { + return simd::Simd(simd::load(ptr)); + } +}; + +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); + +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); + +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 (!env::enable_tf32()) { + 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 (!env::enable_tf32()) { + 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/reduce.cpp b/mlx/backend/cpu/reduce.cpp index 04965690be..0e1083356e 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include #include @@ -7,6 +7,7 @@ #include "mlx/backend/common/reduce.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/primitives.h" namespace mlx::core { @@ -107,20 +108,84 @@ void strided_reduce( } }; +// 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; +}; + template void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) { - constexpr int N = std::min(simd::max_size, simd::max_size); - simd::Simd accumulator_v(init); + using A = typename AccumType::type; + constexpr int N = std::min(simd::max_size, simd::max_size); + + simd::Simd accumulator_v(static_cast(init)); while (size >= N) { - accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); + accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); x += N; size -= N; } - *accumulator = op(*accumulator, op(accumulator_v)); + + A simd_sum = op(accumulator_v); // horizontal reduction + A scalar_acc = op(static_cast(*accumulator), simd_sum); + while (size-- > 0) { - *accumulator = op(*accumulator, *x); + scalar_acc = op(scalar_acc, static_cast(*x)); x++; } + *accumulator = static_cast(scalar_acc); +} + +// Parallel version for large reductions +template +U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { + 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 + // Use cache-line aligned storage to avoid false sharing + constexpr size_t CACHE_LINE = 64; + constexpr size_t PADDED_SIZE = + (sizeof(U) + CACHE_LINE - 1) / CACHE_LINE * CACHE_LINE; + std::vector partial_storage(n_threads * PADDED_SIZE); + + 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); + + U* partial = + reinterpret_cast(partial_storage.data() + tid * PADDED_SIZE); + *partial = init; + + if (start < end) { + contiguous_reduce( + x + start, partial, static_cast(end - start), op, init); + } + }); + + // Final reduction of partial results + U result = init; + for (int i = 0; i < n_threads; ++i) { + U* partial = reinterpret_cast(partial_storage.data() + i * PADDED_SIZE); + result = op(result, *partial); + } + return result; } // Helper for the ndimensional strided loop @@ -158,16 +223,47 @@ void reduction_op( auto in_ptr = x.data(); auto out_ptr = out.data(); if (plan.type == ContiguousAllReduce) { - *out_ptr = init; - contiguous_reduce(in_ptr, out_ptr, x.size(), Op{}, init); + // Use parallel reduction for large arrays + *out_ptr = parallel_contiguous_reduce(in_ptr, x.size(), Op{}, init); return; } if (plan.type == ContiguousReduce && plan.shape.size() == 1) { int reduction_size = plan.shape[0]; - 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); + 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); + } + }); } return; } diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp new file mode 100644 index 0000000000..66977b0b40 --- /dev/null +++ b/mlx/backend/cpu/rope.cpp @@ -0,0 +1,565 @@ +// Copyright © 2026 Apple Inc. + +#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" +#include "mlx/backend/cpu/threading/common.h" +#include "mlx/fast_primitives.h" + +#if defined(MLX_USE_HIGHWAY) +#include "mlx/backend/cpu/rope_highway.h" +#endif + +namespace mlx::core::fast { + +// ISA-specific SIMD implementations for RoPE. When AVX2 is enabled on this +// branch, Highway is the implementation substrate. +#if !defined(MLX_USE_HIGHWAY) +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 + +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) + j = rope_non_traditional_highway_simd( + x_in, x_out, cos_t, sin_t, half_dims); +#endif +#if !defined(MLX_USE_HIGHWAY) + 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) + j = rope_traditional_highway_simd( + x_in, x_out, cos_t, sin_t, half_dims); +#endif +#if !defined(MLX_USE_HIGHWAY) + 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) { + 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 + auto& offset_arr = inputs[1]; + bool per_batch_offset = offset_arr.size() > 1; + bool has_freqs = inputs.size() == 3; + + // Set up command encoder + auto& encoder = cpu::get_command_encoder(stream()); + encoder.set_input_array(x); + encoder.set_input_array(offset_arr); + if (has_freqs) { + encoder.set_input_array(inputs[2]); + } + 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 ? inputs[2].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 diff --git a/mlx/backend/cpu/rope_highway.cpp b/mlx/backend/cpu/rope_highway.cpp new file mode 100644 index 0000000000..b2d7c3ac21 --- /dev/null +++ b/mlx/backend/cpu/rope_highway.cpp @@ -0,0 +1,387 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cpu/rope_highway.h" + +#undef HWY_TARGET_INCLUDE +#define HWY_TARGET_INCLUDE "mlx/backend/cpu/rope_highway.cpp" +#include "hwy/foreach_target.h" // IWYU pragma: keep + +#include "hwy/highway.h" + +HWY_BEFORE_NAMESPACE(); +namespace mlx::core::fast { +namespace HWY_NAMESPACE { +namespace { + +namespace hn = hwy::HWY_NAMESPACE; + +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 hn::PromoteTo( + 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 = hn::PromoteTo(df, x0h); + x1 = hn::PromoteTo(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); + } +} + +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) { + *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) { + *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) { + *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) { + *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 { + +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; +} + +} // namespace mlx::core::fast +#endif // HWY_ONCE 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/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp new file mode 100644 index 0000000000..28464fb9c0 --- /dev/null +++ b/mlx/backend/cpu/sdpa.cpp @@ -0,0 +1,943 @@ +// Copyright © 2026 Apple Inc. + +#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" +#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."); + } + + 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,), always contiguous + auto sinks_arr = + has_sinks_ ? std::optional(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); + } + + 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([=]() { + 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); + }); + 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([=]() { + 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); + }); + 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([=]() { + 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); + }); + break; + } + default: + throw std::runtime_error( + "[ScaledDotProductAttention::eval_cpu] Unsupported type"); + } +} + +} // namespace mlx::core::fast diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index 626dd93df9..61b9cc383e 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -1,16 +1,23 @@ #pragma once -// Required for using M_LN2 in MSVC. +#ifdef _MSC_VER +#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES +#endif +#include +#endif -#include #include #include +#include #include #include +#include -#ifdef _MSC_VER -#include // For _BitScanReverse +// 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 #include "mlx/types/complex.h" @@ -32,23 +39,47 @@ struct Simd { Simd(Simd v) : value(v.value) {} template Simd(U v) : value(v) {} +}; - T operator[](int) const { - return value; - } +namespace detail { - T& operator[](int) { - return value; - } +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 + template Simd load(const T* x) { - return *(Simd*)x; + if constexpr (detail::HasStaticLoad, T>::value) { + return Simd::load(x); + } else { + return *(Simd*)x; + } } template void store(T* dst, Simd x) { + if constexpr (detail::HasMemberStore, T>::value) { + x.store(dst); + return; + } // 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) { @@ -193,12 +224,8 @@ DEFAULT_BINARY(||) template Simd clz(Simd x_) { #ifdef _MSC_VER - // 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 + unsigned long idx; + return _BitScanReverse(&idx, (unsigned long)x_.value) ? (31 - idx) : 32; #else return __builtin_clz(x_.value); #endif @@ -229,7 +256,7 @@ Simd remainder(Simd a_, Simd b_) { } r = a % b; } else { - r = std::remainder(a, b); + r = std::fmod(a, b); } if constexpr (is_signed_v) { if (r != 0 && (r < 0 != b < 0)) { @@ -244,6 +271,9 @@ Simd maximum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { + if (std::isnan(b)) { + return b; + } if (mlx::core::isnan(a)) { return a; } @@ -256,6 +286,9 @@ Simd minimum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { + if (std::isnan(b)) { + return b; + } 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..e9b1f1a3cc --- /dev/null +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -0,0 +1,877 @@ +// 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; + +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = 4; +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = 8; +template <> +inline constexpr int max_size = 8; + +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); +} + +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) { + bits[0] = static_cast((1u << N) - 1u); + } + } + + template + explicit BoolSimdBase(Simd value) { + using D = highway_detail::D; + const D d; + hn::StoreMaskBits(d, hn::MaskFromVec(value.value), 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(4) +MLX_HIGHWAY_BOOL_SIMD(8) +#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) { + 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)) { + 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] = static_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]; + } +}; + +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 = 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 +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 static_cast(x / y); }); + } 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; + } +} + +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; + } +} + +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::Floor(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::Ceil(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::Round(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 { + Simd out; + out.value = hn::MulAdd(x.value, y.value, Simd(z).value); + return out; + } +} + +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) { + T r = static_cast(x % y); + if constexpr (std::is_signed_v) { + if (r != 0 && ((r < 0) != (y < 0))) { + r = static_cast(r + y); + } + } + return r; + }); + } else { + return highway_detail::map_binary(a, b, [](float x, float y) { + float 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) { + T result = 1; + while (y) { + if (y & 1) { + result = static_cast(result * x); + } + y = static_cast(y >> 1); + x = static_cast(x * x); + } + return result; + }); + } else { + return highway_detail::map_binary( + base, exp, [](float x, float y) { return std::pow(x, y); }); + } +} + +template = 0> +inline Simd atan2(Simd a, Simd b) { + return highway_detail::map_binary( + a, b, [](float x, float 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, [](float v) { return static_cast(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 + +} // namespace mlx::core::simd +HWY_AFTER_NAMESPACE(); diff --git a/mlx/backend/cpu/simd/math.h b/mlx/backend/cpu/simd/math.h index 88676323a5..c731f1c748 100644 --- a/mlx/backend/cpu/simd/math.h +++ b/mlx/backend/cpu/simd/math.h @@ -1,8 +1,10 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #pragma once #include "mlx/backend/cpu/simd/type.h" +#include "mlx/types/complex.h" +#include "mlx/types/half_types.h" namespace mlx::core::simd { @@ -154,57 +156,92 @@ Simd cos(Simd x) { template Simd erf(Simd x) { // https://github.com/pytorch/pytorch/blob/abf28982a8cb43342e7669d859de9543fd804cc9/aten/src/ATen/cpu/vec/vec256/vec256_float.h#L175 - 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); + // 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)); auto e = -exp(-v * v); - auto result = Simd(fma(e * t, r, 1.0f)); - return select(x > 0, result, -result); + auto result = Simd(fma(e * t, r, ComputeT(1.0f))); + return select(x > ComputeT(0), result, -result); +} + +template +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 Simd erfinv(Simd a_) { - Simd a = a_; - auto t = fma(a, 0.0f - a, 1.0f); + // 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)); t = log(t); auto lhs = [](auto t) { - Simd p; - p = 3.03697567e-10f; // 0x1.4deb44p-32 - p = fma(p, t, 2.93243101e-8f); // 0x1.f7c9aep-26 - p = fma(p, t, 1.22150334e-6f); // 0x1.47e512p-20 - p = fma(p, t, 2.84108955e-5f); // 0x1.dca7dep-16 - p = fma(p, t, 3.93552968e-4f); // 0x1.9cab92p-12 - p = fma(p, t, 3.02698812e-3f); // 0x1.8cc0dep-9 - 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 + 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 }; auto rhs = [](auto t) { - Simd p; - p = 5.43877832e-9f; // 0x1.75c000p-28 - p = fma(p, t, 1.43285448e-7f); // 0x1.33b402p-23 - p = fma(p, t, 1.22774793e-6f); // 0x1.499232p-20 - p = fma(p, t, 1.12963626e-7f); // 0x1.e52cd2p-24 - p = fma(p, t, -5.61530760e-5f); // -0x1.d70bd0p-15 - p = fma(p, t, -1.47697632e-4f); // -0x1.35be90p-13 - p = fma(p, t, 2.31468678e-3f); // 0x1.2f6400p-9 - 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 + 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 }; - auto thresh = 6.125f; + auto thresh = ComputeT(6.125f); // Compute both branches and select if N > 1 if constexpr (N == 1) { if ((abs(t) > thresh).value) { // maximum ulp error = 2.35793 - return a * lhs(t); + return Simd(a * lhs(t)); } else { // maximum ulp error = 2.35002 - return a * rhs(t); + return Simd(a * rhs(t)); } } else { - return a * select(abs(t) > thresh, lhs(t), rhs(t)); + return Simd(a * select(abs(t) > thresh, lhs(t), rhs(t))); } } diff --git a/mlx/backend/cpu/simd/type.h b/mlx/backend/cpu/simd/type.h index 59b6ecca30..b0d6de91da 100644 --- a/mlx/backend/cpu/simd/type.h +++ b/mlx/backend/cpu/simd/type.h @@ -9,3 +9,10 @@ #include "mlx/backend/cpu/simd/accelerate_simd.h" #endif #endif + +// x86 SIMD: MLX_ENABLE_AVX2 uses Highway as the implementation substrate. +#if !defined(MLX_USE_ACCELERATE) +#if defined(MLX_USE_HIGHWAY) +#include "mlx/backend/cpu/simd/highway_simd.h" +#endif +#endif diff --git a/mlx/backend/cpu/softmax.cpp b/mlx/backend/cpu/softmax.cpp index d62e86a9c3..2b5c474de5 100644 --- a/mlx/backend/cpu/softmax.cpp +++ b/mlx/backend/cpu/softmax.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include #include @@ -6,6 +6,7 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/dtype_utils.h" #include "mlx/primitives.h" #include "mlx/types/limits.h" @@ -16,6 +17,90 @@ namespace { using namespace mlx::core::simd; +// Process a single row of softmax +template +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 + Simd vnormalizer(0.0); + current_out_ptr = out_ptr; + current_in_ptr = in_ptr; + s = M; + while (s >= 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; + s -= N; + } + AccT normalizer = sum(vnormalizer); + while (s-- > 0) { + AccT _exp = std::exp(*current_in_ptr - maximum); + if constexpr (same_t) { + *current_out_ptr = _exp; + } + normalizer += _exp; + current_in_ptr++; + current_out_ptr++; + } + 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 void softmax(const array& in, array& out, Stream stream) { auto& encoder = cpu::get_command_encoder(stream); @@ -28,89 +113,41 @@ void softmax(const array& in, array& out, Stream stream) { int M = in.shape().back(); int L = in.data_size() / M; - 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); - - const T* current_in_ptr; - T* current_out_ptr; - - for (int i = 0; i < L; i++, in_ptr += M, out_ptr += M) { - // 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 - Simd vnormalizer(0.0); - current_out_ptr = out_ptr; - current_in_ptr = in_ptr; - s = M; - while (s >= 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; - s -= N; - } - AccT normalizer = sum(vnormalizer); - while (s-- > 0) { - AccT _exp = std::exp(*current_in_ptr - maximum); - if constexpr (same_t) { - *current_out_ptr = _exp; - } - normalizer += _exp; - current_in_ptr++; - current_out_ptr++; - } - 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++; + // 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; + } + + 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); + + const T* row_in = in_ptr + row_start * M; + T* row_out = out_ptr + row_start * M; + + for (int i = row_start; i < row_end; i++) { + softmax_row(row_in, row_out, M); + row_in += M; + row_out += M; } - current_out_ptr++; + }); + }); + } 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); } - } - }); + }); + } } } // namespace diff --git a/mlx/backend/cpu/threading/CMakeLists.txt b/mlx/backend/cpu/threading/CMakeLists.txt new file mode 100644 index 0000000000..5a313d5cfc --- /dev/null +++ b/mlx/backend/cpu/threading/CMakeLists.txt @@ -0,0 +1,21 @@ +# Threading backend selection +# +# Uses platform-aligned thread pools: - macOS: Grand Central Dispatch (GCD) - +# Linux/Windows: persistent threading with optional OpenBLAS coordination + +set(THREADING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/common.cpp) + +# Select platform-specific implementation +if(APPLE) + message(STATUS "Threading: Using Accelerate/GCD for macOS") + list(APPEND THREADING_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/accelerate/thread_pool.mm) + target_sources(mlx PRIVATE ${THREADING_SOURCES}) + target_compile_definitions(mlx PRIVATE MLX_THREADING_ACCELERATE) +else() + message(STATUS "Threading: Using persistent CPU threading") + list(APPEND THREADING_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/openblas/thread_pool.cpp) + target_sources(mlx PRIVATE ${THREADING_SOURCES}) + target_compile_definitions(mlx PRIVATE MLX_THREADING_OPENBLAS) +endif() diff --git a/mlx/backend/cpu/threading/accelerate/thread_pool.h b/mlx/backend/cpu/threading/accelerate/thread_pool.h new file mode 100644 index 0000000000..50fb8ba079 --- /dev/null +++ b/mlx/backend/cpu/threading/accelerate/thread_pool.h @@ -0,0 +1,33 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/backend/cpu/threading/base.h" + +namespace mlx::core::cpu { + +/** + * macOS thread pool implementation using Grand Central Dispatch (GCD). + * + * GCD is a system-wide thread pool managed by the macOS kernel. + * Benefits: + * - No thread management overhead in userspace + * - Automatic thread count optimization + * - Integration with system scheduler + * - No conflicts with Accelerate framework + */ +class AccelerateThreadPool : public ThreadPoolBackend { + public: + AccelerateThreadPool(); + ~AccelerateThreadPool() override = default; + + void parallel_for(int n_threads, std::function f) + override; + + int max_threads() const override; + + private: + int max_threads_; +}; + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/accelerate/thread_pool.mm b/mlx/backend/cpu/threading/accelerate/thread_pool.mm new file mode 100644 index 0000000000..bca18f583c --- /dev/null +++ b/mlx/backend/cpu/threading/accelerate/thread_pool.mm @@ -0,0 +1,65 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cpu/threading/accelerate/thread_pool.h" + +#include +#include +#include +#include + +namespace mlx::core::cpu { + +AccelerateThreadPool::AccelerateThreadPool() + : max_threads_(std::thread::hardware_concurrency()) {} + +void AccelerateThreadPool::parallel_for( + int n_threads, + std::function f) { + if (n_threads <= 1) { + f(0, 1); + return; + } + + // Clamp to max_threads + n_threads = std::min(n_threads, max_threads_); + + // Use GCD's dispatch_apply for parallel execution. + // This uses the system-wide thread pool managed by the kernel. + // Capture any exception from worker blocks since GCD blocks cannot + // propagate C++ exceptions (they would std::terminate). + // Use heap-allocated state because __block storage copies non-copyable types. + struct ExState { + std::exception_ptr eptr{nullptr}; + std::atomic taken{false}; + }; + auto ex = std::make_shared(); + + dispatch_apply( + n_threads, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), + ^(size_t i) { + try { + f(static_cast(i), n_threads); + } catch (...) { + bool expected = false; + if (ex->taken.compare_exchange_strong(expected, true)) { + ex->eptr = std::current_exception(); + } + } + }); + + if (ex->eptr) { + std::rethrow_exception(ex->eptr); + } +} + +int AccelerateThreadPool::max_threads() const { + return max_threads_; +} + +// Factory function implementation +std::unique_ptr create_thread_pool_backend() { + return std::make_unique(); +} + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/base.h b/mlx/backend/cpu/threading/base.h new file mode 100644 index 0000000000..128d854397 --- /dev/null +++ b/mlx/backend/cpu/threading/base.h @@ -0,0 +1,49 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include +#include + +namespace mlx::core::cpu { + +/** + * Pure virtual interface for platform-specific thread pool implementations. + * + * This interface abstracts the threading mechanism so different platforms + * can use their respective thread pools: + * - macOS: Grand Central Dispatch (GCD) + * - Linux/Windows: persistent threading with optional OpenBLAS coordination + */ +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 platform-specific thread pool backend. + * Implemented in platform-specific files (accelerate/thread_pool.mm, + * 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..1f6452bb34 --- /dev/null +++ b/mlx/backend/cpu/threading/common.cpp @@ -0,0 +1,30 @@ +// Copyright © 2026 Apple Inc. + +#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 diff --git a/mlx/backend/cpu/threading/common.h b/mlx/backend/cpu/threading/common.h new file mode 100644 index 0000000000..95cedfa19c --- /dev/null +++ b/mlx/backend/cpu/threading/common.h @@ -0,0 +1,90 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#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. Uses platform-native thread pools for optimal performance: + * - macOS: Grand Central Dispatch (GCD) + * - Linux/Windows: persistent threading with optional OpenBLAS coordination + * + * 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 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/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp new file mode 100644 index 0000000000..fced82e4df --- /dev/null +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -0,0 +1,380 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cpu/threading/openblas/thread_pool.h" + +#include +#include + +// Spin-wait hint: reduces power consumption and avoids starving sibling +// hyperthreads during busy-wait loops. +#if defined(MLX_USE_HIGHWAY) +#include "hwy/cache_control.h" +#define MLX_SPIN_PAUSE() hwy::Pause() +#elif 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 int (*blas_get_threads)() = 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"); + blas_get_threads = (int (*)())GetProcAddress(h, "openblas_get_num_threads"); + } +} +static void set_blas_threads(int n) { + init_blas_funcs(); + if (blas_set_threads) + blas_set_threads(n); +} +static int get_blas_threads() { + init_blas_funcs(); + return blas_get_threads ? blas_get_threads() : 1; +} +#elif defined(__unix__) || defined(__linux__) +#include +static void (*blas_set_threads)(int) = nullptr; +static int (*blas_get_threads)() = 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"); + blas_get_threads = (int (*)())dlsym(RTLD_DEFAULT, "openblas_get_num_threads"); +} +static void set_blas_threads(int n) { + init_blas_funcs(); + if (blas_set_threads) + blas_set_threads(n); +} +static int get_blas_threads() { + init_blas_funcs(); + return blas_get_threads ? blas_get_threads() : 1; +} +#else +static void set_blas_threads(int n) { + (void)n; +} +static int get_blas_threads() { + return 1; +} +#endif + +// Physical core detection -- AVX2/FMA workloads get no benefit from SMT +// (hyperthreads share the same SIMD execution units, L1/L2 cache, and memory +// bandwidth). Using physical core count avoids over-subscription and reduces +// atomic/mutex contention in the thread pool. Benchmarked: 16 physical cores +// is +5-7% faster than logical core count for quantized LLM inference. +#ifdef _WIN32 +// Windows: already included above for OpenBLAS DLL resolution. +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; +} +#elif defined(__linux__) +#include +#include +#include +static int get_physical_cores() { + // Count unique (physical_package_id, core_id) pairs across all online CPUs. + // This handles multi-socket systems correctly. + std::set> cores; + for (int i = 0; i < 4096; i++) { + std::string base = + "/sys/devices/system/cpu/cpu" + std::to_string(i) + "/topology/"; + std::ifstream cf(base + "core_id"); + if (!cf) + break; + int core_id, pkg_id = 0; + cf >> core_id; + std::ifstream pf(base + "physical_package_id"); + if (pf) + pf >> pkg_id; + cores.insert({pkg_id, core_id}); + } + return static_cast(cores.size()); +} +#else +static int get_physical_cores() { + return 0; // Unknown platform -- caller falls back to hardware_concurrency() +} +#endif + +namespace mlx::core::cpu { + +namespace { +int get_default_threads() { + if (const char* e = std::getenv("MLX_CPU_THREADS")) { + int n = std::atoi(e); + if (n > 0) + return n; + } + int physical = get_physical_cores(); + if (physical > 0) + return physical; + return std::max(1, (int)std::thread::hardware_concurrency()); +} +} // namespace + +CPUThreadPool::CPUThreadPool() + : max_threads_(std::min(get_default_threads(), 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(); + } + // Pin OpenBLAS to single-threaded unless user explicitly overrides via env + // var. This prevents over-subscription (our N threads + OpenBLAS's N threads + // competing for N cores). BLAS ops are still fully parallel because + // cblas.cpp calls cblas_sgemm from within parallel_for workers -- each worker + // runs single-threaded BLAS on its row slice, achieving full core + // utilization without internal BLAS threading. + if (!std::getenv("OPENBLAS_NUM_THREADS")) { + set_blas_threads(1); + } +} + +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::worker_loop(int worker_id) { + // Signal that this worker is ready and waiting for tasks. + ready_.fetch_add(1, std::memory_order_release); + uint64_t my_gen = gen_.load(std::memory_order_acquire); + + 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_, task_n_threads_, + // started_, 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. Task state is visible via the + // acquire load on wake_gen (happens-before from the main thread's + // release store on gen_). task_ptr_ is a raw pointer (naturally + // atomic on x86-64), so no std::function access race. + if (stop_) + return; + { + if (task_gen_.load(std::memory_order_acquire) != my_gen) + continue; + int nth = task_n_threads_.load(std::memory_order_acquire); + if (nth > 0 && started_.load(std::memory_order_relaxed) < nth) { + int slot = started_.fetch_add(1, std::memory_order_acq_rel); + if (slot < nth) { + (*task_ptr_)(slot, nth); + done_.fetch_add(1, std::memory_order_acq_rel); + } + } + } + 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(); + if (task_gen_.load(std::memory_order_acquire) != my_gen) + continue; + int nth = task_n_threads_.load(std::memory_order_acquire); + if (nth <= 0 || started_.load(std::memory_order_relaxed) >= nth) + continue; + int slot = started_.fetch_add(1, std::memory_order_acq_rel); + if (slot >= nth) + continue; + (*task_ptr_)(slot, nth); + done_.fetch_add(1, std::memory_order_acq_rel); + } + } +} + +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; + } + + // Serialize concurrent parallel_for calls from different CPU streams. + // All task state (task_ptr_, started_, 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_); + + 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 task state. task_ptr_ is a raw pointer (naturally atomic on + // x86-64). All relaxed stores below become visible to workers via the + // gen_.fetch_add(release) below, which provides happens-before for any + // thread that observes the new gen_ via acquire load. + task_ptr_ = &f; + task_n_threads_.store(n_threads, std::memory_order_relaxed); + started_.store(1, std::memory_order_relaxed); // slot 0 reserved for main + 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; + task_gen_.store(new_gen, 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 + (*task_ptr_)(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(); + } + } + + // Reset task state so late-waking workers (from spin or cv_wait) + // won't pass the started_ < task_n_threads_ check with stale values. + task_gen_.store(0, std::memory_order_release); + task_n_threads_.store(0, std::memory_order_release); + task_ptr_ = nullptr; +} + +int CPUThreadPool::max_threads() const { + return max_threads_; +} + +std::unique_ptr create_thread_pool_backend() { + return std::make_unique(); +} + +} // namespace mlx::core::cpu 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..6b983ecbab --- /dev/null +++ b/mlx/backend/cpu/threading/openblas/thread_pool.h @@ -0,0 +1,79 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include "mlx/backend/cpu/threading/base.h" + +#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(); + ~CPUThreadPool() override; + + void parallel_for(int n_threads, std::function f) + override; + int max_threads() const override; + + private: + void worker_loop(int worker_id); + + // 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_, started_, done_, etc.) is shared, concurrent calls + // must be serialized. The GCD backend (macOS) handles this implicitly + // via dispatch_apply; we need an explicit mutex. + std::mutex dispatch_mtx_; + + std::mutex mtx_; // worker sleep/wake coordination + std::condition_variable cv_; + + const std::function* task_ptr_ = nullptr; + std::atomic task_n_threads_{0}; + std::atomic started_{0}; + std::atomic done_{0}; + std::atomic ready_{0}; + std::atomic gen_{0}; + std::atomic task_gen_{0}; + std::atomic sleeping_count_{0}; // workers currently in cv_.wait + bool stop_ = false; + + 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..69289a75a6 100644 --- a/mlx/backend/cpu/unary.h +++ b/mlx/backend/cpu/unary.h @@ -1,10 +1,11 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #pragma once #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/simd/simd.h" +#include "mlx/backend/cpu/threading/common.h" #include "mlx/dtype_utils.h" #include "mlx/utils.h" @@ -18,6 +19,24 @@ void unary_op(const T* a, U* out, size_t shape, size_t stride) { } } +// 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++; + } +} + template void unary_op(const array& a, array& out, Op) { const T* src = a.data(); @@ -25,30 +44,70 @@ void unary_op(const array& a, array& out, Op) { auto ndim = a.ndim(); if (a.flags().contiguous) { auto size = a.data_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++; + + // 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); } } else { - size_t shape = ndim > 0 ? a.shape().back() : 1; - size_t stride = ndim > 0 ? a.strides().back() : 1; + size_t inner_shape = ndim > 0 ? a.shape().back() : 1; + size_t inner_stride = ndim > 0 ? a.strides().back() : 1; if (ndim <= 1) { - unary_op(src, dst, shape, stride); + unary_op(src, dst, inner_shape, inner_stride); return; } - 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(); + + 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(); + } } } } diff --git a/mlx/backend/cpu/unary_ops.h b/mlx/backend/cpu/unary_ops.h index e2dd7413f7..f8718acfa1 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -1,4 +1,4 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #pragma once @@ -77,8 +77,7 @@ struct Real { struct Sigmoid { template Simd operator()(Simd x) { - auto y = 1.0f / (1.0f + simd::exp(simd::abs(x))); - return simd::select(x < Simd{0}, y, Simd{1} - y); + return simd::sigmoid(x); } SINGLE() }; @@ -88,12 +87,12 @@ struct Sign { Simd operator()(Simd x) { auto z = Simd{0}; auto o = Simd{1}; - auto m = Simd{-1}; 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 { + auto m = Simd{-1}; return simd::select(x < z, m, simd::select(x > z, o, z)); } } @@ -154,19 +153,11 @@ struct ToFP8 { struct FromFP8 { template Simd operator()(Simd x) { - auto v = Simd(x & 127); - auto sign_bit = Simd((x >> 7) & 1) << 15; - auto u = (v << 7) | (((v + 1) >> 7) << 14) | sign_bit; - Simd out; - if constexpr (simd::max_size >= N) { - auto converted = *(Simd*)(&u); - out = converted * 256.0; - } else { - for (int i = 0; i < N; ++i) { - auto converted = *(float16_t*)(&u[i]); - out[i] = converted * 256.0; - } - } + auto v = Simd(x & 127) << 7; + auto converted = *(Simd*)(&v); + converted = converted * 256.0; + auto sign = Simd(x & 128); + Simd out = select(sign, -converted, converted); return out; } float operator()(uint8_t x) { diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index c37515f9ef..5bc7161846 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include "mlx/primitives.h" #include "mlx/distributed/primitives.h" @@ -34,6 +34,10 @@ bool fast::ScaledDotProductAttention::use_fallback( bool output_logsumexp, bool force_fused, Stream s) { + // Use native CPU kernel for inference (handles causal, array mask, sinks) + if (s.device == Device::cpu && !output_logsumexp) { + return false; + } if (force_fused) { throw std::invalid_argument( "[scaled_dot_product_attention] force_fused=True but no fused " @@ -182,11 +186,23 @@ NO_GPU(MaskedScatter) namespace fast { NO_GPU_USE_FALLBACK(CrossEntropy) NO_GPU_MULTI(CrossEntropyVJP) -NO_GPU_USE_FALLBACK(LayerNorm) +// 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) NO_GPU_MULTI(LayerNormVJP) -NO_GPU_USE_FALLBACK(RMSNorm) +bool RMSNorm::use_fallback(Stream s) { + return false; // Use native eval_cpu +} +NO_GPU_MULTI(RMSNorm) NO_GPU_MULTI(RMSNormVJP) -NO_GPU_USE_FALLBACK(RoPE) +// RoPE has native CPU implementation (rope.cpp) +bool RoPE::use_fallback(Stream s) { + return false; // Use native eval_cpu +} +NO_GPU_MULTI(RoPE) 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..f7e425af9a 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1,4 +1,4 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #include #include @@ -48,9 +48,7 @@ class RMSNorm : public Custom { static bool use_fallback(Stream stream); void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } + override; void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -81,9 +79,7 @@ class RMSNormVJP : public Custom { : Custom(stream, std::move(fallback)), eps_(eps) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } + override; void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -169,9 +165,7 @@ class LayerNorm : public Custom { static bool use_fallback(Stream s); void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } + override; void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -201,9 +195,7 @@ class LayerNormVJP : public Custom { : Custom(stream, std::move(fallback)), eps_(eps) {} void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } + override; void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -237,9 +229,7 @@ class RoPE : public Custom { static bool use_fallback(Stream s); void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } + override; void eval_gpu(const std::vector& inputs, std::vector& outputs) override; @@ -296,10 +286,7 @@ class ScaledDotProductAttention : public Custom { static bool supports_bool_mask(); void eval_cpu(const std::vector& inputs, std::vector& outputs) - override { - throw std::runtime_error("NYI"); - } - + override; 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 185019342a..6e26c9425b 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 @@ -1705,6 +1705,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 dafe65d42d..8f8742bc33 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -407,6 +407,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 318da6f677..35e811bc8f 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 @@ -45,6 +46,7 @@ target_sources( utils_tests.cpp vmap_tests.cpp linalg_tests.cpp + thread_pool_tests.cpp ${GPU_TEST_SOURCES}) target_link_libraries(tests PRIVATE mlx doctest) diff --git a/tests/fast_tests.cpp b/tests/fast_tests.cpp new file mode 100644 index 0000000000..73093a35da --- /dev/null +++ b/tests/fast_tests.cpp @@ -0,0 +1,506 @@ +// Copyright © 2026 Apple Inc. + +#include +#include +#include +#include +#include + +#include "doctest/doctest.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() { + 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) { + 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(); + const float* out = y.data(); + for (int i = 0; i < static_cast(expected.size()); ++i) { + CHECK(std::abs(out[i] - expected[i]) < 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(); +} + +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") { + check_quantized_matmul_token_typed(4, 1, 8e-3f); + check_quantized_matmul_token_typed(8, 1, 8e-3f); +} diff --git a/tests/thread_pool_tests.cpp b/tests/thread_pool_tests.cpp new file mode 100644 index 0000000000..dc904ddecd --- /dev/null +++ b/tests/thread_pool_tests.cpp @@ -0,0 +1,324 @@ +// Copyright © 2026 Apple Inc. + +#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::atomic finished{false}; + + std::thread watchdog([&] { + std::this_thread::sleep_for(std::chrono::seconds(5)); + if (!finished.load()) { + // Deadlock detected - force fail + FAIL("parallel_for deadlocked after exception"); + } + }); + watchdog.detach(); + + // 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 + } + + finished.store(true); + + // 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); +} From 231f5bf98af2a445e697031580c904737b9275fb Mon Sep 17 00:00:00 2001 From: Daniel Hiltgen Date: Thu, 28 May 2026 21:50:13 -0700 Subject: [PATCH 02/65] Adjust for runtime dynamic selection (cherry picked from commit a4e93db5e7175a835d6d6189df59dea83d4455d4) --- CMakeLists.txt | 14 +- mlx.pc.in | 2 +- mlx/backend/cpu/CMakeLists.txt | 212 +++- mlx/backend/cpu/compiled.cpp | 19 +- mlx/backend/cpu/compiled_preamble.h | 9 +- mlx/backend/cpu/gemms/cblas.cpp | 3 +- mlx/backend/cpu/gemms/simd_bf16.cpp | 409 +------ mlx/backend/cpu/gemms/simd_fp16.cpp | 406 +------ .../cpu/gemms/simd_low_precision_gemm.h | 402 +++++++ mlx/backend/cpu/highway_utils.h | 134 +++ mlx/backend/cpu/jit_compiler.cpp | 302 ++++- mlx/backend/cpu/make_compiled_preamble.ps1 | 42 +- mlx/backend/cpu/make_compiled_preamble.sh | 19 +- mlx/backend/cpu/norms.cpp | 196 +-- mlx/backend/cpu/norms_highway.cpp | 481 +++++++- mlx/backend/cpu/norms_highway.h | 42 + mlx/backend/cpu/norms_highway_dispatch.cpp | 230 ++++ mlx/backend/cpu/quantized.cpp | 65 +- mlx/backend/cpu/quantized_highway.cpp | 1052 ++++++++++++++--- mlx/backend/cpu/quantized_highway.h | 44 +- .../cpu/quantized_highway_dispatch.cpp | 331 ++++++ mlx/backend/cpu/reduce.cpp | 18 +- mlx/backend/cpu/rope.cpp | 18 +- mlx/backend/cpu/rope_highway.cpp | 214 ++-- mlx/backend/cpu/rope_highway_dispatch.cpp | 120 ++ mlx/backend/cpu/sdpa.cpp | 66 ++ mlx/backend/cpu/sdpa_highway.cpp | 579 +++++++++ mlx/backend/cpu/sdpa_highway.h | 34 + mlx/backend/cpu/sdpa_highway_dispatch.cpp | 130 ++ mlx/backend/cpu/simd/highway_simd.h | 86 +- mlx/backend/cpu/simd/type.h | 11 +- .../cpu/threading/openblas/thread_pool.cpp | 20 +- mlx/io/load.h | 2 +- tests/CMakeLists.txt | 11 +- tests/blas_tests.cpp | 21 +- tests/thread_pool_tests.cpp | 20 +- 36 files changed, 4398 insertions(+), 1366 deletions(-) create mode 100644 mlx/backend/cpu/gemms/simd_low_precision_gemm.h create mode 100644 mlx/backend/cpu/highway_utils.h create mode 100644 mlx/backend/cpu/norms_highway_dispatch.cpp create mode 100644 mlx/backend/cpu/quantized_highway_dispatch.cpp create mode 100644 mlx/backend/cpu/rope_highway_dispatch.cpp create mode 100644 mlx/backend/cpu/sdpa_highway.cpp create mode 100644 mlx/backend/cpu/sdpa_highway.h create mode 100644 mlx/backend/cpu/sdpa_highway_dispatch.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 62f9a61784..d1c6180759 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,19 +43,19 @@ 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) if(MLX_BUILD_CPU AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") - set(_AVX2_DEFAULT ON) + set(_X86_SIMD_DEFAULT ON) else() - set(_AVX2_DEFAULT OFF) + set(_X86_SIMD_DEFAULT OFF) endif() -option(MLX_ENABLE_AVX2 "Enable AVX2 SIMD on x86 (includes BMI2, FMA, and F16C)" - ${_AVX2_DEFAULT}) +option(MLX_ENABLE_X86_SIMD + "Enable runtime-dispatched x86 CPU SIMD kernels via Highway" + ${_X86_SIMD_DEFAULT}) set(MLX_HIGHWAY_SOURCE_DIR "" - CACHE PATH "Path to a local Highway source checkout for MLX_ENABLE_AVX2") + 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 MLX_ENABLE_AVX2 fetches Highway") + 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 0f4ac7b8d2..9ac50b3d17 100644 --- a/mlx.pc.in +++ b/mlx.pc.in @@ -11,7 +11,7 @@ @PACKAGE_INIT@ -if (@MLX_BUILD_CPU@ AND @MLX_ENABLE_AVX2@) +if (@MLX_BUILD_CPU@ AND @MLX_ENABLE_X86_SIMD@) include(CMakeFindDependencyMacro) find_dependency(hwy CONFIG PATHS "${PACKAGE_PREFIX_DIR}" NO_DEFAULT_PATH) endif() diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 1e372c9e31..8d0082cb4b 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -7,43 +7,15 @@ else() endif() set(MLX_HIGHWAY_INCLUDE_DIR "") +set(PREAMBLE_SIMD_FLAGS "") +set(PREAMBLE_HWY_AVX2_FLAGS "") +set(PREAMBLE_HWY_AVX3_FLAGS "") -if(MLX_ENABLE_AVX2) +if(MLX_ENABLE_X86_SIMD) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") - message(FATAL_ERROR "MLX_ENABLE_AVX2 requires an x86 target") + message(FATAL_ERROR "MLX_ENABLE_X86_SIMD requires an x86 target") endif() - include(CheckCXXCompilerFlag) - if(MSVC) - check_cxx_compiler_flag("/arch:AVX2" MLX_COMPILER_SUPPORTS_AVX2) - if(NOT MLX_COMPILER_SUPPORTS_AVX2) - message(FATAL_ERROR "MLX_ENABLE_AVX2 requires /arch:AVX2 support") - endif() - set(MLX_AVX2_COMPILE_OPTIONS /arch:AVX2) - set(PREAMBLE_SIMD_FLAGS "/arch:AVX2") - else() - # Highway's AVX2 target assumes the x86 feature set shipped with mainstream - # Intel/AMD AVX2 CPUs. VMs that mask BMI2/FMA/F16C need a separate, stricter - # baseline. - check_cxx_compiler_flag("-mavx2 -mbmi2 -mfma -mf16c" - MLX_COMPILER_SUPPORTS_AVX2) - if(NOT MLX_COMPILER_SUPPORTS_AVX2) - message( - FATAL_ERROR - "MLX_ENABLE_AVX2 requires -mavx2 -mbmi2 -mfma -mf16c support") - endif() - set(MLX_AVX2_COMPILE_OPTIONS -mavx2 -mbmi2 -mfma -mf16c) - set(PREAMBLE_SIMD_FLAGS "-mavx2 -mbmi2 -mfma -mf16c") - endif() - - # MLX_ENABLE_AVX2 deliberately builds one Highway x86 target: AVX2. - # HWY_DISABLED_TARGETS masks wider AVX-512-class targets, and - # HWY_COMPILE_ONLY_STATIC keeps lower fallback targets out of the MLX binary. - # Future AVX512 support could update this target set explicitly. - set(MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS - "HWY_DISABLED_TARGETS=(HWY_AVX2-1)" HWY_DISABLE_PCLMUL_AES - HWY_COMPILE_ONLY_STATIC) - set(HWY_ENABLE_CONTRIB OFF CACHE BOOL "" FORCE) @@ -73,19 +45,66 @@ if(MLX_ENABLE_AVX2) set(MLX_HIGHWAY_INCLUDE_DIR ${highway_SOURCE_DIR}) endif() if(NOT TARGET hwy) - message(FATAL_ERROR "MLX_ENABLE_AVX2 requires Highway target hwy") + message(FATAL_ERROR "MLX_ENABLE_X86_SIMD requires Highway target hwy") endif() if(NOT TARGET hwy::hwy) add_library(hwy::hwy ALIAS hwy) endif() - target_compile_definitions(hwy PRIVATE ${MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS}) - target_compile_options(hwy PRIVATE ${MLX_AVX2_COMPILE_OPTIONS}) - target_compile_definitions(mlx PRIVATE MLX_USE_HIGHWAY - ${MLX_HIGHWAY_AVX2_ONLY_DEFINITIONS}) - target_compile_options(mlx PRIVATE ${MLX_AVX2_COMPILE_OPTIONS}) + 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}) + target_compile_definitions(mlx PRIVATE MLX_USE_HIGHWAY_KERNELS + ${MLX_HIGHWAY_TARGET_DEFINITIONS}) + target_include_directories(mlx PRIVATE ${MLX_HIGHWAY_INCLUDE_DIR}) target_link_libraries(mlx PRIVATE hwy::hwy) - message(STATUS "x86 SIMD: AVX2 enabled (${PREAMBLE_SIMD_FLAGS})") + if(MSVC) + target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) + set(PREAMBLE_HWY_AVX2_FLAGS + "/DMLX_USE_HIGHWAY_JIT_SIMD /DHWY_COMPILE_ONLY_STATIC /DHWY_DISABLE_PCLMUL_AES /arch:AVX2" + ) + elseif(NOT WIN32) + target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) + # Highway's AVX2 target includes BMI2, FMA, and F16C in its feature group. + set(PREAMBLE_HWY_AVX2_FLAGS + "-DMLX_USE_HIGHWAY_JIT_SIMD -DHWY_COMPILE_ONLY_STATIC -DHWY_DISABLE_PCLMUL_AES -mavx2 -mbmi2 -mfma -mf16c" + ) + target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + # Highway's HWY_AVX3 target maps to AVX-512F/BW/CD/DQ/VL plus AVX2-family + # prerequisites; use explicit compiler ISA flags for the generated JIT + # preamble. + set(PREAMBLE_HWY_AVX3_FLAGS + "-DMLX_USE_HIGHWAY_JIT_SIMD -DHWY_COMPILE_ONLY_STATIC -DHWY_DISABLE_PCLMUL_AES -mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd -mbmi2 -mfma -mf16c" + ) + endif() + if(WIN32 AND NOT MSVC) + message( + STATUS + "x86 SIMD: Highway runtime dispatch enabled, Windows non-MSVC CPU JIT disabled" + ) + elseif(WIN32) + message( + STATUS + "x86 SIMD: Highway runtime dispatch enabled, Windows CPU JIT capped to HWY_AVX2" + ) + else() + message( + STATUS + "x86 SIMD: Highway runtime dispatch enabled, toolchain-selected targets" + ) + endif() endif() set(COMPILE_DEPS @@ -95,12 +114,15 @@ set(COMPILE_DEPS ${PROJECT_SOURCE_DIR}/mlx/types/complex.h simd/simd.h simd/base_simd.h - simd/highway_simd.h simd/math.h simd/type.h unary_ops.h binary_ops.h) +if(MLX_ENABLE_X86_SIMD) + list(APPEND COMPILE_DEPS highway_utils.h simd/highway_simd.h) +endif() + if(WIN32) set(SHELL_EXT ps1) set(SHELL_CMD powershell -ExecutionPolicy Bypass -File) @@ -109,17 +131,50 @@ else() set(SHELL_CMD bash) endif() +set(PREAMBLE_OUTPUTS ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) add_custom_command( - OUTPUT compiled_preamble.cpp + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp COMMAND ${SHELL_CMD} ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp ${COMPILER} ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} - "${PREAMBLE_SIMD_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" + "${PREAMBLE_SIMD_FLAGS}" "" get_prebuilt_preamble DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h ${COMPILE_DEPS}) -add_custom_target(cpu_compiled_preamble DEPENDS compiled_preamble.cpp) +if(PREAMBLE_HWY_AVX2_FLAGS) + list(APPEND PREAMBLE_OUTPUTS + ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp + COMMAND + ${SHELL_CMD} + ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} + ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp ${COMPILER} + ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} + "${PREAMBLE_HWY_AVX2_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" + get_prebuilt_preamble_avx2 + DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h + ${COMPILE_DEPS}) +endif() + +if(PREAMBLE_HWY_AVX3_FLAGS) + list(APPEND PREAMBLE_OUTPUTS + ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp + COMMAND + ${SHELL_CMD} + ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} + ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp ${COMPILER} + ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} + "${PREAMBLE_HWY_AVX3_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" + get_prebuilt_preamble_avx3 + DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h + ${COMPILE_DEPS}) +endif() + +add_custom_target(cpu_compiled_preamble DEPENDS ${PREAMBLE_OUTPUTS}) add_dependencies(mlx cpu_compiled_preamble) @@ -159,12 +214,71 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sdpa.cpp ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp - ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) + ${PREAMBLE_OUTPUTS}) -if(MLX_ENABLE_AVX2) - 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) +if(MLX_ENABLE_X86_SIMD) + 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) diff --git a/mlx/backend/cpu/compiled.cpp b/mlx/backend/cpu/compiled.cpp index b5607397e3..2f1b8f654e 100644 --- a/mlx/backend/cpu/compiled.cpp +++ b/mlx/backend/cpu/compiled.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include #include @@ -50,7 +50,7 @@ static CompilerCache& cache() { }; // GPU compile is available through the GPU backend. CPU compile requires a -// usable C++ compiler (MSVC or clang-cl on Windows). +// supported local C++ JIT compiler. namespace detail { bool compile_available_for_device(const Device& device) { return device == Device::gpu || JitCompiler::available(); @@ -76,27 +76,32 @@ void* compile( return it->second; } std::string source_code = source_builder(); + auto source_id = std::hash{}(source_code); + auto source_hash = fmt::format("_{:016x}", source_id); std::string kernel_file_name; // Deal with long kernel names. Maximum length for filename on macOS is 255 // characters, and on Windows the maximum length for whole path is 260. Clip - // file name with a little extra room and append a 16 character hash. + // file name with a little extra room and append hashes for the kernel name + // and generated source. The source hash keeps scalar and target-specific JIT + // preambles from reusing stale libraries with the same kernel symbol. #ifdef _WIN32 constexpr int max_file_name_length = 140; #else constexpr int max_file_name_length = 245; #endif - if (kernel_name.size() > max_file_name_length) { + auto max_base_length = max_file_name_length - source_hash.size(); + if (kernel_name.size() > max_base_length) { std::ostringstream file_name; - file_name - << std::string_view(kernel_name).substr(0, max_file_name_length - 16); + file_name << std::string_view(kernel_name).substr(0, max_base_length - 16); auto file_id = - std::hash{}(kernel_name.substr(max_file_name_length - 16)); + std::hash{}(kernel_name.substr(max_base_length - 16)); file_name << "_" << std::hex << std::setw(16) << file_id << std::dec; kernel_file_name = file_name.str(); } else { kernel_file_name = kernel_name; } + kernel_file_name += source_hash; auto output_dir = std::filesystem::temp_directory_path() / "mlx" / version() / "cpu"; diff --git a/mlx/backend/cpu/compiled_preamble.h b/mlx/backend/cpu/compiled_preamble.h index 02e3db8e78..b3b8465729 100644 --- a/mlx/backend/cpu/compiled_preamble.h +++ b/mlx/backend/cpu/compiled_preamble.h @@ -1,4 +1,4 @@ -// Copyright © 2023-24 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #pragma once @@ -10,3 +10,10 @@ // clang-format on const char* get_prebuilt_preamble(); + +#ifdef MLX_HAVE_JIT_PREAMBLE_HWY_AVX2 +const char* get_prebuilt_preamble_avx2(); +#endif +#ifdef MLX_HAVE_JIT_PREAMBLE_HWY_AVX3 +const char* get_prebuilt_preamble_avx3(); +#endif diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 5a9b8102b1..9cd9eb05eb 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -304,6 +304,7 @@ void matmul( 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, @@ -312,7 +313,7 @@ void matmul( N, K, &calpha, - a_ptr + m_start * lda, + a_ptr + a_offset, lda, b_ptr, ldb, diff --git a/mlx/backend/cpu/gemms/simd_bf16.cpp b/mlx/backend/cpu/gemms/simd_bf16.cpp index f400d40d85..e4c1d49f05 100644 --- a/mlx/backend/cpu/gemms/simd_bf16.cpp +++ b/mlx/backend/cpu/gemms/simd_bf16.cpp @@ -1,227 +1,10 @@ // Copyright © 2025-2026 Apple Inc. -#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/simd/simd.h" -#include "mlx/backend/cpu/threading/common.h" - -#include -#include +#include "mlx/backend/cpu/gemms/simd_low_precision_gemm.h" namespace mlx::core { -constexpr int BF16_MIN_BATCHES_PER_THREAD = 4; - -namespace { - -// Thread-local scratch buffer for bf16->f32 conversion. -// Avoids mmap/munmap cycles and page faults from repeated large allocations. -float* get_scratch(size_t n) { - thread_local std::vector buf; - if (buf.size() < n) { - buf.resize(n); - } - return buf.data(); -} - -void bf16_to_f32(const bfloat16_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]); - } -} - -void f32_to_bf16(const float* src, bfloat16_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 bf16 GEMV: reads bf16 weights directly, converts in-register, FMAs. -// Eliminates 3x memory traffic of separate bf16->f32 conversion + BLAS. -// b_transposed=true: B is [N][K] (row = output), most common for LLM linear -// layers. b_transposed=false: B is [K][N] (row = input). -void bf16_gemv( - const bfloat16_t* a, - const bfloat16_t* b, - bfloat16_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. - // Compute: out[n] = alpha * dot(A, B[n]) + beta * out[n] - // A stays in cache, stream B rows sequentially. - for (size_t n = 0; n < N; n++) { - const bfloat16_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][:] - // Allocate f32 accumulator for N outputs (fits in L1 for typical N) - float* accum = get_scratch(N); - 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 bfloat16_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]); - } - } -} - -// Multi-threaded wrapper for bf16_gemv: splits N across threads. -void bf16_gemv_threaded( - const bfloat16_t* a, - const bfloat16_t* b, - bfloat16_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) { - // For b_transposed, each output n is independent -- trivially parallel. - 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) { - bf16_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) { - // For not-transposed, split N into ranges. Each thread accumulates its own - // slice of accumulators, 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; - float* accum = get_scratch(n_len); - 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 bfloat16_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 { - bf16_gemv(a, b, out, b_transposed, N, K, ldb, alpha, beta); - } -} - -} // namespace - template <> void matmul( const bfloat16_t* a, @@ -239,180 +22,22 @@ void matmul( 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]; - - if (batch_size > 1) { - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; - - 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; - - bf16_to_f32(a_ptr, a_f32, a_elems); - bf16_to_f32(b_ptr, b_f32, b_elems); - if (beta != 0) { - bf16_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_bf16(out_f32, out_ptr, out_elems); - } - }; - - auto& pool = cpu::ThreadPool::instance(); - int n_threads = std::min( - pool.max_threads(), - static_cast(batch_size / BF16_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) { - float* base = get_scratch(buf_size); - 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 { - float* scratch = get_scratch(a_elems + b_elems + out_elems); - run_batches( - 0, - batch_size, - scratch, - scratch + a_elems, - scratch + a_elems + b_elems); - } - } else { - // Single batch - 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 && N * K >= 65536) { - // M=1 GEMV: fused bf16 read + convert + FMA in one pass. - // For a_transposed, M=1 means a is K elements either way. - const bfloat16_t* a_vec = - a_transposed ? a_ptr : a_ptr; // both sequential for M=1 - bf16_gemv_threaded( - a_vec, b_ptr, out_ptr, b_transposed, N, K, ldb, alpha, beta); - } else if (M * N * K >= 65536) { - // Larger GEMM: cast to f32 + use BLAS - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; - - float* a_f32 = get_scratch(a_elems + b_elems + out_elems); - float* b_f32 = a_f32 + a_elems; - float* out_f32 = b_f32 + b_elems; - - bf16_to_f32(a_ptr, a_f32, a_elems); - bf16_to_f32(b_ptr, b_f32, b_elems); - if (beta != 0) { - bf16_to_f32(out_ptr, out_f32, out_elems); - } - - // For large M, split rows across threads - 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) { - cblas_sgemm( - CblasRowMajor, - a_transposed ? CblasTrans : CblasNoTrans, - b_transposed ? CblasTrans : CblasNoTrans, - m_end - m_start, - N, - K, - alpha, - a_f32 + m_start * lda, - 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_bf16(out_f32, out_ptr, out_elems); - } else { - // Small GEMM: use simd_gemm directly (no cast overhead) - simd_gemm( - a_ptr, - b_ptr, - out_ptr, - a_transposed, - b_transposed, - M, - N, - K, - alpha, - beta); - } - } - } + 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); } } // namespace mlx::core diff --git a/mlx/backend/cpu/gemms/simd_fp16.cpp b/mlx/backend/cpu/gemms/simd_fp16.cpp index 312e75cee2..841db96790 100644 --- a/mlx/backend/cpu/gemms/simd_fp16.cpp +++ b/mlx/backend/cpu/gemms/simd_fp16.cpp @@ -1,224 +1,10 @@ // Copyright © 2025-2026 Apple Inc. -#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/simd/simd.h" -#include "mlx/backend/cpu/threading/common.h" - -#include -#include +#include "mlx/backend/cpu/gemms/simd_low_precision_gemm.h" namespace mlx::core { -// Minimum batches per thread before parallelizing the BLAS path. -constexpr int FP16_MIN_BATCHES_PER_THREAD = 4; - -namespace { - -// Thread-local scratch buffer for f16->f32 conversion. -// Avoids mmap/munmap cycles and page faults from repeated large allocations. -float* get_scratch(size_t n) { - thread_local std::vector buf; - if (buf.size() < n) { - buf.resize(n); - } - return buf.data(); -} - -void f16_to_f32(const float16_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]); - } -} - -void f32_to_f16(const float* src, float16_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 f16 GEMV: reads f16 weights directly, converts in-register via F16C, -// FMAs. Eliminates 3x memory traffic of separate f16->f32 conversion + BLAS. -// b_transposed=true: B is [N][K] (row = output), most common for LLM linear -// layers. b_transposed=false: B is [K][N] (row = input). -void f16_gemv( - const float16_t* a, - const float16_t* b, - float16_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. - // Compute: out[n] = alpha * dot(A, B[n]) + beta * out[n] - // A stays in cache, stream B rows sequentially. - for (size_t n = 0; n < N; n++) { - const float16_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][:] - float* accum = get_scratch(N); - 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 float16_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]); - } - } -} - -// Multi-threaded wrapper for f16_gemv: splits N across threads. -void f16_gemv_threaded( - const float16_t* a, - const float16_t* b, - float16_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) { - // For b_transposed, each output n is independent -- trivially parallel. - 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) { - f16_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) { - // For not-transposed, split N into ranges. Each thread accumulates its own - // slice of accumulators, 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; - float* accum = get_scratch(n_len); - 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 float16_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 { - f16_gemv(a, b, out, b_transposed, N, K, ldb, alpha, beta); - } -} - -} // namespace - template <> void matmul( const float16_t* a, @@ -236,180 +22,22 @@ void matmul( 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]; - - // For batched operations (e.g. multi-head attention with 32+ heads), - // cast to float32 and use threaded BLAS -- much faster than naive simd_gemm. - // For single-batch ops (e.g. linear projections with huge weight matrices), - // use simd_gemm to avoid copying the entire weight matrix to float32. - if (batch_size > 1) { - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; - - 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; - - f16_to_f32(a_ptr, a_f32, a_elems); - f16_to_f32(b_ptr, b_f32, b_elems); - if (beta != 0) { - f16_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_f16(out_f32, out_ptr, out_elems); - } - }; - - auto& pool = cpu::ThreadPool::instance(); - int n_threads = std::min( - pool.max_threads(), - static_cast(batch_size / FP16_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) { - float* base = get_scratch(buf_size); - 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 { - float* scratch = get_scratch(a_elems + b_elems + out_elems); - run_batches( - 0, - batch_size, - scratch, - scratch + a_elems, - scratch + a_elems + b_elems); - } - } else { - // Single batch - 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 && N * K >= 65536) { - // M=1 GEMV: fused f16 read + F16C convert + FMA in one pass. - f16_gemv_threaded( - a_ptr, b_ptr, out_ptr, b_transposed, N, K, ldb, alpha, beta); - } else if (M * N * K >= 65536) { - // Larger GEMM: cast to f32 + use BLAS - 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))); - } - - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; - - float* a_f32 = get_scratch(a_elems + b_elems + out_elems); - float* b_f32 = a_f32 + a_elems; - float* out_f32 = b_f32 + b_elems; - - f16_to_f32(a_ptr, a_f32, a_elems); - f16_to_f32(b_ptr, b_f32, b_elems); - if (beta != 0) { - f16_to_f32(out_ptr, out_f32, out_elems); - } - - 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) { - cblas_sgemm( - CblasRowMajor, - a_transposed ? CblasTrans : CblasNoTrans, - b_transposed ? CblasTrans : CblasNoTrans, - m_end - m_start, - N, - K, - alpha, - a_f32 + m_start * lda, - 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_f16(out_f32, out_ptr, out_elems); - } else { - // Small GEMM: use simd_gemm directly (no cast overhead) - simd_gemm( - a_ptr, - b_ptr, - out_ptr, - a_transposed, - b_transposed, - M, - N, - K, - alpha, - beta); - } - } - } + 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); } } // 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..d811a06a3f --- /dev/null +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -0,0 +1,402 @@ +// 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/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 buffer for low-precision <-> f32 conversion. +// Avoids mmap/munmap cycles and page faults from repeated large allocations. +inline float* lowp_gemm_scratch(size_t n) { + thread_local std::vector buf; + if (buf.size() < n) { + buf.resize(n); + } + return buf.data(); +} + +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][:]. + float* accum = lowp_gemm_scratch(N); + 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; + float* accum = lowp_gemm_scratch(n_len); + 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]; + + if (batch_size > 1) { + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + 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) { + float* base = lowp_gemm_scratch(buf_size); + 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 { + float* scratch = lowp_gemm_scratch(a_elems + b_elems + out_elems); + 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 && 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) { + size_t a_rows = a_transposed ? K : M; + size_t b_rows = b_transposed ? N : K; + size_t a_elems = a_rows * lda; + size_t b_elems = b_rows * ldb; + size_t out_elems = M * ldc; + + float* a_f32 = lowp_gemm_scratch(a_elems + b_elems + out_elems); + 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, + alpha, + beta); + } + } + } +} + +} // namespace mlx::core::detail diff --git a/mlx/backend/cpu/highway_utils.h b/mlx/backend/cpu/highway_utils.h new file mode 100644 index 0000000000..d096bc1772 --- /dev/null +++ b/mlx/backend/cpu/highway_utils.h @@ -0,0 +1,134 @@ +// 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; + +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 hn::PromoteTo( + 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 = hn::PromoteTo(df, x0h); + x1 = hn::PromoteTo(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/jit_compiler.cpp b/mlx/backend/cpu/jit_compiler.cpp index 8e61b78b54..0f093b9ea4 100644 --- a/mlx/backend/cpu/jit_compiler.cpp +++ b/mlx/backend/cpu/jit_compiler.cpp @@ -5,7 +5,10 @@ #include "mlx/backend/cpu/compiled_preamble.h" #include +#include +#include #include +#include #include #include @@ -20,6 +23,16 @@ namespace mlx::core { namespace { +enum class JitPreambleTier { + Scalar, + HwyAvx2, + HwyAvx3, +}; + +// Preamble tiers are independent of Highway's runtime-dispatched kernel +// targets. CMake only embeds the available preambles; the JIT chooses the best +// one for the local CPU and runtime compiler. + #if defined(_MSC_VER) // Split string into array. @@ -33,6 +46,17 @@ std::vector str_split(const std::string& str, char delimiter) { return tokens; } +std::string get_env_var(const char* name) { + char* value = nullptr; + size_t size = 0; + if (_dupenv_s(&value, &size, name) != 0 || value == nullptr) { + return {}; + } + std::string result(value); + std::free(value); + return result; +} + // Get path information about MSVC. struct VisualStudioInfo { VisualStudioInfo() { @@ -44,8 +68,8 @@ struct VisualStudioInfo { // Get path of Visual Studio. // Use -latest to get only the most recent installation when multiple // versions are installed, avoiding path concatenation issues. - auto pf86 = std::getenv("ProgramFiles(x86)"); - if (!pf86) { + std::string pf86 = get_env_var("ProgramFiles(x86)"); + if (pf86.empty()) { throw std::runtime_error( "ProgramFiles(x86) environment variable not set."); } @@ -95,7 +119,10 @@ struct VisualStudioInfo { } } - std::string compiler(bool use_include) const { + std::string compiler(bool use_include, JitPreambleTier tier) const { + if (tier == JitPreambleTier::HwyAvx3 && !clang_cl.empty()) { + return clang_cl; + } if (use_include) { // With installed headers, either cl.exe or clang-cl can parse the source. // Prefer cl.exe since it is part of the standard Visual Studio C++ @@ -127,7 +154,58 @@ const VisualStudioInfo& GetVisualStudioInfo() { #endif // defined(_MSC_VER) -bool supports_avx2_target() { +#if !defined(_MSC_VER) +std::string jit_cxx_compiler() { + if (const char* compiler = std::getenv("MLX_JIT_CXX"); + compiler && compiler[0] != '\0') { + return compiler; + } +#if defined(__clang__) + return "clang++"; +#else + return "g++"; +#endif +} + +std::string command_executable(const std::string& executable) { +#if defined(_WIN32) + if (executable.find_first_of(" \t\"") == std::string::npos) { + return executable; + } +#endif + return fmt::format("\"{}\"", executable); +} + +std::string command_path(const std::filesystem::path& path) { +#if defined(_WIN32) + return path.generic_string(); +#else + return path.string(); +#endif +} +#endif // !defined(_MSC_VER) + +std::filesystem::path find_jit_include_dir(bool require_highway) { + std::vector roots; + auto binary_dir = current_binary_dir(); + roots.push_back(binary_dir); +#if !defined(_WIN32) + roots.push_back(binary_dir.parent_path()); +#endif + + for (const auto& root : roots) { + auto include_dir = root / "include"; + auto preamble_header = include_dir / "mlx/backend/cpu/compiled_preamble.h"; + auto highway_header = include_dir / "hwy/highway.h"; + if (std::filesystem::exists(preamble_header) && + (!require_highway || std::filesystem::exists(highway_header))) { + return include_dir; + } + } + return {}; +} + +bool supports_hwy_avx2_preamble() { #if defined(_MSC_VER) #if defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) @@ -170,20 +248,109 @@ bool supports_avx2_target() { #endif // defined(_MSC_VER) } +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + +bool supports_hwy_avx3_preamble() { +#if defined(_MSC_VER) + +#if defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) + int info[4]; + __cpuid(info, 0); + if (info[0] < 7) { + return false; + } + __cpuid(info, 1); + const uint32_t ecx = static_cast(info[2]); + const bool os_avx = (ecx & (1u << 27)) && (ecx & (1u << 28)); + const bool fma = ecx & (1u << 12); + const bool f16c = ecx & (1u << 29); + if (!os_avx) { + return false; + } + const unsigned long long xcr0 = _xgetbv(0); + if ((xcr0 & 0xE6) != 0xE6) { + return false; + } + __cpuidex(info, 7, 0); + const uint32_t ebx = static_cast(info[1]); + const bool bmi2 = ebx & (1u << 8); + const bool avx512f = ebx & (1u << 16); + const bool avx512dq = ebx & (1u << 17); + const bool avx512cd = ebx & (1u << 28); + const bool avx512bw = ebx & (1u << 30); + const bool avx512vl = ebx & (1u << 31); + return avx512f && avx512dq && avx512cd && avx512bw && avx512vl && bmi2 && + fma && f16c; +#else + return false; +#endif // defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) + +#elif defined(__GNUC__) || defined(__clang__) + +#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__) + __builtin_cpu_init(); + return __builtin_cpu_supports("avx512f") && + __builtin_cpu_supports("avx512dq") && + __builtin_cpu_supports("avx512cd") && + __builtin_cpu_supports("avx512bw") && + __builtin_cpu_supports("avx512vl") && __builtin_cpu_supports("bmi2") && + __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c"); +#else + return false; +#endif + +#else + return false; +#endif +} + +bool can_compile_hwy_avx3_preamble() { +#if defined(_MSC_VER) + return !GetVisualStudioInfo().clang_cl.empty(); +#else + return true; +#endif +} + +#endif // defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + +JitPreambleTier select_jit_preamble_tier() { +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + if (supports_hwy_avx3_preamble() && can_compile_hwy_avx3_preamble()) { + return JitPreambleTier::HwyAvx3; + } +#endif +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) + if (supports_hwy_avx2_preamble()) { + return JitPreambleTier::HwyAvx2; + } +#endif + return JitPreambleTier::Scalar; +} + +JitPreambleTier jit_preamble_tier() { + static JitPreambleTier tier = select_jit_preamble_tier(); + return tier; +} + +bool use_hwy_avx2_preamble() { + return jit_preamble_tier() == JitPreambleTier::HwyAvx2; +} + +bool use_hwy_avx3_preamble() { + return jit_preamble_tier() == JitPreambleTier::HwyAvx3; +} + } // namespace const std::tuple& JitCompiler::get_preamble() { - static auto preamble = []() -> std::tuple { + static auto scalar_preamble = + []() -> std::tuple { // Check whether the headers are shipped with the binary, if so use the // preamble from the headers, otherwise use the prebuilt one embedded in // binary, which may not work with all compilers. - auto root_dir = current_binary_dir(); -#if !defined(_WIN32) - root_dir = root_dir.parent_path(); -#endif - auto include_dir = root_dir / "include"; - if (std::filesystem::exists( - include_dir / "mlx/backend/cpu/compiled_preamble.h")) { + auto include_dir = find_jit_include_dir(false); + if (!include_dir.empty()) { return std::make_tuple( true, include_dir.string(), @@ -192,7 +359,53 @@ const std::tuple& JitCompiler::get_preamble() { return std::make_tuple(false, "", get_prebuilt_preamble()); } }(); - return preamble; +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) + static auto avx2_preamble = + []() -> std::tuple { + // Check whether the headers are shipped with the binary, if so use the + // preamble from the headers, otherwise use the prebuilt one embedded in + // binary, which may not work with all compilers. + auto include_dir = find_jit_include_dir(true); + if (!include_dir.empty()) { + return std::make_tuple( + true, + include_dir.string(), + "#define MLX_USE_HIGHWAY_JIT_SIMD\n" + "#define HWY_COMPILE_ONLY_STATIC\n" + "#define HWY_DISABLE_PCLMUL_AES\n" + "#include \"mlx/backend/cpu/compiled_preamble.h\"\n"); + } else { + // Installed MLX headers alone are not enough for the Highway SIMD facade. + // Wheels can still use the embedded prebuilt AVX2 preamble without + // shipping Highway headers as a runtime payload. + return std::make_tuple(false, "", get_prebuilt_preamble_avx2()); + } + }(); +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + static auto avx3_preamble = + []() -> std::tuple { + auto include_dir = find_jit_include_dir(true); + if (!include_dir.empty()) { + return std::make_tuple( + true, + include_dir.string(), + "#define MLX_USE_HIGHWAY_JIT_SIMD\n" + "#define HWY_COMPILE_ONLY_STATIC\n" + "#define HWY_DISABLE_PCLMUL_AES\n" + "#include \"mlx/backend/cpu/compiled_preamble.h\"\n"); + } else { + return std::make_tuple(false, "", get_prebuilt_preamble_avx3()); + } + }(); + if (use_hwy_avx3_preamble()) { + return avx3_preamble; + } +#endif + if (use_hwy_avx2_preamble()) { + return avx2_preamble; + } +#endif + return scalar_preamble; } bool JitCompiler::available() { @@ -201,7 +414,7 @@ bool JitCompiler::available() { try { bool use_include = std::get<0>(get_preamble()); const auto& info = GetVisualStudioInfo(); - return !info.compiler(use_include).empty(); + return !info.compiler(use_include, jit_preamble_tier()).empty(); } catch (...) { return false; } @@ -209,12 +422,19 @@ bool JitCompiler::available() { return result; #else #ifdef _WIN32 - static int result = std::system("g++ --version > NUL 2>&1"); + // Windows CPU JIT is only enabled for the Visual Studio ABI path above. + // MinGW-style JIT code was slower than the runtime-dispatched kernels in + // testing and has a more fragile runtime DLL discovery story. + return false; #else - static int result = std::system("g++ --version > /dev/null 2>&1"); -#endif + static int result = std::system( + fmt::format( + "{} --version > /dev/null 2>&1", + command_executable(jit_cxx_compiler())) + .c_str()); return result == 0; #endif +#endif } std::string JitCompiler::build_command( @@ -227,13 +447,8 @@ std::string JitCompiler::build_command( if (use_include) { compiler_flags += fmt::format(" /I \"{}\"", include_dir); } -#ifdef MLX_USE_HIGHWAY - compiler_flags += - " /DMLX_USE_HIGHWAY /DHWY_DISABLED_TARGETS=HWY_AVX2-1 " - "/DHWY_DISABLE_PCLMUL_AES /DHWY_COMPILE_ONLY_STATIC"; -#endif const VisualStudioInfo& info = GetVisualStudioInfo(); - std::string compiler = info.compiler(use_include); + std::string compiler = info.compiler(use_include, jit_preamble_tier()); for (const std::string& inc : info.includepaths) { if (!inc.empty()) { compiler_flags += fmt::format(" /I \"{}\"", inc); @@ -249,8 +464,14 @@ std::string JitCompiler::build_command( if (!info.clang_cl.empty() && compiler == info.clang_cl) { compiler_flags += " -Wno-everything"; } -#ifdef __AVX2__ - if (supports_avx2_target()) { +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) || \ + defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + if (use_hwy_avx3_preamble()) { + compiler_flags += + " /clang:-mavx512f /clang:-mavx512vl /clang:-mavx512bw" + " /clang:-mavx512dq /clang:-mavx512cd /clang:-mbmi2" + " /clang:-mfma /clang:-mf16c"; + } else if (use_hwy_avx2_preamble()) { compiler_flags += " /arch:AVX2"; } #endif @@ -271,29 +492,30 @@ std::string JitCompiler::build_command( if (use_include) { extra_flags = fmt::format("-I \"{}\"", include_dir); } -#ifdef __AVX2__ - if (supports_avx2_target()) { +#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) || \ + defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) + if (use_hwy_avx3_preamble()) { + if (!extra_flags.empty()) { + extra_flags += " "; + } + extra_flags += + "-mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd " + "-mbmi2 -mfma -mf16c"; + } else if (use_hwy_avx2_preamble()) { if (!extra_flags.empty()) { extra_flags += " "; } - // Match the build-time Highway AVX2 target. This assumes the BMI2/FMA/F16C - // feature set present on mainstream Intel/AMD AVX2 CPUs. + // JIT code is compiled locally, so it can pin to the current CPU after the + // runtime feature check while the shipped MLX binary remains baseline-safe. extra_flags += "-mavx2 -mbmi2 -mfma -mf16c"; } -#endif -#ifdef MLX_USE_HIGHWAY - if (!extra_flags.empty()) { - extra_flags += " "; - } - extra_flags += - "-DMLX_USE_HIGHWAY -DHWY_DISABLED_TARGETS=HWY_AVX2-1 " - "-DHWY_DISABLE_PCLMUL_AES -DHWY_COMPILE_ONLY_STATIC"; #endif return fmt::format( - "g++ -std=c++17 -O3 -Wall -fPIC -shared {} \"{}\" -o \"{}\" 2>&1", + "{} -std=c++17 -O3 -Wall -fPIC -shared {} \"{}\" -o \"{}\" 2>&1", + command_executable(jit_cxx_compiler()), extra_flags, - (dir / source_file_name).string(), - (dir / shared_lib_name).string()); + command_path(dir / source_file_name), + command_path(dir / shared_lib_name)); #endif } diff --git a/mlx/backend/cpu/make_compiled_preamble.ps1 b/mlx/backend/cpu/make_compiled_preamble.ps1 index 5aa30fef61..f1516e8e02 100644 --- a/mlx/backend/cpu/make_compiled_preamble.ps1 +++ b/mlx/backend/cpu/make_compiled_preamble.ps1 @@ -10,8 +10,22 @@ $SRCDIR = $args[2] # on macOS it controls -nobuiltininc and -arch flags for the preprocessor. # MSVC and clang-cl both accept the same preprocessor flags so no distinction needed.) # args[4] = CMAKE_SYSTEM_PROCESSOR (unused on Windows) -$SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mbmi2 -mfma -mf16c" -$HIGHWAY_INCLUDE_DIR = $args[6] # Optional, used when MLX_ENABLE_AVX2 uses Highway +$FUNCTION_NAME = "get_prebuilt_preamble" +$SIMD_FLAGS = "" +$EXTRA_INCLUDE = "" +if ($args.Count -gt 5) { + if ($args.Count -eq 6 -and $args[5] -like "get_prebuilt_preamble*") { + $FUNCTION_NAME = $args[5] + } else { + $SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mbmi2 -mfma -mf16c" + if ($args.Count -gt 6) { + $EXTRA_INCLUDE = $args[6] # Optional, e.g. Highway headers for JIT SIMD preambles. + } + if ($args.Count -gt 7 -and $args[7]) { + $FUNCTION_NAME = $args[7] + } + } +} # Detect compiler type: MSVC/clang-cl use /EP, GCC/clang++ use -E -P $CL_NAME = [System.IO.Path]::GetFileNameWithoutExtension($CL) @@ -33,33 +47,31 @@ if ($SIMD_FLAGS) { } if ($IS_MSVC_LIKE) { [void]$CL_ARGS.Add("/I$SRCDIR") - if ($HIGHWAY_INCLUDE_DIR) { - [void]$CL_ARGS.Add("/I$HIGHWAY_INCLUDE_DIR") - [void]$CL_ARGS.Add('/DMLX_USE_HIGHWAY') - [void]$CL_ARGS.Add('/DHWY_DISABLED_TARGETS=HWY_AVX2-1') - [void]$CL_ARGS.Add('/DHWY_DISABLE_PCLMUL_AES') - [void]$CL_ARGS.Add('/DHWY_COMPILE_ONLY_STATIC') + if ($EXTRA_INCLUDE) { + [void]$CL_ARGS.Add("/I$EXTRA_INCLUDE") } [void]$CL_ARGS.Add('/Tp') } else { [void]$CL_ARGS.Add('-I') [void]$CL_ARGS.Add("$SRCDIR") - if ($HIGHWAY_INCLUDE_DIR) { + if ($EXTRA_INCLUDE) { [void]$CL_ARGS.Add('-I') - [void]$CL_ARGS.Add("$HIGHWAY_INCLUDE_DIR") - [void]$CL_ARGS.Add('-DMLX_USE_HIGHWAY') - [void]$CL_ARGS.Add('-DHWY_DISABLED_TARGETS=HWY_AVX2-1') - [void]$CL_ARGS.Add('-DHWY_DISABLE_PCLMUL_AES') - [void]$CL_ARGS.Add('-DHWY_COMPILE_ONLY_STATIC') + [void]$CL_ARGS.Add("$EXTRA_INCLUDE") } } [void]$CL_ARGS.Add("$SRCDIR/mlx/backend/cpu/compiled_preamble.h") # Get command result as array. Redirect stderr to null to suppress warnings. $CONTENT = & $CL @CL_ARGS 2>$null +if ($LASTEXITCODE -ne 0) { + throw "Failed to preprocess JIT preamble with $CL (exit code $LASTEXITCODE)" +} # Remove empty lines. # Otherwise there will be too much empty lines making the result unreadable. $CONTENT = $CONTENT | Where-Object { $_.Trim() -ne '' } +if (-not $CONTENT) { + throw "Failed to preprocess JIT preamble with ${CL}: no output" +} # Concatenate to string. $CONTENT = $CONTENT -join "`n" @@ -70,7 +82,7 @@ $CONTENT = $CONTENT -join "`n" $CHARCODES = ([System.Text.Encoding]::ASCII.GetBytes($CONTENT) -join ', ') + ', 0' $OUTPUT = @" -const char* get_prebuilt_preamble() { +const char* $FUNCTION_NAME() { static char preamble[] = { $CHARCODES }; return preamble; } diff --git a/mlx/backend/cpu/make_compiled_preamble.sh b/mlx/backend/cpu/make_compiled_preamble.sh index 156a307c8b..b0a79cec16 100644 --- a/mlx/backend/cpu/make_compiled_preamble.sh +++ b/mlx/backend/cpu/make_compiled_preamble.sh @@ -12,7 +12,8 @@ SRCDIR=$3 CLANG=$4 ARCH=$5 SIMD_FLAGS=$6 # Optional, e.g. "-mavx2 -mbmi2 -mfma -mf16c" -HIGHWAY_INCLUDE_DIR=$7 # Optional, used when MLX_ENABLE_AVX2 uses Highway +EXTRA_INCLUDE=$7 # Optional, e.g. Highway headers for JIT SIMD preambles. +FUNCTION_NAME=${8:-get_prebuilt_preamble} if [ "$CLANG" = "TRUE" ]; then read -r -d '' INCLUDES <<- EOM @@ -29,24 +30,18 @@ else CC_FLAGS="-std=c++17" fi -HIGHWAY_INCLUDE_FLAG=() -if [ -n "$HIGHWAY_INCLUDE_DIR" ]; then - HIGHWAY_INCLUDE_FLAG=( - -I "$HIGHWAY_INCLUDE_DIR" - -DMLX_USE_HIGHWAY - -DHWY_DISABLED_TARGETS=HWY_AVX2-1 - -DHWY_DISABLE_PCLMUL_AES - -DHWY_COMPILE_ONLY_STATIC - ) +EXTRA_INCLUDE_FLAGS=() +if [ -n "$EXTRA_INCLUDE" ]; then + EXTRA_INCLUDE_FLAGS=(-I "$EXTRA_INCLUDE") fi CONTENT=$( - "$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" "${HIGHWAY_INCLUDE_FLAG[@]}" \ + "$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" "${EXTRA_INCLUDE_FLAGS[@]}" \ -E -P "$SRCDIR/mlx/backend/cpu/compiled_preamble.h" 2>/dev/null ) cat << EOF > "$OUTPUT_FILE" -const char* get_prebuilt_preamble() { +const char* $FUNCTION_NAME() { return R"preamble( $INCLUDES $CONTENT diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp index 1bdcb30f38..74b12ac8d3 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "mlx/allocator.h" #include "mlx/backend/cpu/copy.h" @@ -12,7 +13,7 @@ #include "mlx/transforms.h" #include "mlx/utils.h" -#if defined(MLX_USE_HIGHWAY) +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/norms_highway.h" #endif @@ -364,7 +365,7 @@ void rms_norm_float( int rows, float eps, bool has_weight) { -#if defined(MLX_USE_HIGHWAY) +#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++) { @@ -384,7 +385,7 @@ void layer_norm_float( float eps, bool has_weight, bool has_bias) { -#if defined(MLX_USE_HIGHWAY) +#if defined(MLX_USE_HIGHWAY_KERNELS) layer_norm_highway_float( x, weight, bias, out, width, rows, eps, has_weight, has_bias); #else @@ -402,6 +403,63 @@ void layer_norm_float( #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( @@ -488,28 +546,20 @@ void RMSNorm::eval_cpu( int row_start = rows_per_thread * tid; int row_end = std::min(row_start + rows_per_thread, num_rows); - for (int row = row_start; row < row_end; row++) { - rms_norm_row_half( - x_ptr + row * width, - w_ptr, - out_ptr + row * width, - width, - eps, - has_weight); - } - }); - }); - } else { - encoder.dispatch([=]() { - for (int row = 0; row < num_rows; row++) { - rms_norm_row_half( - x_ptr + row * width, + rms_norm_half( + x_ptr + row_start * width, w_ptr, - out_ptr + row * width, + 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; @@ -527,28 +577,20 @@ void RMSNorm::eval_cpu( int row_start = rows_per_thread * tid; int row_end = std::min(row_start + rows_per_thread, num_rows); - for (int row = row_start; row < row_end; row++) { - rms_norm_row_half( - x_ptr + row * width, - w_ptr, - out_ptr + row * width, - width, - eps, - has_weight); - } - }); - }); - } else { - encoder.dispatch([=]() { - for (int row = 0; row < num_rows; row++) { - rms_norm_row_half( - x_ptr + row * width, + rms_norm_half( + x_ptr + row_start * width, w_ptr, - out_ptr + row * width, + 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; @@ -671,32 +713,30 @@ void LayerNorm::eval_cpu( int row_start = rows_per_thread * tid; int row_end = std::min(row_start + rows_per_thread, num_rows); - for (int row = row_start; row < row_end; row++) { - layer_norm_row_half( - x_ptr + row * width, - w_ptr, - b_ptr, - out_ptr + row * width, - width, - eps, - has_weight, - has_bias); - } - }); - }); - } else { - encoder.dispatch([=]() { - for (int row = 0; row < num_rows; row++) { - layer_norm_row_half( - x_ptr + row * width, + layer_norm_half( + x_ptr + row_start * width, w_ptr, b_ptr, - out_ptr + row * width, + 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; @@ -715,32 +755,30 @@ void LayerNorm::eval_cpu( int row_start = rows_per_thread * tid; int row_end = std::min(row_start + rows_per_thread, num_rows); - for (int row = row_start; row < row_end; row++) { - layer_norm_row_half( - x_ptr + row * width, - w_ptr, - b_ptr, - out_ptr + row * width, - width, - eps, - has_weight, - has_bias); - } - }); - }); - } else { - encoder.dispatch([=]() { - for (int row = 0; row < num_rows; row++) { - layer_norm_row_half( - x_ptr + row * width, + layer_norm_half( + x_ptr + row_start * width, w_ptr, b_ptr, - out_ptr + row * width, + 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; diff --git a/mlx/backend/cpu/norms_highway.cpp b/mlx/backend/cpu/norms_highway.cpp index a944359514..49b13332c9 100644 --- a/mlx/backend/cpu/norms_highway.cpp +++ b/mlx/backend/cpu/norms_highway.cpp @@ -1,12 +1,21 @@ // Copyright © 2026 Apple Inc. +// 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 +#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 { @@ -14,6 +23,9 @@ 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; void rms_norm_row_f32( const float* HWY_RESTRICT x, @@ -26,23 +38,30 @@ void rms_norm_row_f32( using V = hn::Vec; const int lanes = static_cast(hn::Lanes(d)); + float total = 0.0f; + int i = 0; V sum_sq0 = hn::Zero(d); V sum_sq1 = hn::Zero(d); + V sum_sq2 = hn::Zero(d); + V sum_sq3 = hn::Zero(d); - int i = 0; - for (; i + 2 * lanes <= width; i += 2 * lanes) { + for (; i + 4 * lanes <= width; 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(sum_sq0, sum_sq1); + V sum_sq = hn::Add(hn::Add(sum_sq0, sum_sq1), hn::Add(sum_sq2, sum_sq3)); for (; i + lanes <= width; i += lanes) { const V vals = hn::LoadU(d, x + i); sum_sq = hn::MulAdd(vals, vals, sum_sq); } - float total = hn::ReduceSum(d, sum_sq); + total = hn::ReduceSum(d, sum_sq); for (; i < width; ++i) { total += x[i] * x[i]; } @@ -71,6 +90,72 @@ void rms_norm_row_f32( } } +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; + 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 <= width; 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 <= width; i += lanes) { + const V vals = load_typed_as_f32(d, x, i); + sum_sq = hn::MulAdd(vals, vals, sum_sq); + } + + total = hn::ReduceSum(d, sum_sq); + for (; i < width; ++i) { + const float val = static_cast(x[i]); + total += val * val; + } + + 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, @@ -154,6 +239,90 @@ void layer_norm_row_f32( } } +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)); + V sum0 = hn::Zero(d); + V sum1 = hn::Zero(d); + + int i = 0; + for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { + sum = hn::Add(sum, load_typed_as_f32(d, x, i)); + } + + float total = hn::ReduceSum(d, sum); + for (; i < width; ++i) { + total += static_cast(x[i]); + } + const float mean = total / width; + + const V vmean = hn::Set(d, mean); + V variance_sum0 = hn::Zero(d); + V variance_sum1 = hn::Zero(d); + + i = 0; + for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { + const V diff = hn::Sub(load_typed_as_f32(d, x, i), vmean); + variance_sum = hn::MulAdd(diff, diff, variance_sum); + } + + float variance = hn::ReduceSum(d, variance_sum); + for (; i < width; ++i) { + const float diff = static_cast(x[i]) - mean; + variance += diff * diff; + } + 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, @@ -168,6 +337,43 @@ void RmsNormF32( } } +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) { + 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) { + RmsNormHalf(x, weight, out, width, rows, eps, has_weight); +} + void LayerNormF32( const float* HWY_RESTRICT x, const float* HWY_RESTRICT weight, @@ -191,6 +397,56 @@ void LayerNormF32( } } +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) { + 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) { + LayerNormHalf(x, weight, bias, out, width, rows, eps, has_weight, has_bias); +} + } // namespace } // namespace HWY_NAMESPACE } // namespace mlx::core::fast @@ -199,8 +455,131 @@ 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, @@ -210,8 +589,32 @@ void rms_norm_highway_float( int rows, float eps, bool has_weight) { - HWY_DYNAMIC_DISPATCH(RmsNormF32)( - x, weight, out, width, rows, eps, has_weight ? 1 : 0); + 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( @@ -224,17 +627,63 @@ void layer_norm_highway_float( 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); + 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 diff --git a/mlx/backend/cpu/norms_highway.h b/mlx/backend/cpu/norms_highway.h index 86c7ad582d..8e0cf4745b 100644 --- a/mlx/backend/cpu/norms_highway.h +++ b/mlx/backend/cpu/norms_highway.h @@ -2,6 +2,8 @@ #pragma once +#include "mlx/types/half_types.h" + namespace mlx::core::fast { void rms_norm_highway_float( @@ -13,6 +15,24 @@ void rms_norm_highway_float( 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, @@ -24,4 +44,26 @@ void layer_norm_highway_float( 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..3de7ba211d --- /dev/null +++ b/mlx/backend/cpu/norms_highway_dispatch.cpp @@ -0,0 +1,230 @@ +// Copyright © 2026 Apple Inc. + +#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 diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 9eb6b3924e..ffb91ee23c 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -17,8 +17,9 @@ #include "mlx/utils.h" // ISA-specific SIMD implementations (int8 kernels, dequant, LUT lookups). -// When AVX2 is enabled on this branch, Highway is the implementation substrate. -#if defined(MLX_USE_HIGHWAY) +// 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 @@ -27,8 +28,6 @@ #include "mlx/backend/cpu/quantized.h" namespace mlx::core { -constexpr bool has_simd_qmm = false; - template int try_batch_extract_multi_col( const T*& x_local, @@ -824,9 +823,24 @@ void _qmm_t_simd( 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; - +#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. @@ -995,7 +1009,7 @@ void _dequant_row_for_blas( const float* biases_row, float* out, int K) { -#if defined(MLX_USE_HIGHWAY) +#if defined(MLX_USE_HIGHWAY_KERNELS) if constexpr (bits == 4 || bits == 8) { _dequant_row_highway( w_row, scales_row, biases_row, out, K); @@ -1168,6 +1182,12 @@ void _qmm_dispatch_transpose( _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; @@ -1491,7 +1511,7 @@ void fp_qmm_t( } } -#if !defined(MLX_USE_HIGHWAY) +#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) { @@ -1626,7 +1646,7 @@ void fp_qmm_t_simd_row( int n_end, int K, float scale_factor) { -#if defined(MLX_USE_HIGHWAY) +#if defined(MLX_USE_HIGHWAY_KERNELS) fp_qmm_t_highway_row( result, x, @@ -1728,6 +1748,23 @@ void fp_qmm_t_simd( 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( @@ -1779,6 +1816,7 @@ void fp_qmm_t_simd( result + m * N, x + m * K, w, scales, 0, N, K, scale_factor); } } +#endif } template @@ -1793,6 +1831,13 @@ void fp_qmm_dispatch_transpose( 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; diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 05b59ef396..51b6543bb2 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -1,12 +1,22 @@ // Copyright © 2026 Apple Inc. +// 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 + +#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 - -#include "mlx/backend/cpu/quantized_highway.h" +#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 { @@ -14,51 +24,75 @@ namespace HWY_NAMESPACE { namespace { namespace hn = hwy::HWY_NAMESPACE; +namespace hu = mlx::core::highway::HWY_NAMESPACE; +using hu::load_typed_as_f32; -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 hn::PromoteTo( - df, - hn::LoadU(df16, reinterpret_cast(ptr) + idx)); - } else { -#if HWY_TARGET == HWY_SCALAR - const hn::Rebind dbf16; +// 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 - const hn::Repartition dbf16; +constexpr bool kHas512BitX86Vectors = false; #endif - const hn::Half dbf16_half; - return hn::PromoteTo( - df, - hn::LoadU( - dbf16_half, reinterpret_cast(ptr) + idx)); - } -} 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 +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( - float* HWY_RESTRICT result, + 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 group_size, int n, int K) { static_assert(bits == 4 || bits == 8); @@ -68,14 +102,22 @@ void qmm_t_int8_cols( const int packs_in_group = group_size / pack_factor; const int packs_per_col = groups_per_col * packs_in_group; - const hn::CappedTag di8; + 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}); - float accum[NC] = {}; + 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) { hn::Vec dot_acc[NC]; @@ -84,31 +126,28 @@ void qmm_t_int8_cols( } 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::LoadU(di8, x_group + elem); + const auto x_vec = hn::Load(di8, x_group + elem); + HWY_UNROLL(4) for (int c = 0; c < NC; ++c) { - const uint32_t* w_group = - w + (n + c) * packs_per_col + g * packs_in_group; hn::Vec w_vec; if constexpr (bits == 4) { - w_vec = unpack_4bit_lanes(du8, w_group + elem / pack_factor); + 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::Add( - dot_acc[c], hn::WidenMulPairwiseAdd(di32, prod16, ones16)); + auto unused = hn::Zero(di32); + dot_acc[c] = hn::ReorderWidenMulAccumulate( + di32, prod16, ones16, dot_acc[c], unused); } else { - const auto* w_bytes = - reinterpret_cast(w_group) + elem; + const auto* w_bytes = reinterpret_cast(w_group[c]); + w_group[c] += words_per_vec; w_vec = hn::LoadU(du8, w_bytes); - const auto low7 = hn::And(w_vec, hn::Set(du8, uint8_t{0x7F})); - const auto high_bit = hn::ShiftRight<7>(w_vec); - const auto low16 = hn::SatWidenMulPairwiseAdd(di16, low7, x_vec); - const auto high16 = hn::SatWidenMulPairwiseAdd(di16, high_bit, x_vec); - dot_acc[c] = hn::Add( - dot_acc[c], - hn::Add( - hn::WidenMulPairwiseAdd(di32, low16, ones16), - hn::ShiftLeft<7>( - hn::WidenMulPairwiseAdd(di32, high16, ones16)))); + dot_acc[c] = + hn::SumOfMulQuadAccumulate(di32, w_vec, x_vec, dot_acc[c]); } } } @@ -119,13 +158,17 @@ void qmm_t_int8_cols( 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 float dot = static_cast(hn::ReduceSum(di32, dot_acc[c])); - accum[c] += scale_f * xs * dot + bias_f * xgs; + accum_vec[c] = hn::MulAdd( + hn::Set(df, scale_f * xs), + hn::ConvertTo(df, dot_acc[c]), + accum_vec[c]); + bias_accum[c] += bias_f * xgs; } } for (int c = 0; c < NC; ++c) { - result[c] = accum[c]; + result[c] = + static_cast(hn::ReduceSum(df, accum_vec[c]) + bias_accum[c]); } } @@ -139,7 +182,7 @@ void dequant_row( int K) { static_assert(bits == 4 || bits == 8); constexpr int pack_factor = 32 / bits; - constexpr int lane_cap = bits == 4 ? 8 : 4; + constexpr int lane_cap = kHas512BitX86Vectors ? 16 : (bits == 4 ? 8 : 4); const hn::CappedTag du; const hn::Rebind df; @@ -156,17 +199,28 @@ void dequant_row( const VF scale = hn::Set(df, scales_row[g]); const VF bias = hn::Set(df, biases_row[g]); - 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); + 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 + elem); + 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; } - k += pack_factor; } } } @@ -205,7 +259,37 @@ void QuantizeActivationInt8Typed( x_scales[g] = max_value / 127.0f; const VF inv = hn::Set(df, inv_scale); - if (lanes == 8) { + 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)); @@ -215,7 +299,7 @@ void QuantizeActivationInt8Typed( 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::StoreU( + hn::Store( hn::OrderedDemote2To( di8, hn::OrderedDemote2To(di16, q0, q1), @@ -277,7 +361,7 @@ void QuantizeActivationInt8( } } -template +template void QmmTInt8RowTyped( float* HWY_RESTRICT result, const int8_t* HWY_RESTRICT x_q, @@ -286,71 +370,104 @@ void QmmTInt8RowTyped( 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) { int out = 0; int n = n_start; - for (; n + 8 <= n_end; n += 8, out += 8) { - if (bits == 4) { - qmm_t_int8_cols( - result + out, - x_q, - x_scales, - x_group_sums, - w, - scales, - biases, - group_size, - n, - K); - } else { - qmm_t_int8_cols( - result + out, + 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, - group_size, - n, + n_start, + n_end, K); - } - } - for (; n + 4 <= n_end; n += 4, out += 4) { - if (bits == 4) { - qmm_t_int8_cols( - result + out, + break; + case 64: + QmmTInt8RowTyped( + result, x_q, x_scales, x_group_sums, w, scales, biases, - group_size, - n, + n_start, + n_end, K); - } else { - qmm_t_int8_cols( - result + out, + break; + case 128: + QmmTInt8RowTyped( + result, x_q, x_scales, x_group_sums, w, scales, biases, - group_size, - n, + n_start, + n_end, K); - } + break; + default: + throw std::invalid_argument( + "Quantization group size must be 32, 64 or 128."); } - for (; n < n_end; ++n, ++out) { - if (bits == 4) { - qmm_t_int8_cols( - result + out, +} + +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, @@ -358,11 +475,13 @@ void QmmTInt8RowTyped( scales, biases, group_size, - n, + n_start, + n_end, K); - } else { - qmm_t_int8_cols( - result + out, + break; + case 8: + QmmTInt8RowForBits( + result, x_q, x_scales, x_group_sums, @@ -370,9 +489,12 @@ void QmmTInt8RowTyped( scales, biases, group_size, - n, + n_start, + n_end, K); - } + break; + default: + throw std::invalid_argument("Quantization bits must be 4 or 8."); } } @@ -392,7 +514,7 @@ void QmmTInt8Row( int K) { switch (dtype) { case QuantizedHighwayDType::Float32: - QmmTInt8RowTyped( + QmmTInt8RowForDType( result, x_q, x_scales, @@ -407,7 +529,7 @@ void QmmTInt8Row( K); break; case QuantizedHighwayDType::Float16: - QmmTInt8RowTyped( + QmmTInt8RowForDType( result, x_q, x_scales, @@ -422,7 +544,7 @@ void QmmTInt8Row( K); break; case QuantizedHighwayDType::BFloat16: - QmmTInt8RowTyped( + QmmTInt8RowForDType( result, x_q, x_scales, @@ -439,6 +561,264 @@ void QmmTInt8Row( } } +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 (!env::enable_tf32() || K > INT8_MAX_K) { + return false; + } + + 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, @@ -448,8 +828,14 @@ hn::Vec load_fp4_weight_values( constexpr int pack_factor = 8; const size_t lanes = hn::Lanes(df); - const hn::Rebind du32; - if (lanes == 8) { + 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)), @@ -481,13 +867,20 @@ hn::Vec load_fp8_weight_values( const uint32_t* w, int elem_off, const float* fp8_lut) { - const hn::Rebind di32; const hn::Rebind du8; + const hn::Rebind du16; + 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 indices = hn::PromoteTo(di32, hn::LoadU(du8, bytes + base)); - return hn::GatherIndex(df, fp8_lut, indices); + 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))); + return hn::Mul( + hn::PromoteTo(df, hn::BitCast(df16, hn::Or(payload, sign))), + hn::Set(df, 256.0f)); } template @@ -520,7 +913,8 @@ void fp_qmm_t_highway_cols( static_assert(bits == 4 || bits == 8); static_assert(group_size == 16 || group_size == 32); - const hn::CappedTag df; + 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; @@ -656,6 +1050,70 @@ void FpQmmTHighwayRowTyped( } } +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, @@ -711,6 +1169,34 @@ void FpQmmTHighwayRowForDType( } } +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, @@ -774,6 +1260,69 @@ void FpQmmTHighwayRow( } } +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) { + 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, @@ -802,11 +1351,170 @@ 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, @@ -815,8 +1523,8 @@ void dequant_row_highway_4bit( float* out, int group_size, int K) { - HWY_DYNAMIC_DISPATCH(DequantRow4Bit)( - w_row, scales_row, biases_row, out, group_size, K); + HWY_DYNAMIC_DISPATCH(DequantRow4Bit) + (w_row, scales_row, biases_row, out, group_size, K); } void dequant_row_highway_8bit( @@ -826,8 +1534,8 @@ void dequant_row_highway_8bit( float* out, int group_size, int K) { - HWY_DYNAMIC_DISPATCH(DequantRow8Bit)( - w_row, scales_row, biases_row, out, group_size, K); + HWY_DYNAMIC_DISPATCH(DequantRow8Bit) + (w_row, scales_row, biases_row, out, group_size, K); } void quantize_activation_int8_highway( @@ -838,8 +1546,8 @@ void quantize_activation_int8_highway( 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); + HWY_DYNAMIC_DISPATCH(QuantizeActivationInt8) + (x, dtype, K, group_size, x_q, x_scales, x_group_sums); } void qmm_t_int8_highway_row( @@ -856,20 +1564,36 @@ void qmm_t_int8_highway_row( 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); + 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( @@ -886,21 +1610,53 @@ void fp_qmm_t_highway_row( 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); + 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 diff --git a/mlx/backend/cpu/quantized_highway.h b/mlx/backend/cpu/quantized_highway.h index 596f47808e..0b4a4ffc8c 100644 --- a/mlx/backend/cpu/quantized_highway.h +++ b/mlx/backend/cpu/quantized_highway.h @@ -18,8 +18,6 @@ namespace mlx::core { -constexpr bool has_simd_qmm = true; - enum class QuantizedHighwayDType : uint8_t { Float32, Float16, @@ -42,20 +40,6 @@ constexpr QuantizedHighwayDType quantized_highway_dtype() { } } -template <> -struct LoadAsFloat { - static inline simd::Simd apply(const float16_t* ptr) { - return simd::Simd(simd::load(ptr)); - } -}; - -template <> -struct LoadAsFloat { - static inline simd::Simd apply(const bfloat16_t* ptr) { - return simd::Simd(simd::load(ptr)); - } -}; - void dequant_row_highway_4bit( const uint32_t* w_row, const float* scales_row, @@ -96,6 +80,19 @@ void qmm_t_int8_highway_row( 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, @@ -111,6 +108,21 @@ void fp_qmm_t_highway_row( 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, diff --git a/mlx/backend/cpu/quantized_highway_dispatch.cpp b/mlx/backend/cpu/quantized_highway_dispatch.cpp new file mode 100644 index 0000000000..2fd2685f5b --- /dev/null +++ b/mlx/backend/cpu/quantized_highway_dispatch.cpp @@ -0,0 +1,331 @@ +// Copyright © 2026 Apple Inc. + +#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 diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index 0e1083356e..d8c45de7c7 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -157,20 +157,19 @@ U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { return result; } - // Each thread computes a partial reduction - // Use cache-line aligned storage to avoid false sharing - constexpr size_t CACHE_LINE = 64; - constexpr size_t PADDED_SIZE = - (sizeof(U) + CACHE_LINE - 1) / CACHE_LINE * CACHE_LINE; - std::vector partial_storage(n_threads * PADDED_SIZE); + // Each thread computes a partial reduction. Keep each partial on its own + // cache line to avoid false sharing while preserving U's alignment/lifetime. + struct alignas(64) Partial { + U 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); - U* partial = - reinterpret_cast(partial_storage.data() + tid * PADDED_SIZE); + U* partial = &partials[tid].value; *partial = init; if (start < end) { @@ -182,8 +181,7 @@ U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { // Final reduction of partial results U result = init; for (int i = 0; i < n_threads; ++i) { - U* partial = reinterpret_cast(partial_storage.data() + i * PADDED_SIZE); - result = op(result, *partial); + result = op(result, partials[i].value); } return result; } diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp index 66977b0b40..76f95a459d 100644 --- a/mlx/backend/cpu/rope.cpp +++ b/mlx/backend/cpu/rope.cpp @@ -11,15 +11,15 @@ #include "mlx/backend/cpu/threading/common.h" #include "mlx/fast_primitives.h" -#if defined(MLX_USE_HIGHWAY) +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/rope_highway.h" #endif namespace mlx::core::fast { -// ISA-specific SIMD implementations for RoPE. When AVX2 is enabled on this -// branch, Highway is the implementation substrate. -#if !defined(MLX_USE_HIGHWAY) +// 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 @@ -32,7 +32,7 @@ inline int rope_non_traditional_simd(const T*, T*, const float*, const float*, int) { return 0; } -#endif // !MLX_USE_HIGHWAY +#endif // !MLX_USE_HIGHWAY_KERNELS namespace { @@ -89,11 +89,11 @@ inline void rope_apply_non_traditional( constexpr int N = max_size; int j = 0; -#if defined(MLX_USE_HIGHWAY) +#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) +#if !defined(MLX_USE_HIGHWAY_KERNELS) if constexpr (has_simd_rope && N >= simd_rope_min_size) { if (j == 0) { j = rope_non_traditional_simd( @@ -155,11 +155,11 @@ inline void rope_apply_traditional( int j = 0; -#if defined(MLX_USE_HIGHWAY) +#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) +#if !defined(MLX_USE_HIGHWAY_KERNELS) if constexpr (has_simd_rope && N >= simd_rope_min_size) { if (j == 0) { j = rope_traditional_simd( diff --git a/mlx/backend/cpu/rope_highway.cpp b/mlx/backend/cpu/rope_highway.cpp index b2d7c3ac21..195fd9bb34 100644 --- a/mlx/backend/cpu/rope_highway.cpp +++ b/mlx/backend/cpu/rope_highway.cpp @@ -1,12 +1,20 @@ // Copyright © 2026 Apple Inc. +// 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" +#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 { @@ -14,120 +22,11 @@ namespace HWY_NAMESPACE { namespace { namespace hn = hwy::HWY_NAMESPACE; - -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 hn::PromoteTo( - 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 = hn::PromoteTo(df, x0h); - x1 = hn::PromoteTo(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 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( @@ -326,6 +225,75 @@ 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); @@ -339,8 +307,8 @@ int rope_traditional_highway_forward( 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); + HWY_DYNAMIC_DISPATCH(RopeTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); return processed; } @@ -352,8 +320,8 @@ int rope_traditional_highway_reverse( 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); + HWY_DYNAMIC_DISPATCH(RopeTraditionalReverse) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); return processed; } @@ -365,8 +333,8 @@ int rope_non_traditional_highway_forward( 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); + HWY_DYNAMIC_DISPATCH(RopeNonTraditionalForward) + (x_in, x_out, dtype, cos_t, sin_t, half_dims, &processed); return processed; } @@ -378,10 +346,12 @@ int rope_non_traditional_highway_reverse( 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); + 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 diff --git a/mlx/backend/cpu/rope_highway_dispatch.cpp b/mlx/backend/cpu/rope_highway_dispatch.cpp new file mode 100644 index 0000000000..73656c24ee --- /dev/null +++ b/mlx/backend/cpu/rope_highway_dispatch.cpp @@ -0,0 +1,120 @@ +// Copyright © 2026 Apple Inc. + +#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 diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp index 28464fb9c0..abd124a6a0 100644 --- a/mlx/backend/cpu/sdpa.cpp +++ b/mlx/backend/cpu/sdpa.cpp @@ -11,6 +11,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/sdpa_highway.h" +#endif #include "mlx/backend/cpu/threading/common.h" #include "mlx/fast_primitives.h" @@ -852,6 +855,26 @@ void ScaledDotProductAttention::eval_cpu( 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, @@ -869,6 +892,7 @@ void ScaledDotProductAttention::eval_cpu( has_arr_mask, sinks_ptr, has_sinks); +#endif }); break; } @@ -883,6 +907,26 @@ void ScaledDotProductAttention::eval_cpu( 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, @@ -900,6 +944,7 @@ void ScaledDotProductAttention::eval_cpu( has_arr_mask, sinks_ptr, has_sinks); +#endif }); break; } @@ -914,6 +959,26 @@ void ScaledDotProductAttention::eval_cpu( 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, @@ -931,6 +996,7 @@ void ScaledDotProductAttention::eval_cpu( has_arr_mask, sinks_ptr, has_sinks); +#endif }); break; } diff --git a/mlx/backend/cpu/sdpa_highway.cpp b/mlx/backend/cpu/sdpa_highway.cpp new file mode 100644 index 0000000000..54beb19cc7 --- /dev/null +++ b/mlx/backend/cpu/sdpa_highway.cpp @@ -0,0 +1,579 @@ +// Copyright © 2026 Apple Inc. + +// 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/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; + +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[16] = {}; + 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[16]; + int b = 0; + for (; b + 4 <= lanes; b += 4) { + sdpa_dot_four(df, q_f, keys, head_dim, scale, mask, s + b, dots + b); + } + for (; 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[16]; + 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[16]; + 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) { + 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 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..e0c3a51ff8 --- /dev/null +++ b/mlx/backend/cpu/sdpa_highway_dispatch.cpp @@ -0,0 +1,130 @@ +// Copyright © 2026 Apple Inc. + +#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 diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index e9b1f1a3cc..1beac4cca1 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -13,20 +13,34 @@ 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 = 8; +inline constexpr int max_size = highway_max_f32_lanes; template <> -inline constexpr int max_size = 4; +inline constexpr int max_size = highway_max_f64_lanes; template <> -inline constexpr int max_size = 8; +inline constexpr int max_size = highway_max_f32_lanes; template <> -inline constexpr int max_size = 8; +inline constexpr int max_size = highway_max_f32_lanes; template <> inline constexpr int max_size = 8; template <> -inline constexpr int max_size = 8; +inline constexpr int max_size = highway_max_f32_lanes; template <> -inline constexpr int max_size = 8; +inline constexpr int max_size = highway_max_f32_lanes; namespace highway_detail { @@ -130,7 +144,11 @@ struct BoolSimdBase { BoolSimdBase(bool value) { if (value) { - bits[0] = static_cast((1u << N) - 1u); + 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); } } @@ -189,8 +207,10 @@ struct BoolSimdBase { } \ }; +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 @@ -264,6 +284,32 @@ struct Simd { } }; +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; @@ -290,6 +336,32 @@ struct Simd { } }; +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; diff --git a/mlx/backend/cpu/simd/type.h b/mlx/backend/cpu/simd/type.h index b0d6de91da..1e1463b1e1 100644 --- a/mlx/backend/cpu/simd/type.h +++ b/mlx/backend/cpu/simd/type.h @@ -2,6 +2,10 @@ #include "mlx/backend/cpu/simd/base_simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) || defined(MLX_USE_HIGHWAY_JIT_SIMD) +#include "mlx/backend/cpu/simd/highway_simd.h" +#endif + #ifdef MLX_USE_ACCELERATE #if defined(__x86_64__) // the accelerate_simd implementation require neon -- use base implementation @@ -9,10 +13,3 @@ #include "mlx/backend/cpu/simd/accelerate_simd.h" #endif #endif - -// x86 SIMD: MLX_ENABLE_AVX2 uses Highway as the implementation substrate. -#if !defined(MLX_USE_ACCELERATE) -#if defined(MLX_USE_HIGHWAY) -#include "mlx/backend/cpu/simd/highway_simd.h" -#endif -#endif diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp index fced82e4df..a3804a5938 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -7,10 +7,7 @@ // Spin-wait hint: reduces power consumption and avoids starving sibling // hyperthreads during busy-wait loops. -#if defined(MLX_USE_HIGHWAY) -#include "hwy/cache_control.h" -#define MLX_SPIN_PAUSE() hwy::Pause() -#elif defined(_MSC_VER) +#if defined(_MSC_VER) #include #if defined(_M_ARM64) || defined(_M_ARM) #define MLX_SPIN_PAUSE() __yield() @@ -31,7 +28,6 @@ #ifdef _WIN32 #include static void (*blas_set_threads)(int) = nullptr; -static int (*blas_get_threads)() = nullptr; static void init_blas_funcs() { static bool done = false; if (done) @@ -43,7 +39,6 @@ static void init_blas_funcs() { if (h) { blas_set_threads = (void (*)(int))GetProcAddress(h, "openblas_set_num_threads"); - blas_get_threads = (int (*)())GetProcAddress(h, "openblas_get_num_threads"); } } static void set_blas_threads(int n) { @@ -51,14 +46,9 @@ static void set_blas_threads(int n) { if (blas_set_threads) blas_set_threads(n); } -static int get_blas_threads() { - init_blas_funcs(); - return blas_get_threads ? blas_get_threads() : 1; -} #elif defined(__unix__) || defined(__linux__) #include static void (*blas_set_threads)(int) = nullptr; -static int (*blas_get_threads)() = nullptr; static void init_blas_funcs() { static bool done = false; if (done) @@ -66,24 +56,16 @@ static void init_blas_funcs() { done = true; blas_set_threads = (void (*)(int))dlsym(RTLD_DEFAULT, "openblas_set_num_threads"); - blas_get_threads = (int (*)())dlsym(RTLD_DEFAULT, "openblas_get_num_threads"); } static void set_blas_threads(int n) { init_blas_funcs(); if (blas_set_threads) blas_set_threads(n); } -static int get_blas_threads() { - init_blas_funcs(); - return blas_get_threads ? blas_get_threads() : 1; -} #else static void set_blas_threads(int n) { (void)n; } -static int get_blas_threads() { - return 1; -} #endif // Physical core detection -- AVX2/FMA workloads get no benefit from SMT diff --git a/mlx/io/load.h b/mlx/io/load.h index 6b9c9f477b..683abd95aa 100644 --- a/mlx/io/load.h +++ b/mlx/io/load.h @@ -1,4 +1,4 @@ -// Copyright © 2023 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #pragma once diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 35e811bc8f..13c1f6ac03 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -53,5 +53,14 @@ 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 37653ba040..61cdcedca4 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 @@ -108,3 +108,22 @@ TEST_CASE("test matmul") { out = matmul(transpose(a, {0, 2, 1}), transpose(b, {0, 2, 1})); 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); +} diff --git a/tests/thread_pool_tests.cpp b/tests/thread_pool_tests.cpp index dc904ddecd..8ccdb2b82c 100644 --- a/tests/thread_pool_tests.cpp +++ b/tests/thread_pool_tests.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -251,16 +253,17 @@ TEST_CASE("thread_pool parallel_for with exceptions does not deadlock") { auto& pool = ThreadPool::instance(); int nth = std::min(pool.max_threads(), 4); - std::atomic finished{false}; + std::mutex watchdog_mtx; + std::condition_variable watchdog_cv; + bool finished = false; std::thread watchdog([&] { - std::this_thread::sleep_for(std::chrono::seconds(5)); - if (!finished.load()) { - // Deadlock detected - force fail + std::unique_lock lock(watchdog_mtx); + if (!watchdog_cv.wait_for( + lock, std::chrono::seconds(5), [&] { return finished; })) { FAIL("parallel_for deadlocked after exception"); } }); - watchdog.detach(); // Only throw from slot 0 (main thread) so it propagates directly try { @@ -273,7 +276,12 @@ TEST_CASE("thread_pool parallel_for with exceptions does not deadlock") { // Expected } - finished.store(true); + { + std::lock_guard lock(watchdog_mtx); + finished = true; + } + watchdog_cv.notify_one(); + watchdog.join(); // Verify pool still works after exception std::atomic count{0}; From f694e0b4d25ac0e64d9a1ae7353ecd345f4eb691 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:57:09 +0200 Subject: [PATCH 03/65] Restore Simd::operator[] for upstream's sincos #3019 removes the scalar Simd's subscript operator. Upstream #4157 added a simd::sincos that indexes Simd for every N, including 1, so with both the CPU backend does not compile (unary.cpp: "type 'Simd' does not provide a subscript operator"). --- mlx/backend/cpu/simd/base_simd.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index 61b9cc383e..2be9a15e92 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -39,6 +39,14 @@ struct Simd { Simd(Simd v) : value(v.value) {} template Simd(U v) : value(v) {} + + T operator[](int) const { + return value; + } + + T& operator[](int) { + return value; + } }; namespace detail { From d01923dd0a4002b4fa4ef51d9d2af870ba5b703b Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:08:31 +0200 Subject: [PATCH 04/65] Fix the Highway build on MLX 0.32.2: writable Simd lanes Upstream #4157's simd::sincos_checked writes single lanes of a Simd when an argument is past 2^23. The Highway Simd has only a const operator[] that returns a copy, so unary.cpp does not compile on x86: mlx/backend/cpu/simd/math.h:131:14: error: expression is not assignable 131 | out[i] = static_cast(Sine ? std::sin(v) : std::cos(v)); | ~~~~~~ ^ Clang reports it for sincos_checked and . For bfloat16 the code compiled, but each write went to a temporary, so sin and cos returned zero in every lane of a vector holding such an argument. Add the writable operator[] that the Accelerate and NEON fp16 Simd types have. --- mlx/backend/cpu/simd/highway_simd.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 1beac4cca1..e13bcc09dc 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -282,6 +282,10 @@ struct Simd { store(tmp); return tmp[idx]; } + + T& operator[](int idx) { + return reinterpret_cast(&value)[idx]; + } }; template <> From ac7be6533450e346e44506a1fcebccbb385c8b0e Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:42:16 +0200 Subject: [PATCH 05/65] Fix the Highway build on MLX 0.32.3: a vector divide MLX 0.32.3 (#4442) routes the CPU Divide op through simd::divide, which defines an integer quotient by zero as 0, and makes an integer remainder by zero return the dividend. The Highway facade had no divide for vectors, so binary.cpp did not compile with MLX_USE_HIGHWAY_KERNELS, and its integer remainder divided by zero, which traps on x86-64. Add divide, and give remainder upstream's rule. A test runs floor_divide and remainder on int32, uint32 and uint8, the integer types the facade has vectors for, with zero divisors in vector lanes and in the scalar tail, and compares each element with the one-element path. --- mlx/backend/cpu/simd/highway_simd.h | 16 ++++++++++ tests/ops_tests.cpp | 47 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index e13bcc09dc..b8063bd97b 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -519,6 +519,18 @@ inline Simd operator/(Simd a, Simd b) { } } +// As base_simd.h's divide: an integer quotient by zero is 0. Each lane divides +// as a scalar: 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 y == 0 ? T(0) : static_cast(x / y); }); + } else { + return a / b; + } +} + template = 0> inline Simd operator/(Simd a, U b) { return a / Simd(b); @@ -805,6 +817,10 @@ 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) { + // As base_simd.h: a remainder by zero is the dividend. + if (y == 0) { + return x; + } T r = static_cast(x % y); if constexpr (std::is_signed_v) { if (r != 0 && ((r < 0) != (y < 0))) { diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 9c95e9b5e9..0d2ada0bb0 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4705,3 +4705,50 @@ TEST_CASE("roll and tile shape overflow") { auto rolled = roll(x, -2147483647 - 1); 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()); + } + } + } +} From a17e5de495263d4c34a0e314af39f5122e7bcde5 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:40:36 +0200 Subject: [PATCH 06/65] Keep the fork's CPU JIT #3019's JIT preprocesses Highway into per-tier preambles at build time and compiles them at run time with clang++ in Clang builds and g++ in GCC builds, which ties a host's compiler to the build's. Its CMake rule for the scalar preamble also passes an empty argument that CMake drops. In a Linux Clang build the embedded preamble came out empty, and every CPU compile that used it failed ("use of undeclared identifier 'mlx'"). A GCC 12 build was not affected: g++ reports the misplaced argument but still preprocesses the header. Keep the fork's jit_compiler.cpp, compiled.cpp, compiled_preamble.h, preamble scripts and CMake rule. A Highway JIT that the host's own compiler builds is separate work. --- mlx/backend/cpu/CMakeLists.txt | 84 +--- mlx/backend/cpu/compiled.cpp | 439 ++++----------------- mlx/backend/cpu/compiled_preamble.h | 9 +- mlx/backend/cpu/jit_compiler.cpp | 303 ++------------ mlx/backend/cpu/make_compiled_preamble.ps1 | 32 +- mlx/backend/cpu/make_compiled_preamble.sh | 16 +- 6 files changed, 109 insertions(+), 774 deletions(-) diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 8d0082cb4b..4c35040637 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -7,9 +7,6 @@ else() endif() set(MLX_HIGHWAY_INCLUDE_DIR "") -set(PREAMBLE_SIMD_FLAGS "") -set(PREAMBLE_HWY_AVX2_FLAGS "") -set(PREAMBLE_HWY_AVX3_FLAGS "") if(MLX_ENABLE_X86_SIMD) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") @@ -70,41 +67,7 @@ if(MLX_ENABLE_X86_SIMD) ${MLX_HIGHWAY_TARGET_DEFINITIONS}) target_include_directories(mlx PRIVATE ${MLX_HIGHWAY_INCLUDE_DIR}) target_link_libraries(mlx PRIVATE hwy::hwy) - if(MSVC) - target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) - set(PREAMBLE_HWY_AVX2_FLAGS - "/DMLX_USE_HIGHWAY_JIT_SIMD /DHWY_COMPILE_ONLY_STATIC /DHWY_DISABLE_PCLMUL_AES /arch:AVX2" - ) - elseif(NOT WIN32) - target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) - # Highway's AVX2 target includes BMI2, FMA, and F16C in its feature group. - set(PREAMBLE_HWY_AVX2_FLAGS - "-DMLX_USE_HIGHWAY_JIT_SIMD -DHWY_COMPILE_ONLY_STATIC -DHWY_DISABLE_PCLMUL_AES -mavx2 -mbmi2 -mfma -mf16c" - ) - target_compile_definitions(mlx PRIVATE MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - # Highway's HWY_AVX3 target maps to AVX-512F/BW/CD/DQ/VL plus AVX2-family - # prerequisites; use explicit compiler ISA flags for the generated JIT - # preamble. - set(PREAMBLE_HWY_AVX3_FLAGS - "-DMLX_USE_HIGHWAY_JIT_SIMD -DHWY_COMPILE_ONLY_STATIC -DHWY_DISABLE_PCLMUL_AES -mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd -mbmi2 -mfma -mf16c" - ) - endif() - if(WIN32 AND NOT MSVC) - message( - STATUS - "x86 SIMD: Highway runtime dispatch enabled, Windows non-MSVC CPU JIT disabled" - ) - elseif(WIN32) - message( - STATUS - "x86 SIMD: Highway runtime dispatch enabled, Windows CPU JIT capped to HWY_AVX2" - ) - else() - message( - STATUS - "x86 SIMD: Highway runtime dispatch enabled, toolchain-selected targets" - ) - endif() + message(STATUS "Highway: runtime-dispatched CPU kernels enabled") endif() set(COMPILE_DEPS @@ -119,10 +82,6 @@ set(COMPILE_DEPS unary_ops.h binary_ops.h) -if(MLX_ENABLE_X86_SIMD) - list(APPEND COMPILE_DEPS highway_utils.h simd/highway_simd.h) -endif() - if(WIN32) set(SHELL_EXT ps1) set(SHELL_CMD powershell -ExecutionPolicy Bypass -File) @@ -131,50 +90,17 @@ else() set(SHELL_CMD bash) endif() -set(PREAMBLE_OUTPUTS ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp + OUTPUT compiled_preamble.cpp COMMAND ${SHELL_CMD} ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp ${COMPILER} ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} - "${PREAMBLE_SIMD_FLAGS}" "" get_prebuilt_preamble + "${PREAMBLE_SIMD_FLAGS}" DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h ${COMPILE_DEPS}) -if(PREAMBLE_HWY_AVX2_FLAGS) - list(APPEND PREAMBLE_OUTPUTS - ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp) - add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp - COMMAND - ${SHELL_CMD} - ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} - ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx2.cpp ${COMPILER} - ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} - "${PREAMBLE_HWY_AVX2_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" - get_prebuilt_preamble_avx2 - DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h - ${COMPILE_DEPS}) -endif() - -if(PREAMBLE_HWY_AVX3_FLAGS) - list(APPEND PREAMBLE_OUTPUTS - ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp) - add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp - COMMAND - ${SHELL_CMD} - ${CMAKE_CURRENT_SOURCE_DIR}/make_compiled_preamble.${SHELL_EXT} - ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble_avx3.cpp ${COMPILER} - ${PROJECT_SOURCE_DIR} ${CLANG} ${CMAKE_SYSTEM_PROCESSOR} - "${PREAMBLE_HWY_AVX3_FLAGS}" "${MLX_HIGHWAY_INCLUDE_DIR}" - get_prebuilt_preamble_avx3 - DEPENDS make_compiled_preamble.${SHELL_EXT} compiled_preamble.h - ${COMPILE_DEPS}) -endif() - -add_custom_target(cpu_compiled_preamble DEPENDS ${PREAMBLE_OUTPUTS}) +add_custom_target(cpu_compiled_preamble DEPENDS compiled_preamble.cpp) add_dependencies(mlx cpu_compiled_preamble) @@ -214,7 +140,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sdpa.cpp ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp - ${PREAMBLE_OUTPUTS}) + ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) if(MLX_ENABLE_X86_SIMD) if(MSVC AND NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") diff --git a/mlx/backend/cpu/compiled.cpp b/mlx/backend/cpu/compiled.cpp index 2f1b8f654e..f5b516e44b 100644 --- a/mlx/backend/cpu/compiled.cpp +++ b/mlx/backend/cpu/compiled.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023-2024 Apple Inc. #include #include @@ -12,7 +12,6 @@ #include "mlx/backend/common/compiled.h" #include "mlx/backend/cpu/encoder.h" #include "mlx/backend/cpu/jit_compiler.h" -#include "mlx/backend/cpu/threading/common.h" #include "mlx/device.h" #include "mlx/graph_utils.h" #include "mlx/version.h" @@ -50,7 +49,7 @@ static CompilerCache& cache() { }; // GPU compile is available through the GPU backend. CPU compile requires a -// supported local C++ JIT compiler. +// usable C++ compiler (MSVC or clang-cl on Windows). namespace detail { bool compile_available_for_device(const Device& device) { return device == Device::gpu || JitCompiler::available(); @@ -76,32 +75,27 @@ void* compile( return it->second; } std::string source_code = source_builder(); - auto source_id = std::hash{}(source_code); - auto source_hash = fmt::format("_{:016x}", source_id); std::string kernel_file_name; // Deal with long kernel names. Maximum length for filename on macOS is 255 // characters, and on Windows the maximum length for whole path is 260. Clip - // file name with a little extra room and append hashes for the kernel name - // and generated source. The source hash keeps scalar and target-specific JIT - // preambles from reusing stale libraries with the same kernel symbol. + // file name with a little extra room and append a 16 character hash. #ifdef _WIN32 constexpr int max_file_name_length = 140; #else constexpr int max_file_name_length = 245; #endif - auto max_base_length = max_file_name_length - source_hash.size(); - if (kernel_name.size() > max_base_length) { + if (kernel_name.size() > max_file_name_length) { std::ostringstream file_name; - file_name << std::string_view(kernel_name).substr(0, max_base_length - 16); + file_name + << std::string_view(kernel_name).substr(0, max_file_name_length - 16); auto file_id = - std::hash{}(kernel_name.substr(max_base_length - 16)); + std::hash{}(kernel_name.substr(max_file_name_length - 16)); file_name << "_" << std::hex << std::setw(16) << file_id << std::dec; kernel_file_name = file_name.str(); } else { kernel_file_name = kernel_name; } - kernel_file_name += source_hash; auto output_dir = std::filesystem::temp_directory_path() / "mlx" / version() / "cpu"; @@ -213,236 +207,69 @@ inline void build_kernel( } if (contiguous) { - auto out_tstr = get_type_string(outputs[0].dtype()); - - // SIMD main loop (processes max_size elements per iteration) - os << " constexpr int _S = simd::max_size<" << out_tstr << ">;" - << std::endl; - os << " size_t _vi = 0;" << std::endl; - os << " if constexpr (_S > 1) {" << std::endl; - os << " for (; _vi + _S <= size; _vi += _S) {" << std::endl; - - // SIMD loads - for (size_t i = 0; i < inputs.size(); ++i) { - const auto& x = inputs[i]; - auto& xname = namer.get_name(x); - auto tstr = get_type_string(x.dtype()); - - if (is_constant(i)) { - os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>((" << tstr - << ")"; - print_constant(os, x); - os << ");" << std::endl; - } else if (is_scalar(x)) { - os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>(" << xname - << "[0]);" << std::endl; - } else { - os << " auto tmp_" << xname << " = simd::load<" << tstr << ", _S>(" - << xname << " + _vi);" << std::endl; - } - } - - // SIMD computation - for (auto& x : tape) { - os << " auto tmp_" << namer.get_name(x) << " = "; - if (is_static_cast(x.primitive())) { - auto tstr = get_type_string(x.dtype()); - os << "Simd<" << tstr << ", _S>(tmp_" << namer.get_name(x.inputs()[0]) - << ");" << std::endl; - } else { - os << x.primitive().name(); - os << "()("; - for (int i = 0; i < x.inputs().size() - 1; i++) { - os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; - } - os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; - } - } - - // SIMD stores - for (auto& x : outputs) { - os << " simd::store(" << namer.get_name(x) << " + _vi, tmp_" - << namer.get_name(x) << ");" << std::endl; - } - - os << " }" << std::endl; // close SIMD for - os << " }" << std::endl; // close if constexpr - - // Scalar tail loop - os << " for (size_t i = _vi; i < size; ++i) {" << std::endl; - - // Scalar reads (contiguous) - for (size_t i = 0; i < inputs.size(); ++i) { - const auto& x = inputs[i]; - auto& xname = namer.get_name(x); - if (is_constant(i)) { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = "; - print_constant(os, x); - os << ";" << std::endl; - } else if (is_scalar(x)) { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " - << xname << "[0];" << std::endl; - } else { - os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " - << xname << "[i];" << std::endl; - } - } - - // Scalar computation (contiguous tail) - for (auto& x : tape) { - os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) - << " = "; - if (is_static_cast(x.primitive())) { - os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" - << namer.get_name(x.inputs()[0]) << ");" << std::endl; - } else { - os << x.primitive().name() << "()("; - for (int i = 0; i < x.inputs().size() - 1; i++) { - os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; - } - os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; - } - } - - // Scalar writes (contiguous tail) - for (auto& x : outputs) { - os << " " << namer.get_name(x) << "[i] = tmp_" << namer.get_name(x) - << ";" << std::endl; - } - - os << " }" << std::endl; // close scalar tail - + os << " for (size_t i = 0; i < size; ++i) {" << std::endl; } else { - // ===== STRIDED PATH WITH SIMD ===== - auto out_tstr = get_type_string(outputs[0].dtype()); - int inner_d = ndim - 1; - - os << " constexpr int _S = simd::max_size<" << out_tstr << ">;" - << std::endl; - - // Open outer loops (d=0 to d=ndim-2) - for (int d = 0; d < ndim - 1; ++d) { + for (int d = 0; d < ndim; ++d) { os << " for (int i" << d << " = 0; i" << d << " < shape[" << d << "]; ++i" << d << ") {" << std::endl; } + } - // ---- SIMD inner loop ---- - os << " int i" << inner_d << " = 0;" << std::endl; - os << " if constexpr (_S > 1) {" << std::endl; - os << " for (; i" << inner_d << " + _S <= shape[" << inner_d << "]; i" - << inner_d << " += _S) {" << std::endl; - - // SIMD loads (with stride check for gather) - for (size_t i = 0; i < inputs.size(); ++i) { - const auto& x = inputs[i]; - auto& xname = namer.get_name(x); - auto tstr = get_type_string(x.dtype()); - - if (is_constant(i)) { - os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>((" << tstr - << ")"; - print_constant(os, x); - os << ");" << std::endl; - } else if (is_scalar(x)) { - os << " auto tmp_" << xname << " = Simd<" << tstr << ", _S>(" << xname - << "[0]);" << std::endl; - } else { - // Runtime stride check: contiguous inner dim -> simd::load, else gather - os << " Simd<" << tstr << ", _S> tmp_" << xname << ";" << std::endl; - os << " if (" << xname << "_strides[" << inner_d << "] == 1) {" - << std::endl; - os << " tmp_" << xname << " = simd::load<" << tstr << ", _S>(" - << xname << " + i" << inner_d << ");" << std::endl; - os << " } else {" << std::endl; - os << " " << tstr << " _gather_" << xname << "[_S];" << std::endl; - os << " for (int _k = 0; _k < _S; _k++)" << std::endl; - os << " _gather_" << xname << "[_k] = " << xname << "[(i" - << inner_d << " + _k) * " << xname << "_strides[" << inner_d << "]];" - << std::endl; - os << " tmp_" << xname << " = simd::load<" << tstr - << ", _S>(_gather_" << xname << ");" << std::endl; - os << " }" << std::endl; - } - } - - // SIMD computation (strided) - for (auto& x : tape) { - os << " auto tmp_" << namer.get_name(x) << " = "; - if (is_static_cast(x.primitive())) { - auto tstr = get_type_string(x.dtype()); - os << "Simd<" << tstr << ", _S>(tmp_" << namer.get_name(x.inputs()[0]) - << ");" << std::endl; - } else { - os << x.primitive().name() << "()("; - for (int i = 0; i < x.inputs().size() - 1; i++) { - os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; - } - os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; - } - } - - // SIMD stores (output is always contiguous) - for (auto& x : outputs) { - os << " simd::store(" << namer.get_name(x) << ", tmp_" - << namer.get_name(x) << ");" << std::endl; - os << " " << namer.get_name(x) << " += _S;" << std::endl; - } + // Read the inputs in tmps + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& x = inputs[i]; + auto& xname = namer.get_name(x); - os << " }" << std::endl; // close SIMD for - os << " }" << std::endl; // close if constexpr - - // ---- Scalar tail (strided) ---- - os << " for (; i" << inner_d << " < shape[" << inner_d << "]; ++i" - << inner_d << ") {" << std::endl; - - // Scalar reads (indexed by inner dim) - for (size_t i = 0; i < inputs.size(); ++i) { - const auto& x = inputs[i]; - auto& xname = namer.get_name(x); - auto tstr = get_type_string(x.dtype()); - - if (is_constant(i)) { - os << " " << tstr << " tmp_" << xname << " = "; - print_constant(os, x); - os << ";" << std::endl; - } else if (is_scalar(x)) { - os << " " << tstr << " tmp_" << xname << " = " << xname << "[0];" - << std::endl; - } else { - os << " " << tstr << " tmp_" << xname << " = " << xname << "[i" - << inner_d << " * " << xname << "_strides[" << inner_d << "]];" - << std::endl; - } + if (is_constant(i)) { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = "; + print_constant(os, x); + os << ";" << std::endl; + } else if (is_scalar(x)) { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " + << xname << "[0];" << std::endl; + } else if (contiguous) { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = " + << xname << "[i];" << std::endl; + } else { + os << " " << get_type_string(x.dtype()) << " tmp_" << xname << " = *" + << xname << ";" << std::endl; } + } - // Scalar computation (strided tail) - for (auto& x : tape) { - os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) - << " = "; - if (is_static_cast(x.primitive())) { - os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" - << namer.get_name(x.inputs()[0]) << ");" << std::endl; - } else { - os << x.primitive().name() << "()("; - for (int i = 0; i < x.inputs().size() - 1; i++) { - os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; - } - os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; + // Actually write the computation + for (auto& x : tape) { + os << " " << get_type_string(x.dtype()) << " tmp_" << namer.get_name(x) + << " = "; + if (is_static_cast(x.primitive())) { + os << "static_cast<" << get_type_string(x.dtype()) << ">(tmp_" + << namer.get_name(x.inputs()[0]) << ");" << std::endl; + } else { + os << x.primitive().name(); + os << "()("; + for (int i = 0; i < x.inputs().size() - 1; i++) { + os << "tmp_" << namer.get_name(x.inputs()[i]) << ", "; } + os << "tmp_" << namer.get_name(x.inputs().back()) << ");" << std::endl; } + } - // Scalar writes (output contiguous, pointer auto-advances) - for (auto& x : outputs) { + // Write the outputs from tmps + for (auto& x : outputs) { + if (contiguous) { + os << " " << namer.get_name(x) << "[i] = tmp_" << namer.get_name(x) + << ";" << std::endl; + } else { os << " *" << namer.get_name(x) << "++ = tmp_" << namer.get_name(x) << ";" << std::endl; } + } - os << " }" << std::endl; // close scalar tail - - // Close outer loops (d=ndim-2 down to 0) - // Inner dim uses indexed access (no pointer accumulation), so outer loops - // only undo accumulation from dimensions > inner_d (i.e., d+1 < inner_d). - for (int d = ndim - 2; d >= 0; --d) { + // Close loops + if (contiguous) { + os << " }" << std::endl; + } else { + for (int d = ndim - 1; d >= 0; --d) { + // Update pointers for (size_t i = 0; i < inputs.size(); ++i) { const auto& x = inputs[i]; if (is_constant(i) || is_scalar(x)) { @@ -451,9 +278,9 @@ inline void build_kernel( auto& xname = namer.get_name(x); os << " " << xname << " += " << xname << "_strides[" << d << "];" << std::endl; - if (d < ndim - 2) { - os << " " << xname << " -= " << xname << "_strides[" << d + 1 - << "] * shape[" << d + 1 << "];" << std::endl; + if (d < ndim - 1) { + os << " " << xname << " -= " << xname << "_strides[" << d + 1 << "]" + << " * shape[" << d + 1 << "];" << std::endl; } } os << " }" << std::endl; @@ -531,152 +358,20 @@ void Compiled::eval_cpu( args.push_back(x.data()); encoder.set_output_array(x); } - // Metadata for parallel dispatch - SmallVector arg_itemsize; - SmallVector arg_is_scalar; - size_t num_data_args = 0; // input + output args (excludes trailing size arg) - - for (size_t i = 0; i < inputs.size(); ++i) { - if (is_constant_(i)) - continue; - arg_itemsize.push_back(inputs[i].itemsize()); - arg_is_scalar.push_back(is_scalar(inputs_[i])); - num_data_args++; - } - for (auto& x : outputs) { - arg_itemsize.push_back(x.itemsize()); - arg_is_scalar.push_back(false); - num_data_args++; - } - if (contiguous) { args.push_back((void*)outputs[0].data_size()); } - auto fun = reinterpret_cast(fn_ptr); - - if (contiguous) { - size_t total_size = outputs[0].data_size(); - auto& pool = cpu::ThreadPool::instance(); - int n_threads = cpu::effective_threads(total_size, pool.max_threads()); - - if (n_threads > 1) { - // Multi-threaded: parallel_for splits work across threads - encoder.dispatch([fun, - args, - arg_itemsize, - arg_is_scalar, - num_data_args, - total_size, - n_threads]() mutable { - auto& pool = cpu::ThreadPool::instance(); - pool.parallel_for(n_threads, [&](int tid, int nth) { - size_t chunk = (total_size + nth - 1) / nth; - size_t start = chunk * tid; - size_t end = std::min(start + chunk, total_size); - if (start >= end) - return; - - SmallVector thread_args(args.size()); - for (size_t j = 0; j < num_data_args; ++j) { - if (arg_is_scalar[j]) { - thread_args[j] = args[j]; - } else { - thread_args[j] = - static_cast(args[j]) + start * arg_itemsize[j]; - } - } - thread_args[num_data_args] = (void*)(end - start); - fun(nullptr, nullptr, thread_args.data()); - }); - }); - } else { - // Single-threaded contiguous - encoder.dispatch([fun, args = std::move(args)]() mutable { - fun(nullptr, nullptr, args.data()); - }); - } - } else { - // Strided path with threading - size_t total_size = outputs[0].data_size(); - auto& pool = cpu::ThreadPool::instance(); - int n_threads = cpu::effective_threads(total_size, pool.max_threads()); - if (!shape.empty()) { - n_threads = std::min(n_threads, (int)shape[0]); + encoder.dispatch([fun, + args = std::move(args), + strides = std::move(strides), + shape = std::move(shape)]() mutable { + SmallVector strides_ptrs; + for (auto& s : strides) { + strides_ptrs.push_back(s.data()); } - - if (n_threads > 1 && !shape.empty() && shape[0] > 1) { - // Compute outermost stride for each arg (for pointer offsetting) - SmallVector arg_outer_stride(num_data_args); - { - int si = 1; // strides[0] is output, inputs start at 1 - size_t arg_j = 0; - for (size_t i = 0; i < inputs.size(); ++i) { - if (is_constant_(i)) - continue; - if (arg_is_scalar[arg_j]) { - arg_outer_stride[arg_j] = 0; - } else { - arg_outer_stride[arg_j] = strides[si][0]; - si++; - } - arg_j++; - } - // Output args use strides[0] (output strides) - for (size_t i = arg_j; i < num_data_args; ++i) { - arg_outer_stride[i] = strides[0][0]; - } - } - - encoder.dispatch([fun, - args, - strides = std::move(strides), - shape = std::move(shape), - arg_outer_stride, - arg_itemsize, - num_data_args, - n_threads]() mutable { - SmallVector strides_ptrs; - for (auto& s : strides) { - strides_ptrs.push_back(s.data()); - } - auto& pool = cpu::ThreadPool::instance(); - pool.parallel_for(n_threads, [&](int tid, int nth) { - int chunk = (shape[0] + nth - 1) / nth; - int start = chunk * tid; - int end = std::min(start + chunk, shape[0]); - if (start >= end) - return; - - SmallVector thread_args(args.begin(), args.end()); - for (size_t j = 0; j < num_data_args; ++j) { - if (arg_outer_stride[j] != 0) { - thread_args[j] = static_cast(args[j]) + - start * arg_outer_stride[j] * - static_cast(arg_itemsize[j]); - } - } - - auto thread_shape = shape; - thread_shape[0] = end - start; - - fun(thread_shape.data(), strides_ptrs.data(), thread_args.data()); - }); - }); - } else { - // Single-threaded strided - encoder.dispatch([fun, - args = std::move(args), - strides = std::move(strides), - shape = std::move(shape)]() mutable { - SmallVector strides_ptrs; - for (auto& s : strides) { - strides_ptrs.push_back(s.data()); - } - fun(shape.data(), strides_ptrs.data(), args.data()); - }); - } - } + fun(shape.data(), strides_ptrs.data(), args.data()); + }); } } // namespace mlx::core diff --git a/mlx/backend/cpu/compiled_preamble.h b/mlx/backend/cpu/compiled_preamble.h index b3b8465729..02e3db8e78 100644 --- a/mlx/backend/cpu/compiled_preamble.h +++ b/mlx/backend/cpu/compiled_preamble.h @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023-24 Apple Inc. #pragma once @@ -10,10 +10,3 @@ // clang-format on const char* get_prebuilt_preamble(); - -#ifdef MLX_HAVE_JIT_PREAMBLE_HWY_AVX2 -const char* get_prebuilt_preamble_avx2(); -#endif -#ifdef MLX_HAVE_JIT_PREAMBLE_HWY_AVX3 -const char* get_prebuilt_preamble_avx3(); -#endif diff --git a/mlx/backend/cpu/jit_compiler.cpp b/mlx/backend/cpu/jit_compiler.cpp index 0f093b9ea4..530637e551 100644 --- a/mlx/backend/cpu/jit_compiler.cpp +++ b/mlx/backend/cpu/jit_compiler.cpp @@ -5,10 +5,7 @@ #include "mlx/backend/cpu/compiled_preamble.h" #include -#include -#include #include -#include #include #include @@ -23,16 +20,6 @@ namespace mlx::core { namespace { -enum class JitPreambleTier { - Scalar, - HwyAvx2, - HwyAvx3, -}; - -// Preamble tiers are independent of Highway's runtime-dispatched kernel -// targets. CMake only embeds the available preambles; the JIT chooses the best -// one for the local CPU and runtime compiler. - #if defined(_MSC_VER) // Split string into array. @@ -46,17 +33,6 @@ std::vector str_split(const std::string& str, char delimiter) { return tokens; } -std::string get_env_var(const char* name) { - char* value = nullptr; - size_t size = 0; - if (_dupenv_s(&value, &size, name) != 0 || value == nullptr) { - return {}; - } - std::string result(value); - std::free(value); - return result; -} - // Get path information about MSVC. struct VisualStudioInfo { VisualStudioInfo() { @@ -68,8 +44,8 @@ struct VisualStudioInfo { // Get path of Visual Studio. // Use -latest to get only the most recent installation when multiple // versions are installed, avoiding path concatenation issues. - std::string pf86 = get_env_var("ProgramFiles(x86)"); - if (pf86.empty()) { + auto pf86 = std::getenv("ProgramFiles(x86)"); + if (!pf86) { throw std::runtime_error( "ProgramFiles(x86) environment variable not set."); } @@ -119,10 +95,7 @@ struct VisualStudioInfo { } } - std::string compiler(bool use_include, JitPreambleTier tier) const { - if (tier == JitPreambleTier::HwyAvx3 && !clang_cl.empty()) { - return clang_cl; - } + std::string compiler(bool use_include) const { if (use_include) { // With installed headers, either cl.exe or clang-cl can parse the source. // Prefer cl.exe since it is part of the standard Visual Studio C++ @@ -154,58 +127,7 @@ const VisualStudioInfo& GetVisualStudioInfo() { #endif // defined(_MSC_VER) -#if !defined(_MSC_VER) -std::string jit_cxx_compiler() { - if (const char* compiler = std::getenv("MLX_JIT_CXX"); - compiler && compiler[0] != '\0') { - return compiler; - } -#if defined(__clang__) - return "clang++"; -#else - return "g++"; -#endif -} - -std::string command_executable(const std::string& executable) { -#if defined(_WIN32) - if (executable.find_first_of(" \t\"") == std::string::npos) { - return executable; - } -#endif - return fmt::format("\"{}\"", executable); -} - -std::string command_path(const std::filesystem::path& path) { -#if defined(_WIN32) - return path.generic_string(); -#else - return path.string(); -#endif -} -#endif // !defined(_MSC_VER) - -std::filesystem::path find_jit_include_dir(bool require_highway) { - std::vector roots; - auto binary_dir = current_binary_dir(); - roots.push_back(binary_dir); -#if !defined(_WIN32) - roots.push_back(binary_dir.parent_path()); -#endif - - for (const auto& root : roots) { - auto include_dir = root / "include"; - auto preamble_header = include_dir / "mlx/backend/cpu/compiled_preamble.h"; - auto highway_header = include_dir / "hwy/highway.h"; - if (std::filesystem::exists(preamble_header) && - (!require_highway || std::filesystem::exists(highway_header))) { - return include_dir; - } - } - return {}; -} - -bool supports_hwy_avx2_preamble() { +bool supports_avx2_target() { #if defined(_MSC_VER) #if defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) @@ -226,9 +148,7 @@ bool supports_hwy_avx2_preamble() { return false; } __cpuidex(info, 7, 0); - bool avx2 = info[1] & (1 << 5); - bool bmi2 = info[1] & (1 << 8); - return avx2 && bmi2; + return info[1] & (1 << 5); #else return false; #endif // defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) @@ -237,8 +157,8 @@ bool supports_hwy_avx2_preamble() { #if defined(__x86_64__) || defined(__i386__) || defined(__amd64__) __builtin_cpu_init(); - return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("bmi2") && - __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c"); + return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && + __builtin_cpu_supports("f16c"); #else return false; #endif @@ -248,109 +168,20 @@ bool supports_hwy_avx2_preamble() { #endif // defined(_MSC_VER) } -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - -bool supports_hwy_avx3_preamble() { -#if defined(_MSC_VER) - -#if defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) - int info[4]; - __cpuid(info, 0); - if (info[0] < 7) { - return false; - } - __cpuid(info, 1); - const uint32_t ecx = static_cast(info[2]); - const bool os_avx = (ecx & (1u << 27)) && (ecx & (1u << 28)); - const bool fma = ecx & (1u << 12); - const bool f16c = ecx & (1u << 29); - if (!os_avx) { - return false; - } - const unsigned long long xcr0 = _xgetbv(0); - if ((xcr0 & 0xE6) != 0xE6) { - return false; - } - __cpuidex(info, 7, 0); - const uint32_t ebx = static_cast(info[1]); - const bool bmi2 = ebx & (1u << 8); - const bool avx512f = ebx & (1u << 16); - const bool avx512dq = ebx & (1u << 17); - const bool avx512cd = ebx & (1u << 28); - const bool avx512bw = ebx & (1u << 30); - const bool avx512vl = ebx & (1u << 31); - return avx512f && avx512dq && avx512cd && avx512bw && avx512vl && bmi2 && - fma && f16c; -#else - return false; -#endif // defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) - -#elif defined(__GNUC__) || defined(__clang__) - -#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__) - __builtin_cpu_init(); - return __builtin_cpu_supports("avx512f") && - __builtin_cpu_supports("avx512dq") && - __builtin_cpu_supports("avx512cd") && - __builtin_cpu_supports("avx512bw") && - __builtin_cpu_supports("avx512vl") && __builtin_cpu_supports("bmi2") && - __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c"); -#else - return false; -#endif - -#else - return false; -#endif -} - -bool can_compile_hwy_avx3_preamble() { -#if defined(_MSC_VER) - return !GetVisualStudioInfo().clang_cl.empty(); -#else - return true; -#endif -} - -#endif // defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - -JitPreambleTier select_jit_preamble_tier() { -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - if (supports_hwy_avx3_preamble() && can_compile_hwy_avx3_preamble()) { - return JitPreambleTier::HwyAvx3; - } -#endif -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) - if (supports_hwy_avx2_preamble()) { - return JitPreambleTier::HwyAvx2; - } -#endif - return JitPreambleTier::Scalar; -} - -JitPreambleTier jit_preamble_tier() { - static JitPreambleTier tier = select_jit_preamble_tier(); - return tier; -} - -bool use_hwy_avx2_preamble() { - return jit_preamble_tier() == JitPreambleTier::HwyAvx2; -} - -bool use_hwy_avx3_preamble() { - return jit_preamble_tier() == JitPreambleTier::HwyAvx3; -} - } // namespace const std::tuple& JitCompiler::get_preamble() { - static auto scalar_preamble = - []() -> std::tuple { + static auto preamble = []() -> std::tuple { // Check whether the headers are shipped with the binary, if so use the // preamble from the headers, otherwise use the prebuilt one embedded in // binary, which may not work with all compilers. - auto include_dir = find_jit_include_dir(false); - if (!include_dir.empty()) { + auto root_dir = current_binary_dir(); +#if !defined(_WIN32) + root_dir = root_dir.parent_path(); +#endif + auto include_dir = root_dir / "include"; + if (std::filesystem::exists( + include_dir / "mlx/backend/cpu/compiled_preamble.h")) { return std::make_tuple( true, include_dir.string(), @@ -359,53 +190,7 @@ const std::tuple& JitCompiler::get_preamble() { return std::make_tuple(false, "", get_prebuilt_preamble()); } }(); -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) - static auto avx2_preamble = - []() -> std::tuple { - // Check whether the headers are shipped with the binary, if so use the - // preamble from the headers, otherwise use the prebuilt one embedded in - // binary, which may not work with all compilers. - auto include_dir = find_jit_include_dir(true); - if (!include_dir.empty()) { - return std::make_tuple( - true, - include_dir.string(), - "#define MLX_USE_HIGHWAY_JIT_SIMD\n" - "#define HWY_COMPILE_ONLY_STATIC\n" - "#define HWY_DISABLE_PCLMUL_AES\n" - "#include \"mlx/backend/cpu/compiled_preamble.h\"\n"); - } else { - // Installed MLX headers alone are not enough for the Highway SIMD facade. - // Wheels can still use the embedded prebuilt AVX2 preamble without - // shipping Highway headers as a runtime payload. - return std::make_tuple(false, "", get_prebuilt_preamble_avx2()); - } - }(); -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - static auto avx3_preamble = - []() -> std::tuple { - auto include_dir = find_jit_include_dir(true); - if (!include_dir.empty()) { - return std::make_tuple( - true, - include_dir.string(), - "#define MLX_USE_HIGHWAY_JIT_SIMD\n" - "#define HWY_COMPILE_ONLY_STATIC\n" - "#define HWY_DISABLE_PCLMUL_AES\n" - "#include \"mlx/backend/cpu/compiled_preamble.h\"\n"); - } else { - return std::make_tuple(false, "", get_prebuilt_preamble_avx3()); - } - }(); - if (use_hwy_avx3_preamble()) { - return avx3_preamble; - } -#endif - if (use_hwy_avx2_preamble()) { - return avx2_preamble; - } -#endif - return scalar_preamble; + return preamble; } bool JitCompiler::available() { @@ -414,7 +199,7 @@ bool JitCompiler::available() { try { bool use_include = std::get<0>(get_preamble()); const auto& info = GetVisualStudioInfo(); - return !info.compiler(use_include, jit_preamble_tier()).empty(); + return !info.compiler(use_include).empty(); } catch (...) { return false; } @@ -422,18 +207,11 @@ bool JitCompiler::available() { return result; #else #ifdef _WIN32 - // Windows CPU JIT is only enabled for the Visual Studio ABI path above. - // MinGW-style JIT code was slower than the runtime-dispatched kernels in - // testing and has a more fragile runtime DLL discovery story. - return false; + static int result = std::system("g++ --version > NUL 2>&1"); #else - static int result = std::system( - fmt::format( - "{} --version > /dev/null 2>&1", - command_executable(jit_cxx_compiler())) - .c_str()); - return result == 0; + static int result = std::system("g++ --version > /dev/null 2>&1"); #endif + return result == 0; #endif } @@ -448,11 +226,9 @@ std::string JitCompiler::build_command( compiler_flags += fmt::format(" /I \"{}\"", include_dir); } const VisualStudioInfo& info = GetVisualStudioInfo(); - std::string compiler = info.compiler(use_include, jit_preamble_tier()); - for (const std::string& inc : info.includepaths) { - if (!inc.empty()) { - compiler_flags += fmt::format(" /I \"{}\"", inc); - } + std::string compiler = info.compiler(use_include); + for (const std::string& include : info.includepaths) { + compiler_flags += fmt::format(" /I \"{}\"", include); } std::string libpaths; for (const std::string& lib : info.libpaths) { @@ -464,14 +240,8 @@ std::string JitCompiler::build_command( if (!info.clang_cl.empty() && compiler == info.clang_cl) { compiler_flags += " -Wno-everything"; } -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) || \ - defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - if (use_hwy_avx3_preamble()) { - compiler_flags += - " /clang:-mavx512f /clang:-mavx512vl /clang:-mavx512bw" - " /clang:-mavx512dq /clang:-mavx512cd /clang:-mbmi2" - " /clang:-mfma /clang:-mf16c"; - } else if (use_hwy_avx2_preamble()) { +#ifdef __AVX2__ + if (supports_avx2_target()) { compiler_flags += " /arch:AVX2"; } #endif @@ -492,30 +262,19 @@ std::string JitCompiler::build_command( if (use_include) { extra_flags = fmt::format("-I \"{}\"", include_dir); } -#if defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX2) || \ - defined(MLX_HAVE_JIT_PREAMBLE_HWY_AVX3) - if (use_hwy_avx3_preamble()) { - if (!extra_flags.empty()) { - extra_flags += " "; - } - extra_flags += - "-mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd " - "-mbmi2 -mfma -mf16c"; - } else if (use_hwy_avx2_preamble()) { +#ifdef __AVX2__ + if (supports_avx2_target()) { if (!extra_flags.empty()) { extra_flags += " "; } - // JIT code is compiled locally, so it can pin to the current CPU after the - // runtime feature check while the shipped MLX binary remains baseline-safe. - extra_flags += "-mavx2 -mbmi2 -mfma -mf16c"; + extra_flags += "-mavx2 -mfma -mf16c"; } #endif return fmt::format( - "{} -std=c++17 -O3 -Wall -fPIC -shared {} \"{}\" -o \"{}\" 2>&1", - command_executable(jit_cxx_compiler()), + "g++ -std=c++17 -O3 -Wall -fPIC -shared {} \"{}\" -o \"{}\" 2>&1", extra_flags, - command_path(dir / source_file_name), - command_path(dir / shared_lib_name)); + (dir / source_file_name).string(), + (dir / shared_lib_name).string()); #endif } diff --git a/mlx/backend/cpu/make_compiled_preamble.ps1 b/mlx/backend/cpu/make_compiled_preamble.ps1 index f1516e8e02..e9fa7afba6 100644 --- a/mlx/backend/cpu/make_compiled_preamble.ps1 +++ b/mlx/backend/cpu/make_compiled_preamble.ps1 @@ -10,22 +10,7 @@ $SRCDIR = $args[2] # on macOS it controls -nobuiltininc and -arch flags for the preprocessor. # MSVC and clang-cl both accept the same preprocessor flags so no distinction needed.) # args[4] = CMAKE_SYSTEM_PROCESSOR (unused on Windows) -$FUNCTION_NAME = "get_prebuilt_preamble" -$SIMD_FLAGS = "" -$EXTRA_INCLUDE = "" -if ($args.Count -gt 5) { - if ($args.Count -eq 6 -and $args[5] -like "get_prebuilt_preamble*") { - $FUNCTION_NAME = $args[5] - } else { - $SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mbmi2 -mfma -mf16c" - if ($args.Count -gt 6) { - $EXTRA_INCLUDE = $args[6] # Optional, e.g. Highway headers for JIT SIMD preambles. - } - if ($args.Count -gt 7 -and $args[7]) { - $FUNCTION_NAME = $args[7] - } - } -} +$SIMD_FLAGS = $args[5] # Optional, e.g. "/arch:AVX2" or "-mavx2 -mfma -mf16c" # Detect compiler type: MSVC/clang-cl use /EP, GCC/clang++ use -E -P $CL_NAME = [System.IO.Path]::GetFileNameWithoutExtension($CL) @@ -47,31 +32,18 @@ if ($SIMD_FLAGS) { } if ($IS_MSVC_LIKE) { [void]$CL_ARGS.Add("/I$SRCDIR") - if ($EXTRA_INCLUDE) { - [void]$CL_ARGS.Add("/I$EXTRA_INCLUDE") - } [void]$CL_ARGS.Add('/Tp') } else { [void]$CL_ARGS.Add('-I') [void]$CL_ARGS.Add("$SRCDIR") - if ($EXTRA_INCLUDE) { - [void]$CL_ARGS.Add('-I') - [void]$CL_ARGS.Add("$EXTRA_INCLUDE") - } } [void]$CL_ARGS.Add("$SRCDIR/mlx/backend/cpu/compiled_preamble.h") # Get command result as array. Redirect stderr to null to suppress warnings. $CONTENT = & $CL @CL_ARGS 2>$null -if ($LASTEXITCODE -ne 0) { - throw "Failed to preprocess JIT preamble with $CL (exit code $LASTEXITCODE)" -} # Remove empty lines. # Otherwise there will be too much empty lines making the result unreadable. $CONTENT = $CONTENT | Where-Object { $_.Trim() -ne '' } -if (-not $CONTENT) { - throw "Failed to preprocess JIT preamble with ${CL}: no output" -} # Concatenate to string. $CONTENT = $CONTENT -join "`n" @@ -82,7 +54,7 @@ $CONTENT = $CONTENT -join "`n" $CHARCODES = ([System.Text.Encoding]::ASCII.GetBytes($CONTENT) -join ', ') + ', 0' $OUTPUT = @" -const char* $FUNCTION_NAME() { +const char* get_prebuilt_preamble() { static char preamble[] = { $CHARCODES }; return preamble; } diff --git a/mlx/backend/cpu/make_compiled_preamble.sh b/mlx/backend/cpu/make_compiled_preamble.sh index b0a79cec16..dc53bb8b53 100644 --- a/mlx/backend/cpu/make_compiled_preamble.sh +++ b/mlx/backend/cpu/make_compiled_preamble.sh @@ -11,9 +11,7 @@ GCC=$2 SRCDIR=$3 CLANG=$4 ARCH=$5 -SIMD_FLAGS=$6 # Optional, e.g. "-mavx2 -mbmi2 -mfma -mf16c" -EXTRA_INCLUDE=$7 # Optional, e.g. Highway headers for JIT SIMD preambles. -FUNCTION_NAME=${8:-get_prebuilt_preamble} +SIMD_FLAGS=$6 # Optional, e.g. "-mavx2 -mfma -mf16c" if [ "$CLANG" = "TRUE" ]; then read -r -d '' INCLUDES <<- EOM @@ -30,18 +28,10 @@ else CC_FLAGS="-std=c++17" fi -EXTRA_INCLUDE_FLAGS=() -if [ -n "$EXTRA_INCLUDE" ]; then - EXTRA_INCLUDE_FLAGS=(-I "$EXTRA_INCLUDE") -fi - -CONTENT=$( - "$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" "${EXTRA_INCLUDE_FLAGS[@]}" \ - -E -P "$SRCDIR/mlx/backend/cpu/compiled_preamble.h" 2>/dev/null -) +CONTENT=$("$GCC" $CC_FLAGS $SIMD_FLAGS -I "$SRCDIR" -E -P "$SRCDIR/mlx/backend/cpu/compiled_preamble.h" 2>/dev/null) cat << EOF > "$OUTPUT_FILE" -const char* $FUNCTION_NAME() { +const char* get_prebuilt_preamble() { return R"preamble( $INCLUDES $CONTENT From 56faa32426a38dccf1a1f2092d6f440b7e161f9f Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:50:26 +0200 Subject: [PATCH 07/65] Select the CPU quantized backend by file #3019 rewrites quantized.cpp well beyond its Highway guards: thread-pool calls, a dequantize-then-SGEMM path and new kernels sit outside them, and every build compiles the file. Keep it as quantized_highway_backend.cpp, compiled only with MLX_USE_HIGHWAY_KERNELS, and restore the fork's quantized.cpp for every other build, so builds without Highway compile exactly what they did. --- mlx/backend/cpu/CMakeLists.txt | 5 + mlx/backend/cpu/quantized.cpp | 2001 ++---------- mlx/backend/cpu/quantized_highway_backend.cpp | 2734 +++++++++++++++++ 3 files changed, 3063 insertions(+), 1677 deletions(-) create mode 100644 mlx/backend/cpu/quantized_highway_backend.cpp diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 4c35040637..b716b9e48f 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -143,6 +143,11 @@ target_sources( ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) if(MLX_ENABLE_X86_SIMD) + # quantized.cpp's Highway counterpart (quantized.cpp compiles to nothing + # here). + target_sources( + mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway_backend.cpp) + if(MSVC AND NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(MLX_HIGHWAY_MSVC_DISPATCH_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/norms_highway_dispatch.cpp diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index ffb91ee23c..668009e108 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -1,104 +1,34 @@ // Copyright © 2023-2026 Apple Inc. +#if !defined(MLX_USE_HIGHWAY_KERNELS) +// Builds with Highway compile quantized_highway_backend.cpp instead. #include "mlx/backend/common/quantized.h" -#include -#include -#include #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" -#include "mlx/backend/cpu/lapack.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); -} +namespace { -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]]; +array ensure_row_contiguous( + const array& arr, + cpu::CommandEncoder& encoder, + Stream s) { + if (arr.flags().row_contiguous) { + return arr; + } else { + auto arr_cpy = contiguous_copy_cpu(arr, s); + encoder.add_temporary(arr_cpy); + return arr_cpy; } - return simd::load(tmp); -} - -} // namespace mlx::core -#endif // ISA dispatch - -namespace mlx::core { - -namespace { +}; const static float FP4_LUT[16] = { +0.0f, @@ -118,51 +48,10 @@ const static float FP4_LUT[16] = { -4.0f, -6.0f}; -// FP8 E4M3 -> float32 lookup table (256 entries, 1KB). -// Precomputed from the FromFP8 decode: strip sign, interpret lower 7 bits -// as float16 mantissa/exponent (<<7), multiply by 256, apply sign. -// Used by FP quantized matmul for O(1) FP8 weight decoding. -// 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, 480.0f, - -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, -480.0f, -}; -// clang-format on - template static inline T dequantize_scale(uint8_t s) { if constexpr (group_size == 16) { - return static_cast(FP8_LUT[s]); + return static_cast(detail::FromFP8{}(s)); } else { using FOrI = union { bfloat16_t f; @@ -264,238 +153,82 @@ void _qmm( } } -// Helper for computing a range of output columns in _qmm_t (used by threaded -// version) template -void _qmm_t_cols( +void _qmm_t( T* result, const T* x, const uint32_t* w, const T* scales, const T* biases, - int n_start, - int n_end, + 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; - // 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; - T sum = 0; - - for (int k = 0; k < K; k += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; - - for (int kw = 0; kw < packs_in_group; kw++) { - if constexpr (bits == 3 || bits == 5 || bits == 6) { - T wl[pack_factor]; - extract_bits(w_local, wl); -#pragma clang loop unroll(full) - for (int p = 0; p < pack_factor; p++) { - sum += 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 += (*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; - } + 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; - // 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 n = 0; n < N; n++) { + const T* x_local = x; + T sum = 0; + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; - 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; - T sum = 0; - for (int k = 0; k < K; k += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; - - for (int kw = 0; kw < packs_in_group; kw++) { - if constexpr (bits == 3 || bits == 5 || bits == 6) { - T wl[pack_factor]; - extract_bits(w_local, wl); + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T wl[pack_factor]; + extract_bits(w_local, wl); #pragma clang loop unroll(full) - for (int p = 0; p < pack_factor; p++) { - sum += x_local[p] * (scale * wl[p] + bias); - } - w_local += bytes_per_pack; - x_local += pack_factor; - } else { - uint8_t wi = *w_local++; + for (int p = 0; p < pack_factor; p++) { + sum += 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 += (*x_local++) * - (scale * static_cast(wi & bitmask) + bias); - if (bits != 8) { - wi >>= bits; - } + for (int p = 0; p < pack_factor; p++) { + sum += + (*x_local++) * (scale * static_cast(wi & bitmask) + bias); + if (bits != 8) { + wi >>= bits; } } } } - *result = sum; - result++; } + *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) { +simd::Simd extract_bits_simd(const uint32_t* w) { 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) { + 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); + auto l = simd::Simd(*w++); + auto r = simd::Simd(*w); + wi = simd::Simd(l, r); wi = wi >> shifts; wi = wi & bitmask; } else { @@ -505,309 +238,6 @@ simd::Simd extract_bits_simd(const uint32_t* w, int elem_off = 0) { 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, @@ -819,349 +249,42 @@ void _qmm_t_simd( int N, int K) { constexpr int pack_factor = 32 / bits; - constexpr int S = simd::max_size; + constexpr int packs_in_group = group_size / pack_factor; + 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); - } + S % pack_factor == 0, "SIMD size must be divisible by pack factor"); + constexpr int packs_per_simd = S / pack_factor; - 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 buffer for dequant+BLAS path. -float* _qmm_get_scratch(size_t n) { - thread_local std::vector buf; - if (buf.size() < n) { - buf.resize(n); - } - return buf.data(); -} - -// 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; - float* w_f32 = _qmm_get_scratch(w_f32_size + x_f32_size + r_f32_size); - 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]); - } + for (int m = 0; m < M; m++) { + const uint32_t* w_local = w; + const T* scales_local = scales; + const T* biases_local = biases; - 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]); - } - } + simd::Simd acc(0); + auto x_local = x; + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; - // 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); + for (int kw = 0; kw < packs_in_group; kw += packs_per_simd) { + auto wf = simd::Simd(extract_bits_simd(w_local)); + w_local += packs_per_simd; + wf = wf * scale; + wf = wf + bias; + simd::Simd x_simd = simd::load(x_local); + acc = acc + x_simd * wf; + x_local += S; + } } - }); - } 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]); + *result = T(simd::sum(acc)); + result++; } + x += K; } } -// 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, @@ -1174,26 +297,8 @@ void _qmm_dispatch_transpose( 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. - 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) { + // the simd size must be a multiple of the number of elements per word + if constexpr (32 % bits == 0 && simd::max_size % (32 / bits) == 0) { _qmm_t_simd(result, x, w, scales, biases, M, N, K); } else { _qmm_t(result, x, w, scales, biases, M, N, K); @@ -1351,8 +456,7 @@ void fp_qmm( const uint8_t* scales, int M, int N, - int K, - float scale_factor) { + int K) { constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; @@ -1367,10 +471,7 @@ void fp_qmm( T xi = *x++; for (int n = 0; n < N; n += group_size) { - T scale = static_cast( - static_cast( - dequantize_scale(*scales_local++)) * - scale_factor); + T scale = dequantize_scale(*scales_local++); for (int ng = 0; ng < packs_in_group; ng++) { if constexpr (bits == 4) { (*result_local++) += @@ -1379,7 +480,7 @@ void fp_qmm( xi * scale * static_cast(FP4_LUT[(w_local[0] >> 4) & 0xf]); } else { (*result_local++) += - xi * scale * static_cast(FP8_LUT[w_local[0]]); + xi * scale * static_cast(detail::FromFP8{}(w_local[0])); } w_local++; } @@ -1389,61 +490,6 @@ void fp_qmm( } } -// 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, @@ -1452,292 +498,64 @@ void fp_qmm_t( 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)); + int K) { + 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++) { - 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++; + 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 = dequantize_scale(*scales_local++); + + 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(detail::FromFP8{}(w_local[0])); } - sum += scale * gsum; + w_local++; } - *result = sum; - result++; + 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 +simd::Simd fp_extract_bits_simd(const uint32_t* w) { + if constexpr (S == 8 && bits == 4) { 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); + simd::Simd w_out; + for (int i = 0; i < S; ++i) { + w_out[i] = FP4_LUT[wi[i]]; + } + return w_out; } else if constexpr (S == 8 && bits == 8) { - // 8 FP8 values via SIMD LUT gather - return fp8_lut_gather_simd(w, FP8_LUT); + auto w_out = simd::load(reinterpret_cast(w)); + return detail::FromFP8{}(w_out); } 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, @@ -1746,77 +564,41 @@ void fp_qmm_t_simd( 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 + int K) { constexpr int pack_factor = get_pack_factor(bits, 32); - constexpr int S = simd::max_size; + constexpr int packs_in_group = group_size / pack_factor; + 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); - } + S % pack_factor == 0, "SIMD size must be divisible by pack factor"); + constexpr int packs_per_simd = S / pack_factor; + + for (int m = 0; m < M; m++) { + const uint32_t* w_local = w; + const uint8_t* scales_local = scales; + + for (int n = 0; n < N; n++) { + simd::Simd acc(0); + auto x_local = x; + for (int k = 0; k < K; k += group_size) { + T scale = dequantize_scale(*scales_local++); + + simd::Simd g_acc(0); + for (int kw = 0; kw < packs_in_group; kw += packs_per_simd) { + // Extract bits + auto wf = fp_extract_bits_simd(w_local); + w_local += packs_per_simd; + simd::Simd x_simd = simd::load(x_local); + g_acc = g_acc + x_simd * wf; + x_local += S; } - my_chunk = steal_counter.fetch_add(1, std::memory_order_relaxed); + acc = acc + scale * g_acc; } - }); - } 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); + + *result = T(simd::sum(acc)); + result++; } + x += K; } -#endif } template @@ -1828,30 +610,16 @@ void fp_qmm_dispatch_transpose( int M, int N, int K, - bool transposed_w, - float scale_factor) { + bool transposed_w) { 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); + // the simd size must be a multiple of the number of elements per word + if constexpr (simd::max_size % 8 == 0) { + fp_qmm_t_simd(result, x, w, scales, M, N, K); } else { - fp_qmm_t( - result, x, w, scales, M, N, K, scale_factor); + fp_qmm_t(result, x, w, scales, M, N, K); } } else { - fp_qmm(result, x, w, scales, M, N, K, scale_factor); + fp_qmm(result, x, w, scales, M, N, K); } } @@ -1861,8 +629,7 @@ void fp_qmm_dispatch_mode( const array& x, const array& w, const array& scales, - bool transposed_w, - float scale_factor) { + bool transposed_w) { int K = x.shape(-1); int M = x.ndim() > 1 ? x.shape(-2) : 1; int N = out.shape(-1); @@ -1883,8 +650,7 @@ void fp_qmm_dispatch_mode( M, N, K, - transposed_w, - scale_factor); + transposed_w); } } @@ -1896,17 +662,13 @@ void fp_qmm_dispatch_typed( const array& scales, int group_size, int bits, - bool transposed_w, - float scale_factor) { + bool transposed_w) { if (bits == 8) { - fp_qmm_dispatch_mode( - out, x, w, scales, transposed_w, scale_factor); + fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); } else if (group_size == 32) { - fp_qmm_dispatch_mode( - out, x, w, scales, transposed_w, scale_factor); + fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); } else { - fp_qmm_dispatch_mode( - out, x, w, scales, transposed_w, scale_factor); + fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); } } @@ -1917,20 +679,19 @@ void fp_qmm_dispatch( const array& scales, int group_size, int bits, - bool transposed_w, - float scale_factor = 1.0f) { + bool transposed_w) { switch (x.dtype()) { case bfloat16: fp_qmm_dispatch_typed( - out, x, w, scales, group_size, bits, transposed_w, scale_factor); + out, x, w, scales, group_size, bits, transposed_w); break; case float16: fp_qmm_dispatch_typed( - out, x, w, scales, group_size, bits, transposed_w, scale_factor); + out, x, w, scales, group_size, bits, transposed_w); break; case float32: fp_qmm_dispatch_typed( - out, x, w, scales, group_size, bits, transposed_w, scale_factor); + out, x, w, scales, group_size, bits, transposed_w); break; default: throw std::invalid_argument( @@ -1965,44 +726,25 @@ void _bs_qmm_dispatch_typed( 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++) { + for (int i = 0; i < lhs_indices.size(); 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( + 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()); - } - - // 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], + x_ptr + elem_to_loc(x_idx * M * K, x.shape(), x.strides()), 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, + M, N, K, bits, group_size, transposed_w); - i += batch_count; } } @@ -2085,73 +827,21 @@ void fp_bs_qmm_dispatch_mode( 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++) { + for (int i = 0; i < lhs_indices.size(); 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, + x_ptr + elem_to_loc(x_idx * M * K, x.shape(), x.strides()), + 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()), + M, N, K, - transposed_w, - 1.0f); - i += batch_count; + transposed_w); } } @@ -2231,111 +921,6 @@ void fp_bs_qmm_dispatch( } } -// 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 { - // mxfp8: fp8_e8m0 scale (pure exponent, 2^round(log2(x))) - if (raw_scale == 0.0f) { - scale = 1.0f; // 2^0 when all values are zero - } else { - float exp = std::round(std::log2(raw_scale)); - scale = std::pow(2.0f, exp); - } - } - - 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; - int best_idx = 0; - float best_dist = std::abs(normalized - FP4_LUT[0]); - for (int j = 1; j < 16; j++) { - float dist = std::abs(normalized - FP4_LUT[j]); - if (dist < best_dist) { - best_dist = dist; - best_idx = j; - } - } - gp[i] = static_cast(FP4_LUT[best_idx] * 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 QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { @@ -2344,20 +929,9 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { 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); + auto x = ensure_row_contiguous(x_pre, encoder, stream()); + auto w = ensure_row_contiguous(w_pre, encoder, stream()); + auto scales = ensure_row_contiguous(scales_pre, encoder, stream()); out.set_data(allocator::malloc(out.nbytes())); @@ -2366,7 +940,7 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { encoder.set_input_array(scales); encoder.set_output_array(out); if (mode_ == QuantizationMode::Affine) { - auto biases = ensure_row_contiguous(inputs[3]); + auto biases = ensure_row_contiguous(inputs[3], encoder, stream()); encoder.set_input_array(biases); encoder.dispatch([out = array::unsafe_weak_copy(out), x = array::unsafe_weak_copy(x), @@ -2474,6 +1048,114 @@ void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { } } +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; +} + +template +void fp_quantize_dequantize( + const array& w_arr, + array& out_arr, + int bits, + int group_size, + size_t w_size) { + auto w = w_arr.data(); + auto out = out_arr.data(); + + size_t n_groups = w_size / group_size; + + for (size_t i = 0; i < n_groups; ++i) { + size_t idx = i * group_size; + float scale = -std::numeric_limits::infinity(); + for (int j = 0; j < group_size; ++j) { + scale = std::max(scale, std::abs(w[idx + j])); + } + scale /= bits == 4 ? 6.0f : 448.0f; + if (group_size == 16) { + scale = dequantize_scale(detail::ToFP8()(scale)); + } else { + scale = dequantize_scale(to_fp8_e8m0_round_up(scale)); + } + + for (int j = 0; j < group_size; ++j) { + float w_el = scale == 0 ? 0.0f : w[idx + j] / scale; + float output; + if (bits == 8) { + output = detail::FromFP8()(detail::ToFP8()(w_el)); + } else { + output = FP4_LUT[to_fp4_e2m1(w_el)]; + } + out[idx + j] = static_cast(scale * output); + } + } +} + +void dispatch_quantize_dequantize( + const array& w, + array& out, + int bits, + int group_size) { + if (w.dtype() == float16) { + fp_quantize_dequantize(w, out, bits, group_size, w.size()); + } else if (w.dtype() == bfloat16) { + fp_quantize_dequantize(w, out, bits, group_size, w.size()); + } else if (w.dtype() == float32) { + fp_quantize_dequantize(w, out, bits, group_size, w.size()); + } else { + throw std::runtime_error( + "[quantize_dequantize] Only supports floating point inputs"); + } +} + template void quantize( const T* w, @@ -2558,15 +1240,8 @@ void dispatch_quantize( void fast::Quantize::eval_cpu( const std::vector& inputs, std::vector& outputs) { - 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& encoder = cpu::get_command_encoder(stream()); + auto w = ensure_row_contiguous(inputs[0], encoder, stream()); auto& out = outputs[0]; out.set_data(allocator::malloc(out.nbytes())); @@ -2574,10 +1249,6 @@ void fast::Quantize::eval_cpu( 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); @@ -2661,67 +1332,42 @@ void fast::ConvertFP8::eval_cpu( void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { 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); + bool w_quantized = (inputs[1].dtype() == uint32); + if (w_quantized && inputs[0].shape(-2) == 1) { + bool donate_x = inputs[0].is_donatable(); + auto x = ensure_row_contiguous(inputs[0], encoder, stream()); + auto w = ensure_row_contiguous(inputs[1], encoder, stream()); + auto scales = ensure_row_contiguous(inputs[2], encoder, stream()); + + out.set_data(allocator::malloc(out.nbytes())); + + // If x is a copy it should be donatable + donate_x |= x.is_donatable(); + auto xhat = donate_x + ? x + : array(allocator::malloc(x.nbytes()), x.shape(), x.dtype()); + if (!donate_x) { + encoder.add_temporary(xhat); } - // 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); - }); + encoder.set_input_array(x); + encoder.set_input_array(w); + encoder.set_input_array(scales); + encoder.set_output_array(out); + encoder.dispatch([out = array::unsafe_weak_copy(out), + x = array::unsafe_weak_copy(x), + xhat = array::unsafe_weak_copy(xhat), + w = array::unsafe_weak_copy(w), + scales = array::unsafe_weak_copy(scales), + group_size_ = group_size_, + bits_ = bits_]() mutable { + dispatch_quantize_dequantize(x, xhat, bits_, group_size_); + fp_qmm_dispatch(out, xhat, w, scales, group_size_, bits_, true); + }); + return; + } else { + throw std::runtime_error("[QQMatmul] NYI for the general case"); + } } void GatherQQMM::eval_cpu(const std::vector& inputs, array& out) { @@ -2729,3 +1375,4 @@ void GatherQQMM::eval_cpu(const std::vector& inputs, array& out) { } } // namespace mlx::core +#endif // !defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp new file mode 100644 index 0000000000..82df47b616 --- /dev/null +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -0,0 +1,2734 @@ +// 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 "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/lapack.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). +// Precomputed from the FromFP8 decode: strip sign, interpret lower 7 bits +// as float16 mantissa/exponent (<<7), multiply by 256, apply sign. +// Used by FP quantized matmul for O(1) FP8 weight decoding. +// 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, 480.0f, + -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, -480.0f, +}; +// 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 : (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; + + 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(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 = *scales_local++; + T bias = *biases_local++; + for (int ng = 0; ng < packs_in_group; ng++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T 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; + } + } + } + } + } + } + + 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; + T sum = 0; + + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T wl[pack_factor]; + extract_bits(w_local, wl); +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += 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 += (*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; + T sum = 0; + for (int k = 0; k < K; k += group_size) { + T scale = *scales_local++; + T bias = *biases_local++; + + for (int kw = 0; kw < packs_in_group; kw++) { + if constexpr (bits == 3 || bits == 5 || bits == 6) { + T wl[pack_factor]; + extract_bits(w_local, wl); +#pragma clang loop unroll(full) + for (int p = 0; p < pack_factor; p++) { + sum += 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 += (*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 buffer for dequant+BLAS path. +float* _qmm_get_scratch(size_t n) { + thread_local std::vector buf; + if (buf.size() < n) { + buf.resize(n); + } + return buf.data(); +} + +// 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; + float* w_f32 = _qmm_get_scratch(w_f32_size + x_f32_size + r_f32_size); + 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. + 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 { + 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"); + } +} + +// 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 { + // mxfp8: fp8_e8m0 scale (pure exponent, 2^round(log2(x))) + if (raw_scale == 0.0f) { + scale = 1.0f; // 2^0 when all values are zero + } else { + float exp = std::round(std::log2(raw_scale)); + scale = std::pow(2.0f, exp); + } + } + + 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; + int best_idx = 0; + float best_dist = std::abs(normalized - FP4_LUT[0]); + for (int j = 1; j < 16; j++) { + float dist = std::abs(normalized - FP4_LUT[j]); + if (dist < best_dist) { + best_dist = dist; + best_idx = j; + } + } + gp[i] = static_cast(FP4_LUT[best_idx] * 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 QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { + 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 GatherQMM::eval_cpu(const std::vector& inputs, array& out) { + 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 fast::Quantize::eval_cpu( + const std::vector& inputs, + std::vector& outputs) { + 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) { + 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) From d3fd60b06fec0683ab9f3c4f90fdbd495dc487cf Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:58:54 +0200 Subject: [PATCH 08/65] Put #3019's changes to shared CPU files behind MLX_USE_HIGHWAY_KERNELS #3019 changes files that every CPU build compiles, macOS included: thread-pool calls in binary.h, unary.h, copy.cpp, indexing.cpp, reduce.cpp, softmax.cpp and cblas.cpp; the SIMD headers; out-of-line fast-primitive declarations. It also changes two groups that macOS does not compile: the no-GPU fallbacks and the low-precision GEMMs. Guard every hunk with MLX_USE_HIGHWAY_KERNELS, so that a build without Highway preprocesses each file exactly as before; vmlx-swift checks the files macOS compiles. Thirteen of these files, and mlx/io/load.h, get back the copyright lines they had before #3019 moved them to 2026. Without the macro, fast_primitives.h keeps its inline eval_cpu definitions, so #3019's norms.cpp, rope.cpp and sdpa.cpp, which define them out of line, now compile only in Highway builds. --- mlx/backend/cpu/CMakeLists.txt | 11 ++- mlx/backend/cpu/binary.h | 41 ++++++++++- mlx/backend/cpu/copy.cpp | 21 +++++- mlx/backend/cpu/gemms/cblas.cpp | 63 ++++++++++++++++- mlx/backend/cpu/gemms/simd_bf16.cpp | 29 +++++++- mlx/backend/cpu/gemms/simd_fp16.cpp | 29 +++++++- mlx/backend/cpu/indexing.cpp | 69 +++++++++++++++++- mlx/backend/cpu/reduce.cpp | 38 +++++++++- mlx/backend/cpu/simd/base_simd.h | 42 +++++++++++ mlx/backend/cpu/simd/math.h | 68 +++++++++++++++++- mlx/backend/cpu/simd/type.h | 2 + mlx/backend/cpu/softmax.cpp | 104 +++++++++++++++++++++++++++- mlx/backend/cpu/unary.h | 39 ++++++++++- mlx/backend/cpu/unary_ops.h | 29 +++++++- mlx/backend/no_gpu/primitives.cpp | 16 ++++- mlx/fast_primitives.h | 39 ++++++++++- mlx/io/load.h | 2 +- 17 files changed, 624 insertions(+), 18 deletions(-) diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index b716b9e48f..c12ac55da8 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -136,9 +136,6 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/inverse.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cholesky.cpp ${CMAKE_CURRENT_SOURCE_DIR}/unary.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/norms.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/sdpa.cpp ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) @@ -148,6 +145,14 @@ if(MLX_ENABLE_X86_SIMD) target_sources( mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway_backend.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) + if(MSVC AND NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(MLX_HIGHWAY_MSVC_DISPATCH_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/norms_highway_dispatch.cpp diff --git a/mlx/backend/cpu/binary.h b/mlx/backend/cpu/binary.h index 0fcec72369..b053e0fb48 100644 --- a/mlx/backend/cpu/binary.h +++ b/mlx/backend/cpu/binary.h @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023 Apple Inc. #pragma once #include @@ -10,7 +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 { @@ -19,11 +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))); @@ -44,11 +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))); @@ -68,11 +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))); @@ -148,7 +156,25 @@ 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 (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(); +#else int64_t num_iterations = size / stride; // Check if parallelization is beneficial @@ -203,6 +229,7 @@ void binary_op_dispatch_dims( a_it.step(); b_it.step(); } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -220,6 +247,9 @@ 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()); @@ -237,11 +267,15 @@ void binary_op(const array& a, const array& b, array& out, BinaryOpType bopt) { } 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()); @@ -259,11 +293,15 @@ void binary_op(const array& a, const array& b, array& out, BinaryOpType bopt) { } 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()); @@ -280,6 +318,7 @@ void binary_op(const array& a, const array& b, array& out, BinaryOpType bopt) { } 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 6311d0ecd7..2aaa7bdae1 100644 --- a/mlx/backend/cpu/copy.cpp +++ b/mlx/backend/cpu/copy.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023-2024 Apple Inc. #include @@ -7,7 +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" namespace mlx::core { @@ -110,8 +112,24 @@ 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, + dst_ptr + out.loc, + shape, + strides[0], + strides[1], + ndim - 3); + in.step(); + out.step(); +#else int64_t num_iterations = size / stride; // Check if parallelization is beneficial @@ -163,6 +181,7 @@ void copy_general_general( 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 9cd9eb05eb..8466679ab9 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -1,16 +1,20 @@ -// Copyright © 2025-2026 Apple Inc. +// Copyright © 2025 Apple Inc. #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/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, @@ -33,6 +37,24 @@ 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, + a_transposed ? CblasTrans : CblasNoTrans, // transA + b_transposed ? CblasTrans : CblasNoTrans, // transB + 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 // Check if parallelization over batches is beneficial auto& pool = cpu::ThreadPool::instance(); int n_threads = std::min( @@ -124,6 +146,7 @@ void matmul( ldc); } } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -149,6 +172,24 @@ 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, + a_transposed ? CblasTrans : CblasNoTrans, // transA + b_transposed ? CblasTrans : CblasNoTrans, // transB + 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 auto& pool = cpu::ThreadPool::instance(); int n_threads = std::min( pool.max_threads(), @@ -231,6 +272,7 @@ void matmul( ldc); } } +#endif // MLX_USE_HIGHWAY_KERNELS } } @@ -258,6 +300,24 @@ 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, + a_transposed ? CblasTrans : CblasNoTrans, // transA + b_transposed ? CblasTrans : CblasNoTrans, // transB + 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 auto& pool = cpu::ThreadPool::instance(); int n_threads = std::min( pool.max_threads(), @@ -340,6 +400,7 @@ void matmul( 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 e4c1d49f05..72c5f4d9ce 100644 --- a/mlx/backend/cpu/gemms/simd_bf16.cpp +++ b/mlx/backend/cpu/gemms/simd_bf16.cpp @@ -1,7 +1,14 @@ -// Copyright © 2025-2026 Apple Inc. +// 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 { @@ -22,6 +29,25 @@ 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]; + size_t K = a_shape[ndim - 1]; + for (int i = 0; i < batch_size; ++i) { + simd_gemm( + a + elem_to_loc(M * K * i, a_shape, a_strides), + b + elem_to_loc(K * N * i, b_shape, b_strides), + out + M * N * i, + a_transposed, + b_transposed, + M, + N, + K, + alpha, + beta); + } +#else detail::matmul_lowp( a, b, @@ -38,6 +64,7 @@ void matmul( 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 841db96790..8e954a7c1c 100644 --- a/mlx/backend/cpu/gemms/simd_fp16.cpp +++ b/mlx/backend/cpu/gemms/simd_fp16.cpp @@ -1,7 +1,14 @@ -// Copyright © 2025-2026 Apple Inc. +// 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 { @@ -22,6 +29,25 @@ 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]; + size_t K = a_shape[ndim - 1]; + for (int i = 0; i < batch_size; ++i) { + simd_gemm( + a + elem_to_loc(M * K * i, a_shape, a_strides), + b + elem_to_loc(K * N * i, b_shape, b_strides), + out + M * N * i, + a_transposed, + b_transposed, + M, + N, + K, + alpha, + beta); + } +#else detail::matmul_lowp( a, b, @@ -38,6 +64,7 @@ void matmul( a_strides, b_shape, b_strides); +#endif // MLX_USE_HIGHWAY_KERNELS } } // namespace mlx::core diff --git a/mlx/backend/cpu/indexing.cpp b/mlx/backend/cpu/indexing.cpp index 7a97066538..5d8f1e619c 100644 --- a/mlx/backend/cpu/indexing.cpp +++ b/mlx/backend/cpu/indexing.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023 Apple Inc. #include #include #include @@ -10,7 +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" @@ -88,9 +90,29 @@ 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; + 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]); +#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; @@ -145,8 +167,21 @@ void gather( 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) { + 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(); +#else size_t out_idx = 0; for (size_t idx = 0; idx < ind_size; idx++) { size_t src_idx = 0; @@ -157,7 +192,11 @@ void gather( 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]; @@ -174,6 +213,7 @@ void gather( } src_it.reset(); } +#endif // MLX_USE_HIGHWAY_KERNELS } } } @@ -253,8 +293,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(); @@ -275,6 +322,15 @@ 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) { + auto ind_val = offset_neg_idx( + 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(); @@ -296,7 +352,12 @@ void gather_axis( 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++) { @@ -331,7 +392,11 @@ void gather_axis( 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/reduce.cpp b/mlx/backend/cpu/reduce.cpp index d8c45de7c7..793041168b 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023 Apple Inc. #include #include @@ -7,7 +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 { @@ -108,6 +110,7 @@ void strided_reduce( } }; +#if defined(MLX_USE_HIGHWAY_KERNELS) // Accumulator type: use float for half-precision types to avoid precision loss template struct AccumType { @@ -122,28 +125,49 @@ struct AccumType { using type = float; }; +#endif // MLX_USE_HIGHWAY_KERNELS template void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) + constexpr int N = std::min(simd::max_size, simd::max_size); + simd::Simd accumulator_v(init); +#else using A = typename AccumType::type; constexpr int N = std::min(simd::max_size, simd::max_size); simd::Simd accumulator_v(static_cast(init)); +#endif // MLX_USE_HIGHWAY_KERNELS while (size >= N) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) + accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); +#else accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); +#endif // MLX_USE_HIGHWAY_KERNELS x += N; size -= N; } +#if !defined(MLX_USE_HIGHWAY_KERNELS) + *accumulator = op(*accumulator, op(accumulator_v)); +#else A simd_sum = op(accumulator_v); // horizontal reduction A scalar_acc = op(static_cast(*accumulator), simd_sum); +#endif // MLX_USE_HIGHWAY_KERNELS while (size-- > 0) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) + *accumulator = op(*accumulator, *x); +#else scalar_acc = op(scalar_acc, static_cast(*x)); +#endif // MLX_USE_HIGHWAY_KERNELS x++; } +#if defined(MLX_USE_HIGHWAY_KERNELS) *accumulator = static_cast(scalar_acc); +#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) { @@ -186,6 +210,7 @@ U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { return result; } +#endif // MLX_USE_HIGHWAY_KERNELS // Helper for the ndimensional strided loop void nd_loop( std::function callback, @@ -221,13 +246,23 @@ 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) @@ -262,6 +297,7 @@ void reduction_op( contiguous_reduce(my_in, my_out, reduction_size, Op{}, init); } }); +#endif // MLX_USE_HIGHWAY_KERNELS } return; } diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index 2be9a15e92..3620622066 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -1,4 +1,5 @@ #pragma once +#if defined(MLX_USE_HIGHWAY_KERNELS) #ifdef _MSC_VER #ifndef _USE_MATH_DEFINES @@ -20,6 +21,22 @@ #define M_LN2 0.69314718055994530942 #endif +#else + +// Required for using M_LN2 in MSVC. +#define _USE_MATH_DEFINES + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#include // For _BitScanReverse +#endif + +#endif // MLX_USE_HIGHWAY_KERNELS #include "mlx/types/complex.h" #include "mlx/types/half_types.h" @@ -49,6 +66,7 @@ struct Simd { } }; +#if defined(MLX_USE_HIGHWAY_KERNELS) namespace detail { template @@ -73,21 +91,28 @@ struct HasMemberStore< } // namespace detail +#endif // MLX_USE_HIGHWAY_KERNELS 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) { @@ -232,8 +257,17 @@ DEFAULT_BINARY(||) 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 @@ -264,7 +298,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)) { @@ -279,9 +317,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; } @@ -294,9 +334,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/math.h b/mlx/backend/cpu/simd/math.h index c731f1c748..bf29de381f 100644 --- a/mlx/backend/cpu/simd/math.h +++ b/mlx/backend/cpu/simd/math.h @@ -1,10 +1,12 @@ -// Copyright © 2024-2026 Apple Inc. +// Copyright © 2024 Apple Inc. #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 { @@ -156,6 +158,14 @@ Simd cos(Simd x) { template Simd erf(Simd x) { // 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. @@ -171,12 +181,19 @@ Simd erf(Simd x) { 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 @@ -196,7 +213,12 @@ Simd sigmoid(Simd 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. @@ -206,8 +228,21 @@ Simd erfinv(Simd a_) { 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 + p = fma(p, t, 1.22150334e-6f); // 0x1.47e512p-20 + p = fma(p, t, 2.84108955e-5f); // 0x1.dca7dep-16 + p = fma(p, t, 3.93552968e-4f); // 0x1.9cab92p-12 + p = fma(p, t, 3.02698812e-3f); // 0x1.8cc0dep-9 + 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 @@ -218,8 +253,22 @@ Simd erfinv(Simd a_) { 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 + p = fma(p, t, 1.22774793e-6f); // 0x1.499232p-20 + p = fma(p, t, 1.12963626e-7f); // 0x1.e52cd2p-24 + p = fma(p, t, -5.61530760e-5f); // -0x1.d70bd0p-15 + p = fma(p, t, -1.47697632e-4f); // -0x1.35be90p-13 + p = fma(p, t, 2.31468678e-3f); // 0x1.2f6400p-9 + 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 @@ -231,17 +280,34 @@ Simd erfinv(Simd a_) { 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 1e1463b1e1..032508be24 100644 --- a/mlx/backend/cpu/simd/type.h +++ b/mlx/backend/cpu/simd/type.h @@ -2,10 +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 2b5c474de5..59b393c8ab 100644 --- a/mlx/backend/cpu/softmax.cpp +++ b/mlx/backend/cpu/softmax.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023-2024 Apple Inc. #include #include @@ -6,7 +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" @@ -17,8 +19,11 @@ namespace { using namespace mlx::core::simd; +#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); @@ -102,6 +107,7 @@ void softmax_row(const T* in_ptr, T* out_ptr, int M) { } 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); @@ -113,6 +119,11 @@ 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 @@ -122,7 +133,12 @@ void softmax(const array& in, array& out, Stream stream) { 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) { @@ -130,24 +146,110 @@ void softmax(const array& in, array& out, Stream stream) { 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; + 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; + } +#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)); + current_in_ptr++; + } + // Compute the normalizer and the exponentials + Simd vnormalizer(0.0); + current_out_ptr = out_ptr; + current_in_ptr = in_ptr; + s = M; + while (s >= N) { + Simd vexp = load(current_in_ptr); + vexp = exp(vexp - maximum); + if constexpr (same_t) { + store(current_out_ptr, vexp); +#else for (int i = row_start; i < row_end; i++) { softmax_row(row_in, row_out, M); row_in += M; row_out += M; +#endif // MLX_USE_HIGHWAY_KERNELS } +#if !defined(MLX_USE_HIGHWAY_KERNELS) + vnormalizer = vnormalizer + vexp; + current_in_ptr += N; + current_out_ptr += N; + s -= N; +#else }); }); } 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 + } +#if !defined(MLX_USE_HIGHWAY_KERNELS) + AccT normalizer = sum(vnormalizer); + while (s-- > 0) { + AccT _exp = std::exp(*current_in_ptr - maximum); + if constexpr (same_t) { + *current_out_ptr = _exp; + } + normalizer += _exp; + current_in_ptr++; + current_out_ptr++; + } + 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++; } + } + }); +#else }); } +#endif // MLX_USE_HIGHWAY_KERNELS } } // namespace diff --git a/mlx/backend/cpu/unary.h b/mlx/backend/cpu/unary.h index 69289a75a6..6707165019 100644 --- a/mlx/backend/cpu/unary.h +++ b/mlx/backend/cpu/unary.h @@ -1,11 +1,13 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023 Apple Inc. #pragma once #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" @@ -19,6 +21,7 @@ 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) { @@ -37,6 +40,7 @@ void unary_op_contiguous_chunk(const T* src, U* dst, size_t size) { } } +#endif // MLX_USE_HIGHWAY_KERNELS template void unary_op(const array& a, array& out, Op) { const T* src = a.data(); @@ -44,6 +48,14 @@ 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(); @@ -63,14 +75,38 @@ void unary_op(const array& a, array& out, Op) { } 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 size_t num_iterations = a.size() / inner_shape; @@ -108,6 +144,7 @@ void unary_op(const array& a, array& out, Op) { 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 f8718acfa1..16fb8fd00f 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -1,4 +1,4 @@ -// Copyright © 2024-2026 Apple Inc. +// Copyright © 2024 Apple Inc. #pragma once @@ -77,7 +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() }; @@ -87,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)); } } @@ -153,12 +163,29 @@ struct ToFP8 { struct FromFP8 { template Simd operator()(Simd x) { +#if !defined(MLX_USE_HIGHWAY_KERNELS) + auto v = Simd(x & 127); + auto sign_bit = Simd((x >> 7) & 1) << 15; + auto u = (v << 7) | (((v + 1) >> 7) << 14) | sign_bit; + Simd out; + if constexpr (simd::max_size >= N) { + auto converted = *(Simd*)(&u); + out = converted * 256.0; + } else { + for (int i = 0; i < N; ++i) { + auto converted = *(float16_t*)(&u[i]); + out[i] = converted * 256.0; + } + } + return out; +#else auto v = Simd(x & 127) << 7; auto converted = *(Simd*)(&v); converted = converted * 256.0; auto sign = Simd(x & 128); Simd out = select(sign, -converted, converted); return out; +#endif // MLX_USE_HIGHWAY_KERNELS } float operator()(uint8_t x) { return (*this)(Simd(x)).value; diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index 5bc7161846..97b3e0a5d5 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023-2024 Apple Inc. #include "mlx/primitives.h" #include "mlx/distributed/primitives.h" @@ -34,10 +34,12 @@ 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) if (s.device == Device::cpu && !output_logsumexp) { return false; } +#endif // MLX_USE_HIGHWAY_KERNELS if (force_fused) { throw std::invalid_argument( "[scaled_dot_product_attention] force_fused=True but no fused " @@ -186,23 +188,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 f7e425af9a..730dc4c7ef 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1,4 +1,4 @@ -// Copyright © 2024-2026 Apple Inc. +// Copyright © 2024 Apple Inc. #include #include @@ -48,7 +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; @@ -79,7 +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; @@ -165,7 +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; @@ -195,7 +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; @@ -229,7 +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; @@ -286,7 +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/mlx/io/load.h b/mlx/io/load.h index 683abd95aa..6b9c9f477b 100644 --- a/mlx/io/load.h +++ b/mlx/io/load.h @@ -1,4 +1,4 @@ -// Copyright © 2023-2026 Apple Inc. +// Copyright © 2023 Apple Inc. #pragma once From f9d4d55a9bba42f9bbc1f271ef603cea8bea9757 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:58:59 +0200 Subject: [PATCH 09/65] Decode E4M3 0x7F and 0xFF as NaN in the quantized fp8 paths MLX 0.32.3 (#4376) decodes the E4M3 codes 0x7F and 0xFF as NaN. #3019's quantized backend decodes them through FP8_LUT, a table computed from the old FromFP8, which held 480 and -480 there, and its dispatched kernels decoded mxfp8 weights from the bits in the same way. Set the two entries to NaN. In the kernels, keep the bit decode, which is right for every other code, and select NaN for the two codes instead of a gather from the table. A test multiplies with mxfp8 weights and nvfp4 scales that hold both codes, and compares every other output exactly with dequantize, or with the value the codes give. It also multiplies every finite code by an identity matrix, with the weights transposed and not, and compares each output with dequantize. --- mlx/backend/cpu/quantized_highway.cpp | 7 +- mlx/backend/cpu/quantized_highway_backend.cpp | 9 +- tests/ops_tests.cpp | 103 ++++++++++++++++++ 3 files changed, 113 insertions(+), 6 deletions(-) diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 51b6543bb2..6eb0add3e1 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -869,6 +869,7 @@ hn::Vec load_fp8_weight_values( 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); @@ -878,9 +879,13 @@ hn::Vec load_fp8_weight_values( 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))); - return hn::Mul( + 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 diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 82df47b616..527f25d860 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -121,9 +121,8 @@ const static float FP4_LUT[16] = { -6.0f}; // FP8 E4M3 -> float32 lookup table (256 entries, 1KB). -// Precomputed from the FromFP8 decode: strip sign, interpret lower 7 bits -// as float16 mantissa/exponent (<<7), multiply by 256, apply sign. -// Used by FP quantized matmul for O(1) FP8 weight decoding. +// 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, @@ -141,7 +140,7 @@ const static float FP8_LUT[256] = { 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, 480.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, @@ -157,7 +156,7 @@ const static float FP8_LUT[256] = { -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, -480.0f, + -256.0f, -288.0f, -320.0f, -352.0f, -384.0f, -416.0f, -448.0f, -NAN, }; // clang-format on diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 0d2ada0bb0..af943bda17 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4752,3 +4752,106 @@ TEST_CASE("test integer floor_divide and remainder by zero in whole vectors") { } } } + +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()); +} From 7ef5e1af07bdc8476d7db39feb51dff4490ee0c8 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:22:38 +0200 Subject: [PATCH 10/65] Compile #3019's new CPU sources only with Highway, and drop the GCD pool #3019's new sources and its thread pool were compiled in every CPU build, macOS included, where a GCD pool drove parallel_for. Wrap each new library source in MLX_USE_HIGHWAY_KERNELS, except #3019's MSVC-only dispatch shims, so that a build system which compiles every file it finds (SwiftPM) builds them only with the macro; in CMake, build the pool's directory only with Highway; and keep one pool: the std::thread pool Linux builds use. The pool's own test builds only where the pool does. --- mlx/backend/cpu/CMakeLists.txt | 6 +- mlx/backend/cpu/norms.cpp | 2 + mlx/backend/cpu/norms_highway.cpp | 2 + mlx/backend/cpu/quantized_highway.cpp | 2 + mlx/backend/cpu/rope.cpp | 2 + mlx/backend/cpu/rope_highway.cpp | 2 + mlx/backend/cpu/sdpa.cpp | 2 + mlx/backend/cpu/sdpa_highway.cpp | 2 + mlx/backend/cpu/threading/CMakeLists.txt | 25 ++----- .../cpu/threading/accelerate/thread_pool.h | 33 ---------- .../cpu/threading/accelerate/thread_pool.mm | 65 ------------------- mlx/backend/cpu/threading/common.cpp | 2 + .../cpu/threading/openblas/thread_pool.cpp | 2 + tests/CMakeLists.txt | 6 +- 14 files changed, 30 insertions(+), 123 deletions(-) delete mode 100644 mlx/backend/cpu/threading/accelerate/thread_pool.h delete mode 100644 mlx/backend/cpu/threading/accelerate/thread_pool.mm diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index c12ac55da8..4340e03d0f 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -153,6 +153,9 @@ if(MLX_ENABLE_X86_SIMD) ${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 @@ -230,6 +233,3 @@ else() target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp ${CMAKE_CURRENT_SOURCE_DIR}/jit_compiler.cpp) endif() - -# Include threading backend (platform-specific implementation) -add_subdirectory(threading) diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp index 74b12ac8d3..e5bb2bc87b 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include #include @@ -801,3 +802,4 @@ void LayerNormVJP::eval_cpu( } } // 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 index 49b13332c9..495d12c95d 100644 --- a/mlx/backend/cpu/norms_highway.cpp +++ b/mlx/backend/cpu/norms_highway.cpp @@ -1,4 +1,5 @@ // 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 @@ -687,3 +688,4 @@ void layer_norm_highway_bfloat16( } // namespace mlx::core::fast #endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 6eb0add3e1..85e368e15d 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -1,4 +1,5 @@ // 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 @@ -1665,3 +1666,4 @@ void fp_qmm_t_highway( } // namespace mlx::core #endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp index 76f95a459d..e10ec0c0e4 100644 --- a/mlx/backend/cpu/rope.cpp +++ b/mlx/backend/cpu/rope.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include #include @@ -563,3 +564,4 @@ void RoPE::eval_cpu( } } // 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 index 195fd9bb34..0a1f8c3a07 100644 --- a/mlx/backend/cpu/rope_highway.cpp +++ b/mlx/backend/cpu/rope_highway.cpp @@ -1,4 +1,5 @@ // 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 @@ -355,3 +356,4 @@ int rope_non_traditional_highway_reverse( } // namespace mlx::core::fast #endif // HWY_ONCE +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp index abd124a6a0..c5704e3f0c 100644 --- a/mlx/backend/cpu/sdpa.cpp +++ b/mlx/backend/cpu/sdpa.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include #include @@ -1007,3 +1008,4 @@ void ScaledDotProductAttention::eval_cpu( } } // 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 index 54beb19cc7..35a813a321 100644 --- a/mlx/backend/cpu/sdpa_highway.cpp +++ b/mlx/backend/cpu/sdpa_highway.cpp @@ -1,4 +1,5 @@ // 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 @@ -577,3 +578,4 @@ void sdpa_highway( } // namespace mlx::core::fast #endif +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/threading/CMakeLists.txt b/mlx/backend/cpu/threading/CMakeLists.txt index 5a313d5cfc..95f3d68a15 100644 --- a/mlx/backend/cpu/threading/CMakeLists.txt +++ b/mlx/backend/cpu/threading/CMakeLists.txt @@ -1,21 +1,4 @@ -# Threading backend selection -# -# Uses platform-aligned thread pools: - macOS: Grand Central Dispatch (GCD) - -# Linux/Windows: persistent threading with optional OpenBLAS coordination - -set(THREADING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/common.cpp) - -# Select platform-specific implementation -if(APPLE) - message(STATUS "Threading: Using Accelerate/GCD for macOS") - list(APPEND THREADING_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/accelerate/thread_pool.mm) - target_sources(mlx PRIVATE ${THREADING_SOURCES}) - target_compile_definitions(mlx PRIVATE MLX_THREADING_ACCELERATE) -else() - message(STATUS "Threading: Using persistent CPU threading") - list(APPEND THREADING_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/openblas/thread_pool.cpp) - target_sources(mlx PRIVATE ${THREADING_SOURCES}) - target_compile_definitions(mlx PRIVATE MLX_THREADING_OPENBLAS) -endif() +# 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}/openblas/thread_pool.cpp) diff --git a/mlx/backend/cpu/threading/accelerate/thread_pool.h b/mlx/backend/cpu/threading/accelerate/thread_pool.h deleted file mode 100644 index 50fb8ba079..0000000000 --- a/mlx/backend/cpu/threading/accelerate/thread_pool.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2026 Apple Inc. - -#pragma once - -#include "mlx/backend/cpu/threading/base.h" - -namespace mlx::core::cpu { - -/** - * macOS thread pool implementation using Grand Central Dispatch (GCD). - * - * GCD is a system-wide thread pool managed by the macOS kernel. - * Benefits: - * - No thread management overhead in userspace - * - Automatic thread count optimization - * - Integration with system scheduler - * - No conflicts with Accelerate framework - */ -class AccelerateThreadPool : public ThreadPoolBackend { - public: - AccelerateThreadPool(); - ~AccelerateThreadPool() override = default; - - void parallel_for(int n_threads, std::function f) - override; - - int max_threads() const override; - - private: - int max_threads_; -}; - -} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/accelerate/thread_pool.mm b/mlx/backend/cpu/threading/accelerate/thread_pool.mm deleted file mode 100644 index bca18f583c..0000000000 --- a/mlx/backend/cpu/threading/accelerate/thread_pool.mm +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright © 2026 Apple Inc. - -#include "mlx/backend/cpu/threading/accelerate/thread_pool.h" - -#include -#include -#include -#include - -namespace mlx::core::cpu { - -AccelerateThreadPool::AccelerateThreadPool() - : max_threads_(std::thread::hardware_concurrency()) {} - -void AccelerateThreadPool::parallel_for( - int n_threads, - std::function f) { - if (n_threads <= 1) { - f(0, 1); - return; - } - - // Clamp to max_threads - n_threads = std::min(n_threads, max_threads_); - - // Use GCD's dispatch_apply for parallel execution. - // This uses the system-wide thread pool managed by the kernel. - // Capture any exception from worker blocks since GCD blocks cannot - // propagate C++ exceptions (they would std::terminate). - // Use heap-allocated state because __block storage copies non-copyable types. - struct ExState { - std::exception_ptr eptr{nullptr}; - std::atomic taken{false}; - }; - auto ex = std::make_shared(); - - dispatch_apply( - n_threads, - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), - ^(size_t i) { - try { - f(static_cast(i), n_threads); - } catch (...) { - bool expected = false; - if (ex->taken.compare_exchange_strong(expected, true)) { - ex->eptr = std::current_exception(); - } - } - }); - - if (ex->eptr) { - std::rethrow_exception(ex->eptr); - } -} - -int AccelerateThreadPool::max_threads() const { - return max_threads_; -} - -// Factory function implementation -std::unique_ptr create_thread_pool_backend() { - return std::make_unique(); -} - -} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/threading/common.cpp b/mlx/backend/cpu/threading/common.cpp index 1f6452bb34..2fac3df5e6 100644 --- a/mlx/backend/cpu/threading/common.cpp +++ b/mlx/backend/cpu/threading/common.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/threading/common.h" @@ -28,3 +29,4 @@ int ThreadPool::max_threads() const { } } // namespace mlx::core::cpu +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp index a3804a5938..76aaa8ab57 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/threading/openblas/thread_pool.h" @@ -360,3 +361,4 @@ std::unique_ptr create_thread_pool_backend() { } } // namespace mlx::core::cpu +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 13c1f6ac03..35c9ebc795 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -46,9 +46,13 @@ target_sources( utils_tests.cpp vmap_tests.cpp linalg_tests.cpp - thread_pool_tests.cpp ${GPU_TEST_SOURCES}) +if(MLX_ENABLE_X86_SIMD) + # The CPU thread pool exists only in builds with Highway kernels. + target_sources(tests PRIVATE thread_pool_tests.cpp) +endif() + target_link_libraries(tests PRIVATE mlx doctest) target_compile_options(tests PRIVATE ${SANITIZER_COMPILE_FLAGS}) target_link_options(tests PRIVATE ${SANITIZER_LINK_FLAGS}) From 9c7e45006a54d7b11216ce3132b3a3382b83c406 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:45:47 +0200 Subject: [PATCH 11/65] Name the CMake option MLX_USE_HIGHWAY, on for Linux x86-64 MLX_ENABLE_X86_SIMD stays as an alias on a fresh configure. The default is on for Linux x86-64 only: the kernels are tested there, and not yet on Windows or Intel macOS. --- CMakeLists.txt | 20 ++++++++++++++------ mlx.pc.in | 2 +- mlx/backend/cpu/CMakeLists.txt | 8 ++++---- tests/CMakeLists.txt | 2 +- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d1c6180759..0c2bed188b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,14 +42,22 @@ 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) -if(MLX_BUILD_CPU AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") - set(_X86_SIMD_DEFAULT ON) +# Highway SIMD kernels for the CPU backend (runtime-dispatched per target). On +# by default for Linux x86-64. MLX_ENABLE_X86_SIMD, the name in +# ml-explore/mlx#3019, is accepted as an alias. +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(_X86_SIMD_DEFAULT OFF) + set(_MLX_USE_HIGHWAY_DEFAULT OFF) +endif() +if(DEFINED MLX_ENABLE_X86_SIMD) + set(_MLX_USE_HIGHWAY_DEFAULT ${MLX_ENABLE_X86_SIMD}) endif() -option(MLX_ENABLE_X86_SIMD - "Enable runtime-dispatched x86 CPU SIMD kernels via Highway" - ${_X86_SIMD_DEFAULT}) +option(MLX_USE_HIGHWAY "Build the CPU backend's Highway SIMD kernels" + ${_MLX_USE_HIGHWAY_DEFAULT}) +set(MLX_ENABLE_X86_SIMD ${MLX_USE_HIGHWAY}) set(MLX_HIGHWAY_SOURCE_DIR "" CACHE PATH "Path to a local Highway source checkout") diff --git a/mlx.pc.in b/mlx.pc.in index 9ac50b3d17..df82f29388 100644 --- a/mlx.pc.in +++ b/mlx.pc.in @@ -11,7 +11,7 @@ @PACKAGE_INIT@ -if (@MLX_BUILD_CPU@ AND @MLX_ENABLE_X86_SIMD@) +if (@MLX_BUILD_CPU@ AND @MLX_USE_HIGHWAY@) include(CMakeFindDependencyMacro) find_dependency(hwy CONFIG PATHS "${PACKAGE_PREFIX_DIR}" NO_DEFAULT_PATH) endif() diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 4340e03d0f..c1d5b244f0 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -8,9 +8,9 @@ endif() set(MLX_HIGHWAY_INCLUDE_DIR "") -if(MLX_ENABLE_X86_SIMD) +if(MLX_USE_HIGHWAY) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") - message(FATAL_ERROR "MLX_ENABLE_X86_SIMD requires an x86 target") + message(FATAL_ERROR "MLX_USE_HIGHWAY requires an x86 target") endif() set(HWY_ENABLE_CONTRIB @@ -42,7 +42,7 @@ if(MLX_ENABLE_X86_SIMD) set(MLX_HIGHWAY_INCLUDE_DIR ${highway_SOURCE_DIR}) endif() if(NOT TARGET hwy) - message(FATAL_ERROR "MLX_ENABLE_X86_SIMD requires Highway target hwy") + message(FATAL_ERROR "MLX_USE_HIGHWAY requires Highway target hwy") endif() if(NOT TARGET hwy::hwy) add_library(hwy::hwy ALIAS hwy) @@ -139,7 +139,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/eval.cpp ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) -if(MLX_ENABLE_X86_SIMD) +if(MLX_USE_HIGHWAY) # quantized.cpp's Highway counterpart (quantized.cpp compiles to nothing # here). target_sources( diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 35c9ebc795..420ba23679 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -48,7 +48,7 @@ target_sources( linalg_tests.cpp ${GPU_TEST_SOURCES}) -if(MLX_ENABLE_X86_SIMD) +if(MLX_USE_HIGHWAY) # The CPU thread pool exists only in builds with Highway kernels. target_sources(tests PRIVATE thread_pool_tests.cpp) endif() From a51c0dea57edbf633e089845490b612739bc7907 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:56:05 +0200 Subject: [PATCH 12/65] Keep 3, 5 and 6-bit weights off #3019's M >= 32 dequantize path The dequantize-then-SGEMM path for M >= 32 reads 32 / bits values per word, which is wrong for 3, 5 and 6 bits: MLX packs those as a byte stream, and the result was garbage (relative error 1.3 to 2.2). Keep it for 2, 4 and 8 bits. --- mlx/backend/cpu/quantized_highway_backend.cpp | 11 ++- tests/CMakeLists.txt | 1 + tests/highway_quantized_tests.cpp | 95 +++++++++++++++++++ 3 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 tests/highway_quantized_tests.cpp diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 527f25d860..fd1d10c6d2 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -1179,9 +1179,14 @@ void _qmm_dispatch_transpose( // 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. - if (M >= QMM_BLAS_M_THRESHOLD) { - _qmm_t_blas(result, x, w, scales, biases, M, N, K); - return; + // _qmm_t_blas's dequantizer reads 32 / bits values per uint32 word, which + // is how MLX packs 2, 4 and 8 bits. 3, 5 and 6 bits are packed as a byte + // stream, so they take the row kernels below at every M. + 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) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 420ba23679..5c28b1a9aa 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -51,6 +51,7 @@ target_sources( if(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) endif() target_link_libraries(tests PRIVATE mlx doctest) diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp new file mode 100644 index 0000000000..dccc6ecab4 --- /dev/null +++ b/tests/highway_quantized_tests.cpp @@ -0,0 +1,95 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +// Every |got - reference| is at most c * eps32 * sum_k |a_ik b_kj|. The +// reference and the magnitude are computed in float64 by MLX's own ops on the +// CPU. That makes an fp32 kernel's rounding bound rigorous for any summation +// order with c = K + 2, while an index or precision bug exceeds it. +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(); +} + +// The same bound for an affine quantized matmul against its dequantized +// weights. The kernels compute s * sum(x * q) + b * sum(x) per group, so their +// rounding scales with sum |x| * (|s| * q + |b|), which exceeds sum |x * w| +// where s * q and b nearly cancel. dequantize() with |s| and |b| gives +// |s| * q + |b|. +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); +} From 607608cb16f29a4ee4adc39cf14a3e5ec1ce11ec Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:00:28 +0200 Subject: [PATCH 13/65] Round QQMatmul's simulated activations as upstream does QQMatmul's simulated activation quantization rounded the mxfp block scale to nearest, saturating a block's largest elements, and broke FP4 ties toward the first table entry. Use upstream's to_fp8_e8m0_round_up (#4353) and to_fp4_e2m1 (round half to even) again. --- mlx/backend/cpu/quantized_highway_backend.cpp | 77 +++++++++++++++---- tests/highway_quantized_tests.cpp | 49 ++++++++++++ 2 files changed, 109 insertions(+), 17 deletions(-) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index fd1d10c6d2..d44b8135f4 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -2237,6 +2237,59 @@ void fp_bs_qmm_dispatch( } } +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 @@ -2273,13 +2326,11 @@ void quantize_dequantize_fp( uint8_t scale_fp8 = to_fp8(raw_scale * scale_encode); scale = from_fp8(scale_fp8) / scale_encode; } else { - // mxfp8: fp8_e8m0 scale (pure exponent, 2^round(log2(x))) - if (raw_scale == 0.0f) { - scale = 1.0f; // 2^0 when all values are zero - } else { - float exp = std::round(std::log2(raw_scale)); - scale = std::pow(2.0f, exp); - } + // 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) { @@ -2295,16 +2346,8 @@ void quantize_dequantize_fp( // 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; - int best_idx = 0; - float best_dist = std::abs(normalized - FP4_LUT[0]); - for (int j = 1; j < 16; j++) { - float dist = std::abs(normalized - FP4_LUT[j]); - if (dist < best_dist) { - best_dist = dist; - best_idx = j; - } - } - gp[i] = static_cast(FP4_LUT[best_idx] * 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 diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp index dccc6ecab4..b44183834d 100644 --- a/tests/highway_quantized_tests.cpp +++ b/tests/highway_quantized_tests.cpp @@ -93,3 +93,52 @@ TEST_CASE("highway gather_qmm merges experts without the byte-packing bug") { auto reference = matmul(x, transpose(take(w_hat, experts, 0), {0, 2, 1})); CHECK(relative_error(y, reference) < 1e-5f); } + +namespace { + +// One group of `values` through qqmm against a quantized identity, which +// returns the activations exactly as QQMatmul quantized and dequantized them. +// The identity quantizes exactly: mxfp4 stores 1 as 4 with scale 2^-2, mxfp8 as +// 256 with scale 2^-8. +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 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: a nearest E8M0 scale of 1 would saturate the block's + // largest element to 448. Rounding the scale up to 2 keeps it: 582.4 / 2 = + // 291.2, which E4M3 rounds to 288, so the element 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); +} From bf8578942a97bf744b4f1f093fda36452610995b Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:14:23 +0200 Subject: [PATCH 14/65] Send attention the native CPU kernel cannot hold to the fallback #3019's native CPU SDPA indexes values and output with the query's head dimension, keeps queries in a float[256] buffer, and implements float32, float16 and bfloat16 only. MLA-style shapes came out wrong, and a head dimension above 256 would overflow the buffer. Let use_fallback compose those shapes and the other dtypes, and refuse them in eval_cpu. --- mlx/backend/cpu/sdpa.cpp | 6 +++ mlx/backend/no_gpu/primitives.cpp | 8 ++- tests/CMakeLists.txt | 1 + tests/highway_kernel_tests.cpp | 81 +++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 tests/highway_kernel_tests.cpp diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp index c5704e3f0c..5332fd5447 100644 --- a/mlx/backend/cpu/sdpa.cpp +++ b/mlx/backend/cpu/sdpa.cpp @@ -770,6 +770,12 @@ void ScaledDotProductAttention::eval_cpu( "[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) { + throw std::invalid_argument( + "[ScaledDotProductAttention::eval_cpu] The CPU kernel needs one head " + "dimension of at most 256 for queries, keys and values. 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) diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index 97b3e0a5d5..9f93b0d8d5 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -36,7 +36,13 @@ bool fast::ScaledDotProductAttention::use_fallback( Stream s) { #if defined(MLX_USE_HIGHWAY_KERNELS) // Use native CPU kernel for inference (handles causal, array mask, sinks) - if (s.device == Device::cpu && !output_logsumexp) { + // The native CPU kernel takes float32, float16 and bfloat16, and one head + // dimension of at most 256 (its stack buffers) for queries, keys and values. + // Everything else composes. + 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) { return false; } #endif // MLX_USE_HIGHWAY_KERNELS diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5c28b1a9aa..3d0772cbde 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -52,6 +52,7 @@ if(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) endif() target_link_libraries(tests PRIVATE mlx doctest) diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp new file mode 100644 index 0000000000..9032aa1e40 --- /dev/null +++ b/tests/highway_kernel_tests.cpp @@ -0,0 +1,81 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +// Every |got - reference| is at most c * eps32 * sum_k |a_ik b_kj|. The +// reference and the magnitude are computed in float64 by MLX's own ops on the +// CPU. That makes an fp32 kernel's rounding bound rigorous for any summation +// order with c = K + 2, while an index or precision bug exceeds it. +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); + } +} From 5ccb3bffa637b9aa390459618e44d64a0b1c95dc Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:24:05 +0200 Subject: [PATCH 15/65] Compute float64 elementwise math in double in the Highway facade The facade's lane maps called libm in float for every lane type, so float64 results of the functions they cover were rounded to float: the inverse trigonometric and hyperbolic functions, tan, sinh, cosh, tanh, the logarithms, expm1, pow, atan2 and remainder. Compute in double for double lanes. --- mlx/backend/cpu/simd/highway_simd.h | 27 +++++++------ tests/highway_kernel_tests.cpp | 60 +++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 11 deletions(-) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index b8063bd97b..b63ff54cff 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -394,13 +394,17 @@ struct Simd { 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]))); + out[i] = static_cast(fn(static_cast>(in[i]))); } return Simd::load(out); } @@ -414,7 +418,8 @@ Simd map_binary(Simd x, Simd y, Fn fn) { 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]))); + fn(static_cast>(in_x[i]), + static_cast>(in_y[i]))); } return Simd::load(out); } @@ -830,8 +835,8 @@ inline Simd remainder(Simd a, Simd b) { return r; }); } else { - return highway_detail::map_binary(a, b, [](float x, float y) { - float r = std::fmod(x, y); + 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; } @@ -856,14 +861,14 @@ inline Simd pow(Simd base, Simd exp) { }); } else { return highway_detail::map_binary( - base, exp, [](float x, float y) { return std::pow(x, y); }); + 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, [](float x, float y) { return std::atan2(x, y); }); + a, b, [](auto x, auto y) { return std::atan2(x, y); }); } template = 0> @@ -941,11 +946,11 @@ 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, [](float v) { return static_cast(std::std_name(v)); }); \ +#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) diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 9032aa1e40..dcfd5546bf 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -79,3 +79,63 @@ TEST_CASE("highway sdpa declines shapes and types its kernel cannot hold") { 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); + } +} From 10e601eea0f5c984c094ad7974d6e3e13759bf87 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:33:24 +0200 Subject: [PATCH 16/65] Return 0 for integer pow with a negative exponent in the Highway facade The facade's integer pow looped forever on a negative exponent. Return 0, as base_simd does since upstream #4100. --- mlx/backend/cpu/simd/highway_simd.h | 5 +++++ tests/highway_kernel_tests.cpp | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index b63ff54cff..6c8028c465 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -850,6 +850,11 @@ 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) { T result = 1; + if constexpr (std::is_signed_v) { + if (y < 0) { + return T(0); + } + } while (y) { if (y & 1) { result = static_cast(result * x); diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index dcfd5546bf..5df959ee4b 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -139,3 +139,23 @@ TEST_CASE("highway float64 elementwise math computes in double") { CHECK(slice(remainders, {i}, {i + 1}).item() == r); } } + +TEST_CASE("highway integer power with a negative exponent") { + // base_simd.h's rule (hwy/base, lines 249-267): 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]); + } +} From 5410adc27ee4e172fdba8723c7c52b12b9bf3799 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:36:59 +0200 Subject: [PATCH 17/65] Keep bf16 and fp16 reduction partials in float until the end #3019's parallel reductions rounded each thread's partial to the output dtype before combining them, so an fp16 sum depended on the thread count: 2^18 + 3 elements of 2^-4 and one -2^14 summed to 0 with 8 threads, not 0.1875. Keep the partials in the accumulator type and round once. MLX widens bf16 sums to float before this code, so the bf16 test passes without the change; fp16 sums it widens only where its SIMD width is 1, which under Highway it is not. --- mlx/backend/cpu/reduce.cpp | 72 ++++++++++++++++++---------------- tests/highway_kernel_tests.cpp | 23 +++++++++++ 2 files changed, 62 insertions(+), 33 deletions(-) diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index 793041168b..bcf3bd2f90 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -126,51 +126,53 @@ struct AccumType { }; #endif // MLX_USE_HIGHWAY_KERNELS +#if defined(MLX_USE_HIGHWAY_KERNELS) +template +A contiguous_accumulate(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 +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(const T* x, U* accumulator, int size, Op op, U init) { -#if !defined(MLX_USE_HIGHWAY_KERNELS) constexpr int N = std::min(simd::max_size, simd::max_size); simd::Simd accumulator_v(init); -#else - using A = typename AccumType::type; - constexpr int N = std::min(simd::max_size, simd::max_size); - - simd::Simd accumulator_v(static_cast(init)); -#endif // MLX_USE_HIGHWAY_KERNELS while (size >= N) { -#if !defined(MLX_USE_HIGHWAY_KERNELS) accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); -#else - accumulator_v = op(accumulator_v, simd::Simd(simd::load(x))); -#endif // MLX_USE_HIGHWAY_KERNELS x += N; size -= N; } -#if !defined(MLX_USE_HIGHWAY_KERNELS) *accumulator = op(*accumulator, op(accumulator_v)); -#else - - A simd_sum = op(accumulator_v); // horizontal reduction - A scalar_acc = op(static_cast(*accumulator), simd_sum); - -#endif // MLX_USE_HIGHWAY_KERNELS while (size-- > 0) { -#if !defined(MLX_USE_HIGHWAY_KERNELS) *accumulator = op(*accumulator, *x); -#else - scalar_acc = op(scalar_acc, static_cast(*x)); -#endif // MLX_USE_HIGHWAY_KERNELS x++; } -#if defined(MLX_USE_HIGHWAY_KERNELS) - *accumulator = static_cast(scalar_acc); -#endif // MLX_USE_HIGHWAY_KERNELS } +#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); @@ -182,9 +184,9 @@ U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { } // Each thread computes a partial reduction. Keep each partial on its own - // cache line to avoid false sharing while preserving U's alignment/lifetime. + // cache line to avoid false sharing while preserving A's alignment/lifetime. struct alignas(64) Partial { - U value; + A value; }; std::vector partials(n_threads); @@ -193,21 +195,25 @@ U parallel_contiguous_reduce(const T* x, size_t size, Op op, U init) { size_t start = chunk * tid; size_t end = std::min(start + chunk, size); - U* partial = &partials[tid].value; - *partial = init; + A* partial = &partials[tid].value; + *partial = static_cast(init); if (start < end) { - contiguous_reduce( - x + start, partial, static_cast(end - start), op, init); + *partial = contiguous_accumulate( + x + start, + static_cast(end - start), + op, + static_cast(init), + static_cast(init)); } }); // Final reduction of partial results - U result = init; + A result = static_cast(init); for (int i = 0; i < n_threads; ++i) { result = op(result, partials[i].value); } - return result; + return static_cast(result); } #endif // MLX_USE_HIGHWAY_KERNELS diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 5df959ee4b..7c5d49f83e 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -159,3 +159,26 @@ TEST_CASE("highway integer power with a negative exponent") { 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 bf16 sum does not depend on the thread count") { + // 2^20 + 3 ones, then -2^20: the sum is exactly 3. Every thread's partial is + // exact in float; rounded to bf16 before they are combined, the total is + // never 3 for any pool of 2 to 64 threads (0 with 2, 4, 8, 16 or 32, 4096 + // with 6, -8192 with 12). A plain count of ones is no test: at many pool + // sizes each partial happens to be exact in bf16. item on a bf16 array + // would read four bytes of a two-byte buffer, so widen first. + auto x = concatenate( + {ones({(1 << 20) + 3}, bfloat16), full({1}, -1048576.0f, bfloat16)}); + CHECK(astype(sum(x), float32).item() == 3.0f); +} From cacd7504fdf64a13f0dbd0a2a82a4ddbc9c7bf55 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:46:54 +0200 Subject: [PATCH 18/65] Round once in the Highway facade's fma, on every target Every elementwise kernel runs the facade at Highway's static target, SSE2 on x86-64, where MulAdd is a multiply and an add. fma promises one rounding, as base_simd's std::fma gives, and MLX's polynomials rely on it: erfinv lost most of its bits near |x| = 1 (64.7 units in the last place at 0.99983, against at most 2.1 rounded once). Without native FMA, compute each lane with std::fma. --- mlx/backend/cpu/simd/highway_simd.h | 23 ++++++++++++++++++++++ tests/highway_kernel_tests.cpp | 30 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 6c8028c465..5b07774e07 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -812,9 +812,32 @@ inline Simd fma(Simd x, Simd y, U z) { 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, and fma promises one + // rounding (base_simd.h's std::fma): MLX's polynomials rely on it. This + // is the static target's path, SSE2 on x86-64, which runs every + // elementwise kernel; glibc's fma uses the CPU's FMA where it has one. + 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 } } diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 7c5d49f83e..19cfd3fccb 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -182,3 +182,33 @@ TEST_CASE("highway bf16 sum does not depend on the thread count") { {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") { + // MLX's erfinv computes t = fma(a, -a, 1). Where Highway's MulAdd rounds a * + // a first, near |a| = 1 the result keeps few of its bits: 64 units in the + // last place at 0.99983, where one rounding (the scalar code's std::fma) + // keeps the worst over this range to about 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); +} From ec8e5e306ef3b3636b351ecf230013d1a17b7d5c Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 22:01:52 +0200 Subject: [PATCH 19/65] Keep float16 inf and NaN through Highway's conversions Highway emulates float16 -> float32 where a target has no conversion instruction, which on x86-64 includes the facade's static target, SSE2, and reads exponent 31 as finite there. float16 inf came out as 65536: sin(inf) gave 0.691895, which is sin(65536) in float16, and inf - inf gave 0. NaN came out as a number: NaN - NaN gave 0, and isnan(NaN) false. Give those lanes float32's inf or a quiet NaN, in the facade and in the loads the dispatched kernels share. --- mlx/backend/cpu/highway_utils.h | 32 +++++++++++++++++++++++--- mlx/backend/cpu/simd/highway_simd.h | 32 +++++++++++++++++++++++++- tests/highway_kernel_tests.cpp | 35 +++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 4 deletions(-) diff --git a/mlx/backend/cpu/highway_utils.h b/mlx/backend/cpu/highway_utils.h index d096bc1772..0384603768 100644 --- a/mlx/backend/cpu/highway_utils.h +++ b/mlx/backend/cpu/highway_utils.h @@ -15,13 +15,39 @@ namespace HWY_NAMESPACE { namespace hn = hwy::HWY_NAMESPACE; +// Highway emulates float16 -> float32 where a target has no conversion +// instruction (x86 before AVX2, EMU128, SCALAR), and reads exponent 31 as a +// finite exponent there: inf became 65536. Lanes with exponent 31 take +// float32's inf, or a quiet NaN with the same payload, as the instructions +// give. simd/highway_simd.h has the same function for the facade. +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 hn::PromoteTo( + return promote_f16( df, hn::LoadU(df16, reinterpret_cast(ptr) + idx)); } else { @@ -77,8 +103,8 @@ void load_interleaved_typed_as_f32( hn::Vec x1h; hn::LoadInterleaved2( df16, reinterpret_cast(ptr) + idx, x0h, x1h); - x0 = hn::PromoteTo(df, x0h); - x1 = hn::PromoteTo(df, x1h); + x0 = promote_f16(df, x0h); + x1 = promote_f16(df, x1h); } else { #if HWY_TARGET == HWY_SCALAR const hn::Rebind dbf16; diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 5b07774e07..538a07bdbb 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -129,6 +129,32 @@ LaneTypeT* lane_ptr(T* ptr) { return reinterpret_cast*>(ptr); } +// Highway emulates float16 -> float32 where a target has no conversion +// instruction (x86 before AVX2, EMU128, SCALAR), and reads exponent 31 as a +// finite exponent there: inf became 65536. Lanes with exponent 31 take +// float32's inf, or a quiet NaN with the same payload, as the instructions +// give. highway_utils.h has the same function for the dispatched kernels. +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); @@ -235,7 +261,11 @@ struct Simd { value = other.value; } else if constexpr ( std::is_same_v && highway_detail::is_half_v) { - value = hn::PromoteTo(D(), other.value); + 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); diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 19cfd3fccb..42ab57b326 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -212,3 +212,38 @@ TEST_CASE("highway facade fma rounds once on every target") { CAPTURE(worst); CHECK(worst <= 8.0); } + +TEST_CASE("highway float16 keeps inf and nan") { + // Highway emulates float16 -> float32 where a target has no conversion + // instruction, and reads exponent 31 as finite there: inf became 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))); + } +} From f2821606af8e8fd97c50883d4d492439b4a9d67c Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:15:07 +0200 Subject: [PATCH 20/65] Decode E4M3 0x7F and 0xFF as NaN under Highway, as MLX 0.32.3 does MLX 0.32.3 (#4376) decodes the E4M3 codes 0x7F and 0xFF as NaN, carrying into an all-ones float16 exponent, and takes the sign from the bits. Under Highway, FromFP8 still decoded them as 480 and -480, as #3019 wrote it. Decode the same bits there, widen to float, then multiply by 256. A test decodes all 256 codes in whole vectors, and 0x7F, 0xFF and 0x80 in the scalar tail, and dequantizes mxfp8 weights and nvfp4 scales that hold both codes. --- mlx/backend/cpu/unary_ops.h | 10 ++--- tests/ops_tests.cpp | 76 +++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 7 deletions(-) diff --git a/mlx/backend/cpu/unary_ops.h b/mlx/backend/cpu/unary_ops.h index 16fb8fd00f..91da4143a6 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -163,10 +163,10 @@ struct ToFP8 { struct FromFP8 { template Simd operator()(Simd x) { -#if !defined(MLX_USE_HIGHWAY_KERNELS) 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); @@ -179,12 +179,8 @@ struct FromFP8 { } return out; #else - auto v = Simd(x & 127) << 7; - auto converted = *(Simd*)(&v); - converted = converted * 256.0; - auto sign = Simd(x & 128); - Simd out = select(sign, -converted, converted); - return out; + auto converted = *(Simd*)(&u); + return Simd(converted) * 256.0f; #endif // MLX_USE_HIGHWAY_KERNELS } float operator()(uint8_t x) { diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index af943bda17..a9d85f4813 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4855,3 +4855,79 @@ TEST_CASE( 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); +} From 97c68ce5d6749ffbfa1d7e245789e8b08ab02246 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 22:20:56 +0200 Subject: [PATCH 21/65] Make #3019's int8 activation path opt-in #3019 rounds quantized matmul activations to int8 per group whenever env::enable_tf32() is true, and MLX defaults that to true; the path takes 4- and 8-bit weights at group size 32 or more, K up to 16384 and fewer than 32 rows. That trades accuracy for speed without being asked. Gate the path on its own switch, mlx::core::cpu::quantized_int8(), off unless MLX_CPU_QUANTIZED_INT8=1 or set_quantized_int8(true). Without it, the Highway path for affine 2-, 4- and 8-bit weights with transposed layout sums in float32. #3019's "token float32" test expected int8-rounded activations. It now checks the exact result, and a second case checks the int8 path with the switch on, where the build has one. Its "token bfloat16" bound assumes float32 sums, which builds without Highway do not do; quantized_float32_accumulation() says which a build does, and the test returns early where it does not. --- mlx/backend/cpu/CMakeLists.txt | 1 + mlx/backend/cpu/precision.cpp | 49 +++++++++++++++++++++++++++ mlx/backend/cpu/precision.h | 31 +++++++++++++++++ mlx/backend/cpu/quantized_highway.cpp | 2 +- mlx/backend/cpu/quantized_highway.h | 5 +-- tests/fast_tests.cpp | 45 ++++++++++++++++++++---- tests/highway_quantized_tests.cpp | 32 +++++++++++++++++ 7 files changed, 156 insertions(+), 9 deletions(-) create mode 100644 mlx/backend/cpu/precision.cpp create mode 100644 mlx/backend/cpu/precision.h diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index c1d5b244f0..1aa57b8b9d 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -122,6 +122,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 diff --git a/mlx/backend/cpu/precision.cpp b/mlx/backend/cpu/precision.cpp new file mode 100644 index 0000000000..c967312789 --- /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; +} +} // 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 +} + +bool quantized_float32_accumulation() { +#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..4475d34d53 --- /dev/null +++ b/mlx/backend/cpu/precision.h @@ -0,0 +1,31 @@ +// 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 per group +// (the fast path of ml-explore/mlx#3019). Off unless MLX_CPU_QUANTIZED_INT8 is +// a nonzero integer at first use, or until set_quantized_int8(true). +// Process-wide. +MLX_API bool quantized_int8(); +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(); + +// Whether affine 4- and 8-bit quantized matmul sums bf16 and fp16 activations +// in float32 (the Highway kernels) rather than in their own dtype (the scalar +// _qmm_t, which Highway builds still use for 3, 5 and 6 bits). +MLX_API bool quantized_float32_accumulation(); + +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); +} // namespace detail + +} // namespace mlx::core::cpu diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 85e368e15d..9b4d84d8ee 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -667,7 +667,7 @@ bool QmmTInt8HighwayTyped( int K) { constexpr int INT8_MAX_K = 16384; constexpr int STACK_GROUPS = 128; - if (!env::enable_tf32() || K > INT8_MAX_K) { + if (!cpu::quantized_int8() || K > INT8_MAX_K) { return false; } diff --git a/mlx/backend/cpu/quantized_highway.h b/mlx/backend/cpu/quantized_highway.h index 0b4a4ffc8c..ed9b1d06bb 100644 --- a/mlx/backend/cpu/quantized_highway.h +++ b/mlx/backend/cpu/quantized_highway.h @@ -11,6 +11,7 @@ #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" @@ -166,7 +167,7 @@ bool try_int8_simd_row( if constexpr (!((bits == 4 || bits == 8) && group_size >= 32)) { return false; } else { - if (!env::enable_tf32()) { + if (!cpu::quantized_int8()) { return false; } if (K > INT8_MAX_K) { @@ -255,7 +256,7 @@ bool try_int8_preq_parallel( if constexpr (!((bits == 4 || bits == 8) && group_size >= 32)) { return false; } else { - if (!env::enable_tf32()) { + if (!cpu::quantized_int8()) { return false; } if (K > INT8_MAX_K) { diff --git a/tests/fast_tests.cpp b/tests/fast_tests.cpp index 73093a35da..bfc62c95b0 100644 --- a/tests/fast_tests.cpp +++ b/tests/fast_tests.cpp @@ -8,6 +8,7 @@ #include "doctest/doctest.h" +#include "mlx/backend/cpu/precision.h" #include "mlx/fast.h" #include "mlx/mlx.h" @@ -312,7 +313,7 @@ uint32_t pack_u8x4(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) { (static_cast(v2) << 16) | (static_cast(v3) << 24); } -void check_quantized_matmul_8bit_high_values() { +void check_quantized_matmul_8bit_high_values(bool int8_activations) { constexpr int M = 3; constexpr int N = 72; constexpr int K = 64; @@ -385,6 +386,25 @@ void check_quantized_matmul_8bit_high_values() { 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]; @@ -411,10 +431,8 @@ void check_quantized_matmul_8bit_high_values() { x, w, scale_arr, bias_arr, /* transpose = */ true, group_size, bits); y.eval(); - const float* out = y.data(); - for (int i = 0; i < static_cast(expected.size()); ++i) { - CHECK(std::abs(out[i] - expected[i]) < 2e-4f); - } + auto expected_arr = array(expected.data(), {M, N}, float32); + CHECK(max(abs(subtract(y, expected_arr))).item() < 2e-4f); } template @@ -492,7 +510,17 @@ TEST_CASE("test fast quantized matmul token float32") { 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(); + 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::set_quantized_int8(true); + check_quantized_matmul_8bit_high_values(true); + cpu::set_quantized_int8(false); } TEST_CASE("test fast quantized matmul token float16") { @@ -501,6 +529,11 @@ TEST_CASE("test fast quantized matmul token float16") { } TEST_CASE("test fast quantized matmul token bfloat16") { + if (!cpu::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_quantized_tests.cpp b/tests/highway_quantized_tests.cpp index b44183834d..93cca364cd 100644 --- a/tests/highway_quantized_tests.cpp +++ b/tests/highway_quantized_tests.cpp @@ -142,3 +142,35 @@ TEST_CASE("highway qqmm mxfp8 rounds the block scale up") { auto out = through_qqmm(values, "mxfp8", 8); CHECK(out[0] == 576.0f); } + +#include "mlx/backend/cpu/precision.h" + +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::set_quantized_int8(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)); + cpu::set_quantized_int8(false); +} + +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()); +} From 9cafbdb4559ed97fd613f4287129de40571b2aef Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 22:46:55 +0200 Subject: [PATCH 22/65] Record which Highway target each CPU kernel family ran Tests need to see the target that executed, not the one requested, and whether norms, RoPE or the FP-quantized matmul fell back to code that is not dispatched. Each dispatched kernel records its family and HWY_TARGET; a counter counts to 1 and stops. highway_info also reports the compiled and supported targets, restricts dispatch for tests, and has a counter for the SGEMM column split that a later commit adds. In builds with Highway, RMSNorm, LayerNorm and RoPE threw for float64: their use_fallback is false whatever the dtype, and their kernels implement float32, float16 and bfloat16. Their eval_cpu now composes other dtypes through MLX's fallback, as RMSNormVJP::eval_cpu does, and records it. --- mlx/backend/cpu/CMakeLists.txt | 5 +- mlx/backend/cpu/highway_info.cpp | 90 +++++++++++++++ mlx/backend/cpu/highway_info.h | 66 +++++++++++ mlx/backend/cpu/norms.cpp | 23 ++++ mlx/backend/cpu/norms_highway.cpp | 8 ++ mlx/backend/cpu/quantized_highway.cpp | 9 ++ mlx/backend/cpu/quantized_highway_backend.cpp | 2 + mlx/backend/cpu/rope.cpp | 13 +++ mlx/backend/cpu/rope_highway.cpp | 5 + mlx/backend/cpu/sdpa_highway.cpp | 2 + tests/CMakeLists.txt | 1 + tests/highway_info_tests.cpp | 106 ++++++++++++++++++ 12 files changed, 328 insertions(+), 2 deletions(-) create mode 100644 mlx/backend/cpu/highway_info.cpp create mode 100644 mlx/backend/cpu/highway_info.h create mode 100644 tests/highway_info_tests.cpp diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 1aa57b8b9d..61762313e7 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -142,9 +142,10 @@ target_sources( if(MLX_USE_HIGHWAY) # quantized.cpp's Highway counterpart (quantized.cpp compiles to nothing - # here). + # here), and the Highway kernels' dispatch counters. target_sources( - mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/quantized_highway_backend.cpp) + 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. 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..5ea6af6d05 --- /dev/null +++ b/mlx/backend/cpu/highway_info.h @@ -0,0 +1,66 @@ +// 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); + +// What a family's kernels did since the last reset_stats(). `executed` is the +// OR of every target whose kernel ran. `highway_calls` is 1 once a dispatched +// kernel ran, and `fallback_calls` once an entry point sent a call to code that +// is not dynamically dispatched: both count to 1 and stop, so that recording +// in a row loop writes shared memory only once. +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. MLX_HIGHWAY_RECORD goes inside HWY_NAMESPACE code, where +// HWY_TARGET is the target that code was compiled for. Fully qualified, +// because 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/norms.cpp b/mlx/backend/cpu/norms.cpp index e5bb2bc87b..87235b01a7 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -8,6 +8,7 @@ #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" @@ -466,6 +467,17 @@ void layer_norm_half( 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]; auto& weight = inputs[1]; auto& out = outputs[0]; @@ -616,6 +628,17 @@ void RMSNormVJP::eval_cpu( 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]; auto& weight = inputs[1]; auto& bias = inputs[2]; diff --git a/mlx/backend/cpu/norms_highway.cpp b/mlx/backend/cpu/norms_highway.cpp index 495d12c95d..eeda814a0f 100644 --- a/mlx/backend/cpu/norms_highway.cpp +++ b/mlx/backend/cpu/norms_highway.cpp @@ -8,6 +8,8 @@ #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" @@ -332,6 +334,7 @@ void RmsNormF32( 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); @@ -361,6 +364,7 @@ void RmsNormF16( int rows, float eps, int has_weight) { + MLX_HIGHWAY_RECORD(RmsNorm); RmsNormHalf(x, weight, out, width, rows, eps, has_weight); } @@ -372,6 +376,7 @@ void RmsNormBF16( int rows, float eps, int has_weight) { + MLX_HIGHWAY_RECORD(RmsNorm); RmsNormHalf(x, weight, out, width, rows, eps, has_weight); } @@ -385,6 +390,7 @@ void LayerNormF32( 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, @@ -432,6 +438,7 @@ void LayerNormF16( float eps, int has_weight, int has_bias) { + MLX_HIGHWAY_RECORD(LayerNorm); LayerNormHalf(x, weight, bias, out, width, rows, eps, has_weight, has_bias); } @@ -445,6 +452,7 @@ void LayerNormBF16( float eps, int has_weight, int has_bias) { + MLX_HIGHWAY_RECORD(LayerNorm); LayerNormHalf(x, weight, bias, out, width, rows, eps, has_weight, has_bias); } diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 9b4d84d8ee..9ef26d5106 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -9,6 +9,8 @@ #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" @@ -331,6 +333,7 @@ void QuantizeActivationInt8( 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( @@ -513,6 +516,7 @@ void QmmTInt8Row( int n_start, int n_end, int K) { + MLX_HIGHWAY_RECORD(QmmAffineInt8); switch (dtype) { case QuantizedHighwayDType::Float32: QmmTInt8RowForDType( @@ -670,6 +674,7 @@ bool QmmTInt8HighwayTyped( 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; @@ -1217,6 +1222,7 @@ void FpQmmTHighwayRow( float scale_factor, const float* fp4_lut, const float* fp8_lut) { + MLX_HIGHWAY_RECORD(QmmFp); switch (dtype) { case QuantizedHighwayDType::Float32: FpQmmTHighwayRowForDType( @@ -1280,6 +1286,7 @@ void FpQmmTHighway( float scale_factor, const float* fp4_lut, const float* fp8_lut) { + MLX_HIGHWAY_RECORD(QmmFp); switch (dtype) { case QuantizedHighwayDType::Float32: FpQmmTHighwayForDType( @@ -1336,6 +1343,7 @@ void DequantRow4Bit( 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); } @@ -1346,6 +1354,7 @@ void DequantRow8Bit( 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); } diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index d44b8135f4..95f943823d 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -9,6 +9,7 @@ #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/simd/simd.h" #include "mlx/backend/cpu/threading/common.h" @@ -1857,6 +1858,7 @@ void fp_qmm_dispatch_transpose( 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); } } diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp index e10ec0c0e4..83a07e41ce 100644 --- a/mlx/backend/cpu/rope.cpp +++ b/mlx/backend/cpu/rope.cpp @@ -8,9 +8,11 @@ #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" @@ -419,6 +421,17 @@ void rope_dispatch( 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]; diff --git a/mlx/backend/cpu/rope_highway.cpp b/mlx/backend/cpu/rope_highway.cpp index 0a1f8c3a07..e7f7ad4ed6 100644 --- a/mlx/backend/cpu/rope_highway.cpp +++ b/mlx/backend/cpu/rope_highway.cpp @@ -7,6 +7,7 @@ // 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 @@ -178,6 +179,7 @@ void RopeTraditionalForward( 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); } @@ -190,6 +192,7 @@ void RopeTraditionalReverse( 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); } @@ -202,6 +205,7 @@ void RopeNonTraditionalForward( 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); } @@ -214,6 +218,7 @@ void RopeNonTraditionalReverse( 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); } diff --git a/mlx/backend/cpu/sdpa_highway.cpp b/mlx/backend/cpu/sdpa_highway.cpp index 35a813a321..c015feca72 100644 --- a/mlx/backend/cpu/sdpa_highway.cpp +++ b/mlx/backend/cpu/sdpa_highway.cpp @@ -10,6 +10,7 @@ #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" @@ -410,6 +411,7 @@ void SdpaHighway( bool has_mask, const void* HWY_RESTRICT sinks, bool has_sinks) { + MLX_HIGHWAY_RECORD(Sdpa); switch (dtype) { case SdpaHighwayDType::Float32: SdpaHighwayForDType( diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3d0772cbde..19b0d04fa9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -53,6 +53,7 @@ if(MLX_USE_HIGHWAY) 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) endif() target_link_libraries(tests PRIVATE mlx doctest) diff --git a/tests/highway_info_tests.cpp b/tests/highway_info_tests.cpp new file mode 100644 index 0000000000..9a1eb4afc7 --- /dev/null +++ b/tests/highway_info_tests.cpp @@ -0,0 +1,106 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#include "doctest/doctest.h" + +#include "mlx/mlx.h" + +using namespace mlx::core; + +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/precision.h" + +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(); +} +} // 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") { + 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); + } + hi::set_targets_for_test(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::set_quantized_int8(true); + CHECK( + sum(quantized_matmul(x, q[0], q[1], q[2], true, 64, 4)).item() != + 0.0f); + cpu::set_quantized_int8(false); + 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); + } +} From b695d0fe0c1ba038ced89674481e6cecbfea2e3e Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:12:59 +0200 Subject: [PATCH 23/65] Size the CPU pool to the CPUs the process may use, and harden it - The default size is the physical cores in the process's affinity mask, capped by the cgroup v2 cpu.max quota, so the pool does not oversubscribe a CPU-limited container. MLX_CPU_THREADS overrides it; an invalid value is recorded for the caller to report, and the default is used. threading/config.h exports the resolved settings and the parsers behind them. - OpenBLAS is pinned to one thread whenever the pool runs more than one, even with OPENBLAS_NUM_THREADS set, since cblas.cpp splits SGEMMs across the pool. - An exception on any slot is caught; the pool waits for every slot and rethrows the first. Before, a worker's exception terminated the process, and slot 0's exception unwound while the workers still ran the task. - A parallel_for inside a task runs every slot of its range inline, instead of deadlocking on the dispatch mutex. --- mlx/backend/cpu/threading/CMakeLists.txt | 7 +- mlx/backend/cpu/threading/config.cpp | 218 ++++++++++++++++++ mlx/backend/cpu/threading/config.h | 66 ++++++ .../cpu/threading/openblas/thread_pool.cpp | 132 +++++------ .../cpu/threading/openblas/thread_pool.h | 6 + tests/CMakeLists.txt | 1 + tests/highway_threading_tests.cpp | 193 ++++++++++++++++ 7 files changed, 552 insertions(+), 71 deletions(-) create mode 100644 mlx/backend/cpu/threading/config.cpp create mode 100644 mlx/backend/cpu/threading/config.h create mode 100644 tests/highway_threading_tests.cpp diff --git a/mlx/backend/cpu/threading/CMakeLists.txt b/mlx/backend/cpu/threading/CMakeLists.txt index 95f3d68a15..e7086c6995 100644 --- a/mlx/backend/cpu/threading/CMakeLists.txt +++ b/mlx/backend/cpu/threading/CMakeLists.txt @@ -1,4 +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}/openblas/thread_pool.cpp) +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/config.cpp b/mlx/backend/cpu/threading/config.cpp new file mode 100644 index 0000000000..0c7fdca9e1 --- /dev/null +++ b/mlx/backend/cpu/threading/config.cpp @@ -0,0 +1,218 @@ +// 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 + +// Physical core detection -- AVX2/FMA workloads get no benefit from SMT +// (hyperthreads share the same SIMD execution units, L1/L2 cache, and memory +// bandwidth). Using physical core count avoids over-subscription and reduces +// atomic/mutex contention in the thread pool. Benchmarked: 16 physical cores +// is +5-7% faster than logical core count for quantized LLM inference. +#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 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::optional> sysfs_topology(int cpu) { + const std::string base = + "/sys/devices/system/cpu/cpu" + std::to_string(cpu) + "/topology/"; + std::ifstream core_file(base + "core_id"); + int core = 0; + int package = 0; + if (!(core_file >> core)) { + return std::nullopt; + } + std::ifstream package_file(base + "physical_package_id"); + package_file >> package; + return std::make_pair(package, core); +} + +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(), + sysfs_topology, + 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..9043304123 --- /dev/null +++ b/mlx/backend/cpu/threading/config.h @@ -0,0 +1,66 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "mlx/api.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 vmlx reports the error at model load. + 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 whenever it runs more than one itself). +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 (package, core) pairs 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 tightest cgroup v2 cpu.max from the process's cgroup, named by the "0::" +// line of `self_cgroup` (/proc/self/cgroup's text), up to `root` +// (/sys/fs/cgroup). nullopt without a v2 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); +} // 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 index 76aaa8ab57..1e81c96d0f 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -2,6 +2,8 @@ #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 @@ -64,79 +66,42 @@ static void set_blas_threads(int n) { 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 -// Physical core detection -- AVX2/FMA workloads get no benefit from SMT -// (hyperthreads share the same SIMD execution units, L1/L2 cache, and memory -// bandwidth). Using physical core count avoids over-subscription and reduces -// atomic/mutex contention in the thread pool. Benchmarked: 16 physical cores -// is +5-7% faster than logical core count for quantized LLM inference. -#ifdef _WIN32 -// Windows: already included above for OpenBLAS DLL resolution. -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; -} -#elif defined(__linux__) -#include -#include -#include -static int get_physical_cores() { - // Count unique (physical_package_id, core_id) pairs across all online CPUs. - // This handles multi-socket systems correctly. - std::set> cores; - for (int i = 0; i < 4096; i++) { - std::string base = - "/sys/devices/system/cpu/cpu" + std::to_string(i) + "/topology/"; - std::ifstream cf(base + "core_id"); - if (!cf) - break; - int core_id, pkg_id = 0; - cf >> core_id; - std::ifstream pf(base + "physical_package_id"); - if (pf) - pf >> pkg_id; - cores.insert({pkg_id, core_id}); - } - return static_cast(cores.size()); -} -#else -static int get_physical_cores() { - return 0; // Unknown platform -- caller falls back to hardware_concurrency() +static std::atomic& openblas_pinned_flag() { + static std::atomic flag{false}; + return flag; } -#endif namespace mlx::core::cpu { namespace { int get_default_threads() { - if (const char* e = std::getenv("MLX_CPU_THREADS")) { - int n = std::atoi(e); - if (n > 0) - return n; - } - int physical = get_physical_cores(); - if (physical > 0) - return physical; - return std::max(1, (int)std::thread::hardware_concurrency()); + return thread_config().threads; } + +// Set while this thread runs a slot of some parallel_for. +thread_local bool in_parallel_for = false; } // 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() : max_threads_(std::min(get_default_threads(), MAX_WORKERS + 1)) { // Spawn max_threads_ - 1 workers. The main thread takes slot 0 in @@ -153,14 +118,14 @@ CPUThreadPool::CPUThreadPool() while (ready_.load(std::memory_order_acquire) < n_workers) { MLX_SPIN_PAUSE(); } - // Pin OpenBLAS to single-threaded unless user explicitly overrides via env - // var. This prevents over-subscription (our N threads + OpenBLAS's N threads - // competing for N cores). BLAS ops are still fully parallel because - // cblas.cpp calls cblas_sgemm from within parallel_for workers -- each worker - // runs single-threaded BLAS on its row slice, achieving full core - // utilization without internal BLAS threading. - if (!std::getenv("OPENBLAS_NUM_THREADS")) { + // Look OpenBLAS up at any pool size, so that openblas_present() can answer. + init_blas_funcs(); + // Pin OpenBLAS to one thread whenever this pool runs more than one: cblas.cpp + // splits every large SGEMM across the pool, and a second level of threads + // would oversubscribe the cores. MLX_CPU_THREADS is the one setting. + if (max_threads_ > 1) { set_blas_threads(1); + openblas_pinned_flag().store(blas_set_threads != nullptr); } } @@ -224,7 +189,7 @@ void CPUThreadPool::worker_loop(int worker_id) { if (nth > 0 && started_.load(std::memory_order_relaxed) < nth) { int slot = started_.fetch_add(1, std::memory_order_acq_rel); if (slot < nth) { - (*task_ptr_)(slot, nth); + run_slot(slot, nth); done_.fetch_add(1, std::memory_order_acq_rel); } } @@ -258,7 +223,7 @@ void CPUThreadPool::worker_loop(int worker_id) { int slot = started_.fetch_add(1, std::memory_order_acq_rel); if (slot >= nth) continue; - (*task_ptr_)(slot, nth); + run_slot(slot, nth); done_.fetch_add(1, std::memory_order_acq_rel); } } @@ -273,12 +238,23 @@ void CPUThreadPool::parallel_for( return; } + // A task that calls parallel_for runs the inner range itself, every slot in + // turn: the workers are busy with the outer call, and dispatch_mtx_ is not + // recursive. Callers size per-slot state by n_threads, so each slot runs. + 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_, started_, 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()); @@ -333,7 +309,7 @@ void CPUThreadPool::parallel_for( } // Main thread executes slot 0 - (*task_ptr_)(0, n_threads); + run_slot(0, n_threads); done_.fetch_add(1, std::memory_order_acq_rel); // Wait for workers -- spin then yield @@ -350,6 +326,12 @@ void CPUThreadPool::parallel_for( task_gen_.store(0, std::memory_order_release); task_n_threads_.store(0, std::memory_order_release); task_ptr_ = nullptr; + + if (first_error_) { + std::exception_ptr error = first_error_; + first_error_ = nullptr; + std::rethrow_exception(error); + } } int CPUThreadPool::max_threads() const { @@ -360,5 +342,17 @@ std::unique_ptr create_thread_pool_backend() { return std::make_unique(); } +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 index 6b983ecbab..245322f64f 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.h +++ b/mlx/backend/cpu/threading/openblas/thread_pool.h @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -39,6 +40,7 @@ class CPUThreadPool : public ThreadPoolBackend { private: void worker_loop(int worker_id); + void run_slot(int slot, int nth); // Per-worker wake flag on its own cache line to avoid false sharing. // Workers spin on their private flag -- no cross-core cache contention. @@ -73,6 +75,10 @@ class CPUThreadPool : public ThreadPoolBackend { std::atomic sleeping_count_{0}; // workers currently in cv_.wait bool 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]; }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 19b0d04fa9..ae79ccde10 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -54,6 +54,7 @@ if(MLX_USE_HIGHWAY) 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) endif() target_link_libraries(tests PRIVATE mlx doctest) diff --git a/tests/highway_threading_tests.cpp b/tests/highway_threading_tests.cpp new file mode 100644 index 0000000000..be511cc49a --- /dev/null +++ b/tests/highway_threading_tests.cpp @@ -0,0 +1,193 @@ +// 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 "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 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 whenever it runs more than one thread") { + auto& pool = cpu::ThreadPool::instance(); +#if defined(__linux__) + REQUIRE(cpu::openblas_present()); // the containers link Debian's OpenBLAS +#endif + CHECK( + cpu::openblas_pinned() == + (cpu::openblas_present() && pool.max_threads() > 1)); +#if defined(__linux__) + if (cpu::openblas_pinned()) { + // 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)); +} From 00e805ee21bf42f2710e01dae50bcf9c51ef64ce Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:23:00 +0200 Subject: [PATCH 24/65] Split short fp32 GEMMs by columns across the CPU pool With OpenBLAS pinned to one thread, #3019 threads an fp32 GEMM only when M >= 16 and M*N*K >= 65536, so a short input such as an 8-token embedder query runs on one core. Below the row split, split the columns: each slice calls cblas_sgemm on its own columns of the output. --- mlx/backend/cpu/gemms/cblas.cpp | 39 ++++++++++++++++++++++++++++++++ tests/highway_kernel_tests.cpp | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 8466679ab9..7d813f9ea5 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -4,6 +4,7 @@ #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 @@ -101,6 +102,44 @@ void matmul( std::min(pool.max_threads(), std::max(1, static_cast(M / 8))); } + // A short input (M < 16), such as an embedder's 8-token query: split the + // columns instead, so that pinning OpenBLAS to one thread never leaves a + // large GEMM on one core. Each slice writes its own columns of out. + 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; diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 42ab57b326..29a674c4fa 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -247,3 +247,43 @@ TEST_CASE("highway float16 keeps inf and nan") { CHECK(std::isnan(half_at(root, i))); } } + +#include "mlx/backend/cpu/highway_info.h" +#include "mlx/backend/cpu/threading/common.h" + +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); + } + } + } + } +} From 75b0e55a48a1008587111491ed373cb9f535d609 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:37:29 +0200 Subject: [PATCH 25/65] Free CPU kernel scratch that grew past 64 MiB The dequant+SGEMM path and the low-precision GEMMs keep per-thread float32 scratch that grows to the largest operation and is never freed, outside MLX's allocator: after one test call, 78 MB stayed allocated. Borrow it through a lease that frees a buffer larger than 64 MiB when the operation ends. --- .../cpu/gemms/simd_low_precision_gemm.h | 30 +++++---- mlx/backend/cpu/quantized_highway_backend.cpp | 15 ++--- mlx/backend/cpu/scratch.h | 62 +++++++++++++++++++ tests/highway_kernel_tests.cpp | 25 ++++++++ 4 files changed, 113 insertions(+), 19 deletions(-) create mode 100644 mlx/backend/cpu/scratch.h diff --git a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h index d811a06a3f..287fdc268d 100644 --- a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -6,6 +6,7 @@ #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" @@ -17,14 +18,12 @@ namespace mlx::core::detail { constexpr int LOWP_MIN_BATCHES_PER_THREAD = 4; -// Thread-local scratch buffer for low-precision <-> f32 conversion. -// Avoids mmap/munmap cycles and page faults from repeated large allocations. -inline float* lowp_gemm_scratch(size_t n) { +// Thread-local scratch buffer for low-precision <-> f32 conversion, borrowed +// through ScratchLease. Avoids mmap/munmap cycles and page faults from repeated +// large allocations. +inline std::vector& lowp_gemm_buffer() { thread_local std::vector buf; - if (buf.size() < n) { - buf.resize(n); - } - return buf.data(); + return buf; } template @@ -108,7 +107,8 @@ void lowp_gemv( } } else { // B is [K][N]: accumulate outer products a[k] * B[k][:]. - float* accum = lowp_gemm_scratch(N); + 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]); @@ -182,7 +182,8 @@ void lowp_gemv_threaded( constexpr int W = simd::max_size; size_t n_len = n_end - n_start; - float* accum = lowp_gemm_scratch(n_len); + 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]); @@ -287,7 +288,8 @@ void matmul_lowp( size_t buf_size = a_elems + b_elems + out_elems; pool.parallel_for(n_threads, [&](int tid, int nth) { - float* base = lowp_gemm_scratch(buf_size); + 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; @@ -298,7 +300,9 @@ void matmul_lowp( run_batches(start, end, a_f32, b_f32, out_f32); }); } else { - float* scratch = lowp_gemm_scratch(a_elems + b_elems + out_elems); + cpu::ScratchLease batch_scratch( + lowp_gemm_buffer(), a_elems + b_elems + out_elems); + float* scratch = batch_scratch.data(); run_batches( 0, batch_size, @@ -322,7 +326,9 @@ void matmul_lowp( size_t b_elems = b_rows * ldb; size_t out_elems = M * ldc; - float* a_f32 = lowp_gemm_scratch(a_elems + b_elems + out_elems); + 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; diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 95f943823d..d93ceb7f89 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -11,6 +11,7 @@ #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" @@ -970,13 +971,11 @@ void _qmm_t_simd( } } -// Thread-local scratch buffer for dequant+BLAS path. -float* _qmm_get_scratch(size_t n) { +// Thread-local scratch for the dequant+BLAS path, borrowed through +// ScratchLease. +std::vector& _qmm_scratch_buffer() { thread_local std::vector buf; - if (buf.size() < n) { - buf.resize(n); - } - return buf.data(); + return buf; } // Dequantize a row of packed quantized weights to f32. @@ -1048,7 +1047,9 @@ void _qmm_t_blas( 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; - float* w_f32 = _qmm_get_scratch(w_f32_size + x_f32_size + r_f32_size); + 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; diff --git a/mlx/backend/cpu/scratch.h b/mlx/backend/cpu/scratch.h new file mode 100644 index 0000000000..7ac47d430a --- /dev/null +++ b/mlx/backend/cpu/scratch.h @@ -0,0 +1,62 @@ +// Copyright © 2026 Osaurus AI. All rights reserved. +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "mlx/api.h" + +namespace mlx::core::cpu { + +// Bytes of kernel scratch every thread keeps between operations, process-wide. +// MLX_API gives the static default visibility, so that a shared library and +// the code linked against it count in one place. +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. The buffer stays with +// the thread for reuse, unless the operation left it larger than kKeepBytes: +// then the lease frees it when the operation ends, so one large prefill does +// not hold memory outside MLX's allocator for the thread's lifetime. Leases on +// one buffer do not nest: a second could reallocate it under the first. The +// kernels take one per operation, at its top. +class ScratchLease { + public: + static constexpr size_t kKeepBytes = size_t{64} << 20; + + ScratchLease(std::vector& buffer, size_t floats) : buffer_(buffer) { + 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); + } + ScratchLease(const ScratchLease&) = delete; + ScratchLease& operator=(const ScratchLease&) = delete; + ~ScratchLease() { + 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: + std::vector& buffer_; +}; + +} // namespace mlx::core::cpu diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 29a674c4fa..bb45a6fa78 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -287,3 +287,28 @@ TEST_CASE("highway fp32 matmul splits short inputs by columns, exactly") { } } } + +#include "mlx/backend/cpu/scratch.h" + +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); +} From 50e092f8edc8d4e427fea80b8cdb5129dfec08c4 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 01:31:05 +0200 Subject: [PATCH 26/65] Keep the whole 4-bit dot product in the int8 path on every target qmm_t_int8_cols passed ReorderWidenMulAccumulate a fresh zero as its sum1 argument and dropped it. Highway lets that op add part of the products to sum1, and EMU128 adds the odd lanes there, so on EMU128 the 4-bit int8 path lost half of each group's dot product: one row of 256 activations against 64 x 256 weights (group 64) gave 43.31 in one column where float64 gives -41.18. By Highway 1.4.0's code, NEON puts the upper half in sum1 too; no NEON build has run. The x86 targets passed the same test before the fix. Keep sum1 per column and add it with RearrangeToOddPlusEven. --- mlx/backend/cpu/quantized_highway.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index 9ef26d5106..bf4d1457ff 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -123,9 +123,13 @@ void qmm_t_int8_cols( 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; @@ -142,9 +146,8 @@ void qmm_t_int8_cols( 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); - auto unused = hn::Zero(di32); dot_acc[c] = hn::ReorderWidenMulAccumulate( - di32, prod16, ones16, dot_acc[c], unused); + 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; @@ -161,10 +164,9 @@ void qmm_t_int8_cols( 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_acc[c]), - accum_vec[c]); + hn::Set(df, scale_f * xs), hn::ConvertTo(df, dot), accum_vec[c]); bias_accum[c] += bias_f * xgs; } } From ca6c1b68c0a5d8686b65e1193107c19ef5b9f61b Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:11:29 +0200 Subject: [PATCH 27/65] Pin OpenBLAS to one thread at every CPU pool size The pool pinned OpenBLAS only when it ran more than one thread itself. With MLX_CPU_THREADS=1, or under a cgroup quota below two CPUs, which also sizes the pool to one, OpenBLAS kept its own default of one thread per CPU in the affinity mask: it does not read cpu.max. In an x86-64 container whose cpu.max allows 8 CPUs, it ran 9 threads at MLX_CPU_THREADS=1. So under a quota of one CPU, SGEMM ran on every CPU the process could see. Pin OpenBLAS whenever the pool exists. The test now skips when the linked BLAS has no openblas_set_num_threads, instead of failing. --- mlx/backend/cpu/threading/config.h | 2 +- .../cpu/threading/openblas/thread_pool.cpp | 11 +++---- tests/highway_threading_tests.cpp | 30 +++++++++---------- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/mlx/backend/cpu/threading/config.h b/mlx/backend/cpu/threading/config.h index 9043304123..7db97c9e9d 100644 --- a/mlx/backend/cpu/threading/config.h +++ b/mlx/backend/cpu/threading/config.h @@ -28,7 +28,7 @@ struct ThreadConfig { MLX_API const ThreadConfig& thread_config(); // Whether OpenBLAS's thread setter was found, and whether the pool pinned -// OpenBLAS to one thread (it does whenever it runs more than one itself). +// OpenBLAS to one thread (it does at every pool size). MLX_API bool openblas_present(); MLX_API bool openblas_pinned(); diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp index 1e81c96d0f..83c92b4162 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -120,13 +120,10 @@ CPUThreadPool::CPUThreadPool() } // Look OpenBLAS up at any pool size, so that openblas_present() can answer. init_blas_funcs(); - // Pin OpenBLAS to one thread whenever this pool runs more than one: cblas.cpp - // splits every large SGEMM across the pool, and a second level of threads - // would oversubscribe the cores. MLX_CPU_THREADS is the one setting. - if (max_threads_ > 1) { - set_blas_threads(1); - openblas_pinned_flag().store(blas_set_threads != nullptr); - } + // 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() { diff --git a/tests/highway_threading_tests.cpp b/tests/highway_threading_tests.cpp index be511cc49a..c16ab2b420 100644 --- a/tests/highway_threading_tests.cpp +++ b/tests/highway_threading_tests.cpp @@ -162,23 +162,21 @@ TEST_CASE("highway nested parallel_for runs its range inline") { } } -TEST_CASE("highway pool pins OpenBLAS whenever it runs more than one thread") { - auto& pool = cpu::ThreadPool::instance(); -#if defined(__linux__) - REQUIRE(cpu::openblas_present()); // the containers link Debian's OpenBLAS -#endif - CHECK( - cpu::openblas_pinned() == - (cpu::openblas_present() && pool.max_threads() > 1)); -#if defined(__linux__) - if (cpu::openblas_pinned()) { - // 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); +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 } From d04694efe9718436db98ab88cc5357a362bbfe99 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:14:02 +0200 Subject: [PATCH 28/65] Make quantized_float32_accumulation() a test hook in cpu::detail It answered for one path only: with Highway, transposed affine 2-, 4- and 8-bit quantized matmul sums bf16 and fp16 in float32, while every non-transposed call and 3-, 5- and 6-bit weights still sum in their own dtype. Only a test calls it, so move it out of the switch's public API into cpu::detail, with a comment naming the path. --- mlx/backend/cpu/precision.cpp | 16 ++++++++-------- mlx/backend/cpu/precision.h | 8 +++----- tests/fast_tests.cpp | 2 +- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/mlx/backend/cpu/precision.cpp b/mlx/backend/cpu/precision.cpp index c967312789..790e622087 100644 --- a/mlx/backend/cpu/precision.cpp +++ b/mlx/backend/cpu/precision.cpp @@ -12,6 +12,14 @@ 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 { @@ -38,12 +46,4 @@ bool quantized_int8_available() { #endif } -bool quantized_float32_accumulation() { -#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 index 4475d34d53..fe9119a6af 100644 --- a/mlx/backend/cpu/precision.h +++ b/mlx/backend/cpu/precision.h @@ -18,14 +18,12 @@ MLX_API void set_quantized_int8(bool enabled); // Where it does not, the switch changes nothing. MLX_API bool quantized_int8_available(); -// Whether affine 4- and 8-bit quantized matmul sums bf16 and fp16 activations -// in float32 (the Highway kernels) rather than in their own dtype (the scalar -// _qmm_t, which Highway builds still use for 3, 5 and 6 bits). -MLX_API bool quantized_float32_accumulation(); - 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(); } // namespace detail } // namespace mlx::core::cpu diff --git a/tests/fast_tests.cpp b/tests/fast_tests.cpp index bfc62c95b0..3d1287d9d2 100644 --- a/tests/fast_tests.cpp +++ b/tests/fast_tests.cpp @@ -529,7 +529,7 @@ TEST_CASE("test fast quantized matmul token float16") { } TEST_CASE("test fast quantized matmul token bfloat16") { - if (!cpu::quantized_float32_accumulation()) { + if (!cpu::detail::quantized_float32_accumulation()) { MESSAGE( "this build sums bf16 quantized matmuls in bf16; the bound is for float32 sums"); return; From 856710703ce2ff1fd93796ca6bbc8b34e9d2dbe7 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:24:29 +0200 Subject: [PATCH 29/65] Export cpu::ThreadPool from shared builds MLX hides symbols by default, and ThreadPool had no MLX_API, so libmlx.so exported none of its members. A -DBUILD_SHARED_LIBS=ON build of the tests then failed to link on x86-64, where Highway is built: #3019's thread_pool_tests.cpp and our Highway tests call ThreadPool::instance(), max_threads() and parallel_for(). The build that .github/actions/build uses for the C++ tests is shared. Export the class; with it, that build links and its tests pass. --- mlx/backend/cpu/threading/common.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mlx/backend/cpu/threading/common.h b/mlx/backend/cpu/threading/common.h index 95cedfa19c..39b1eabd56 100644 --- a/mlx/backend/cpu/threading/common.h +++ b/mlx/backend/cpu/threading/common.h @@ -2,6 +2,7 @@ #pragma once +#include "mlx/api.h" #include "mlx/backend/cpu/threading/base.h" #include @@ -31,7 +32,7 @@ namespace mlx::core::cpu { * process_chunk(0, size); * } */ -class ThreadPool { +class MLX_API ThreadPool { public: /// Get the singleton instance. static ThreadPool& instance(); From 32ba2106459ced055a5a17d584b097192867f264 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:31:53 +0200 Subject: [PATCH 30/65] Make MLX_USE_HIGHWAY_KERNELS a public compile definition Installed headers change with it: fast_primitives.h declares the four norm primitives' eval_cpu out of line, and unary.h and binary.h take another code path. With the definition private, code compiled against libmlx saw other definitions of the same classes and templates than the library did. Make it PUBLIC, so that the tests, anything linking the mlx target, and the exported MLX target all get it. Highway's own definitions stay PRIVATE. --- mlx/backend/cpu/CMakeLists.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 61762313e7..f6cf09f996 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -63,8 +63,10 @@ if(MLX_USE_HIGHWAY) # 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}) - target_compile_definitions(mlx PRIVATE MLX_USE_HIGHWAY_KERNELS - ${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") From 67b16c1d9157b2243e1f90cfc90ca790f504790c Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:35:30 +0200 Subject: [PATCH 31/65] Fix the edges of the Highway CMake option - MLX_ENABLE_X86_SIMD only set MLX_USE_HIGHWAY's default, which option() ignores once the option is cached: -DMLX_ENABLE_X86_SIMD=OFF on a second configure left the kernels on. The alias now sets the cached option on any configure and removes itself from the cache, so that a later -DMLX_USE_HIGHWAY decides. The line that copied the option back to the alias had no reader. - The CPU backend's processor check took any name containing x86; it now uses the top level's anchored pattern. - Without the CPU backend the tests did not link: fast_tests.cpp, which every build compiles, calls precision.cpp's int8 switch, and the Highway tests were added whenever MLX_USE_HIGHWAY was on, as a cache from a CPU build leaves it. The no-CPU backend now compiles precision.cpp, where the switch changes nothing, and the Highway tests need the CPU backend too. --- CMakeLists.txt | 15 ++++++++------- mlx/backend/cpu/CMakeLists.txt | 4 ++-- mlx/backend/no_cpu/CMakeLists.txt | 1 + tests/CMakeLists.txt | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0c2bed188b..89fd9f3225 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,9 +42,7 @@ 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 (runtime-dispatched per target). On -# by default for Linux x86-64. MLX_ENABLE_X86_SIMD, the name in -# ml-explore/mlx#3019, is accepted as an alias. +# 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)$") @@ -52,12 +50,15 @@ if(MLX_BUILD_CPU else() set(_MLX_USE_HIGHWAY_DEFAULT OFF) endif() -if(DEFINED MLX_ENABLE_X86_SIMD) - set(_MLX_USE_HIGHWAY_DEFAULT ${MLX_ENABLE_X86_SIMD}) -endif() option(MLX_USE_HIGHWAY "Build the CPU backend's Highway SIMD kernels" ${_MLX_USE_HIGHWAY_DEFAULT}) -set(MLX_ENABLE_X86_SIMD ${MLX_USE_HIGHWAY}) +# 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") diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index f6cf09f996..cc9dd87083 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -9,8 +9,8 @@ endif() set(MLX_HIGHWAY_INCLUDE_DIR "") if(MLX_USE_HIGHWAY) - if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|x86") - message(FATAL_ERROR "MLX_USE_HIGHWAY requires an x86 target") + 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 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/tests/CMakeLists.txt b/tests/CMakeLists.txt index ae79ccde10..560d9a43b8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -48,7 +48,7 @@ target_sources( linalg_tests.cpp ${GPU_TEST_SOURCES}) -if(MLX_USE_HIGHWAY) +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) From 2f43d18855538d992d3b0e84ead623d1afa466ba Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 06:38:27 +0200 Subject: [PATCH 32/65] Refuse a nested scratch lease A second lease on a thread's scratch buffer can reallocate it under the first, and nothing refused one: in the new test, the second lease resized the buffer under the first from 16 floats to 1048576. Since a nested parallel_for now runs its slots inline instead of deadlocking, such a bug would not even hang. A thread_local flag in ScratchLease now makes a second lease on the same thread throw std::logic_error. The kernels take one lease per operation, so none of them holds two. --- mlx/backend/cpu/scratch.h | 16 ++++++++++------ tests/highway_kernel_tests.cpp | 13 +++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/mlx/backend/cpu/scratch.h b/mlx/backend/cpu/scratch.h index 7ac47d430a..bce35b0bb2 100644 --- a/mlx/backend/cpu/scratch.h +++ b/mlx/backend/cpu/scratch.h @@ -5,6 +5,7 @@ #include #include +#include #include #include "mlx/api.h" @@ -23,17 +24,17 @@ 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. The buffer stays with -// the thread for reuse, unless the operation left it larger than kKeepBytes: -// then the lease frees it when the operation ends, so one large prefill does -// not hold memory outside MLX's allocator for the thread's lifetime. Leases on -// one buffer do not nest: a second could reallocate it under the first. The -// kernels take one per operation, at its top. +// 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); @@ -41,10 +42,12 @@ class ScratchLease { 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_); @@ -56,6 +59,7 @@ class ScratchLease { } private: + static inline thread_local bool leased_ = false; std::vector& buffer_; }; diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index bb45a6fa78..0c3805f8e2 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -1,6 +1,8 @@ // Copyright © 2026 Osaurus AI. All rights reserved. // SPDX-License-Identifier: MIT +#include + #include "doctest/doctest.h" #include "mlx/mlx.h" @@ -312,3 +314,14 @@ TEST_CASE("highway scratch past 64 MiB is freed after its operation") { .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)); +} From 5c63645999bc876301b2b2642ebcbe337c892ca5 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 07:00:53 +0200 Subject: [PATCH 33/65] Tidy the Highway tests, and test bf16 sin and cos past 2^23 - A scope guard, cpu::detail::QuantizedInt8Scope, restores the int8 switch in the three tests that turn it on, so an exception no longer leaves it on for the tests that follow. - highway_quantized_tests.cpp's copy of within_sum_bound was unused and goes; the comment of the bound after it no longer starts from it. - The #includes in the middle of two files move to the top. - A regression test for the writable Highway Simd lanes: bf16 sin and cos of vectors with a lane past 2^23, which take std::sin and std::cos lane by lane. With the writable operator[] removed for bfloat16 only (removed altogether, float and double do not compile), 127 of its 128 checks failed, each reading 0, and no other test failed. The OpenBLAS test's REQUIRE became a skip in the commit that pins OpenBLAS at every pool size. --- mlx/backend/cpu/precision.h | 15 +++++++++++++++ tests/fast_tests.cpp | 3 +-- tests/highway_info_tests.cpp | 16 ++++++++-------- tests/highway_kernel_tests.cpp | 26 +++++++++++++++++++++---- tests/highway_quantized_tests.cpp | 32 ++++--------------------------- 5 files changed, 50 insertions(+), 42 deletions(-) diff --git a/mlx/backend/cpu/precision.h b/mlx/backend/cpu/precision.h index fe9119a6af..943c5103f6 100644 --- a/mlx/backend/cpu/precision.h +++ b/mlx/backend/cpu/precision.h @@ -24,6 +24,21 @@ 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/tests/fast_tests.cpp b/tests/fast_tests.cpp index 3d1287d9d2..b3bc56e98d 100644 --- a/tests/fast_tests.cpp +++ b/tests/fast_tests.cpp @@ -518,9 +518,8 @@ TEST_CASE("test fast quantized matmul token float32 with int8 activations") { MESSAGE("no int8 path in this build"); return; } - cpu::set_quantized_int8(true); + cpu::detail::QuantizedInt8Scope on(true); check_quantized_matmul_8bit_high_values(true); - cpu::set_quantized_int8(false); } TEST_CASE("test fast quantized matmul token float16") { diff --git a/tests/highway_info_tests.cpp b/tests/highway_info_tests.cpp index 9a1eb4afc7..38499f3a85 100644 --- a/tests/highway_info_tests.cpp +++ b/tests/highway_info_tests.cpp @@ -3,13 +3,12 @@ #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; -#include "mlx/backend/cpu/highway_info.h" -#include "mlx/backend/cpu/precision.h" - namespace hi = mlx::core::cpu::highway_info; namespace { @@ -71,11 +70,12 @@ TEST_CASE("highway int8 family records only when the int8 path ran") { 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::set_quantized_int8(true); - CHECK( - sum(quantized_matmul(x, q[0], q[1], q[2], true, 64, 4)).item() != - 0.0f); - cpu::set_quantized_int8(false); + { + 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); } diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 0c3805f8e2..abc13f54f5 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -5,6 +5,9 @@ #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; @@ -250,8 +253,25 @@ TEST_CASE("highway float16 keeps inf and nan") { } } -#include "mlx/backend/cpu/highway_info.h" -#include "mlx/backend/cpu/threading/common.h" +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 fp32 matmul splits short inputs by columns, exactly") { namespace hi = mlx::core::cpu::highway_info; @@ -290,8 +310,6 @@ TEST_CASE("highway fp32 matmul splits short inputs by columns, exactly") { } } -#include "mlx/backend/cpu/scratch.h" - 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. diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp index 93cca364cd..3c35757ebe 100644 --- a/tests/highway_quantized_tests.cpp +++ b/tests/highway_quantized_tests.cpp @@ -3,36 +3,15 @@ #include "doctest/doctest.h" +#include "mlx/backend/cpu/precision.h" #include "mlx/mlx.h" using namespace mlx::core; namespace { -// Every |got - reference| is at most c * eps32 * sum_k |a_ik b_kj|. The -// reference and the magnitude are computed in float64 by MLX's own ops on the -// CPU. That makes an fp32 kernel's rounding bound rigorous for any summation -// order with c = K + 2, while an index or precision bug exceeds it. -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(); -} - -// The same bound for an affine quantized matmul against its dequantized -// weights. The kernels compute s * sum(x * q) + b * sum(x) per group, so their -// rounding scales with sum |x| * (|s| * q + |b|), which exceeds sum |x * w| -// where s * q and b nearly cancel. dequantize() with |s| and |b| gives -// |s| * q + |b|. +// |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, @@ -143,8 +122,6 @@ TEST_CASE("highway qqmm mxfp8 rounds the block scale up") { CHECK(out[0] == 576.0f); } -#include "mlx/backend/cpu/precision.h" - 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. @@ -156,12 +133,11 @@ TEST_CASE("highway quantized matmul is exact unless int8 is switched on") { 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::set_quantized_int8(true); + 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)); - cpu::set_quantized_int8(false); } TEST_CASE("highway int8 switch parses its variable") { From dea074379d89238c219db9572217cbb7aba9e04b Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 07:08:19 +0200 Subject: [PATCH 34/65] Shorten our CPU backend comments, and drop claims no log shows - The thread pool's comments no longer describe the GCD pool, which this branch dropped. - threading/config.cpp holds #3019's Windows core count, so its header carries #3019's copyright line too, and #3019's unmeasured +5-7% goes. - threading/config.h says what an invalid MLX_CPU_THREADS does now: the pool uses its default and keeps the message for a caller. - precision.h says to set the int8 switch only while no quantized matmul runs, since the kernels read it per row. - Our comments come down to one or two lines, and claim only what a log shows: 65536 is what exponent 31 decodes to, the bf16 sum test names only the logged pool sizes (8 threads give 0; 9 and 12 give -8192), no comment cites line numbers of the code before #3019, and scratch.h makes no shared-library claim. --- mlx/backend/cpu/gemms/cblas.cpp | 5 ++-- .../cpu/gemms/simd_low_precision_gemm.h | 5 ++-- mlx/backend/cpu/highway_info.h | 12 +++----- mlx/backend/cpu/highway_utils.h | 7 ++--- mlx/backend/cpu/precision.h | 7 ++--- mlx/backend/cpu/quantized_highway_backend.cpp | 5 ++-- mlx/backend/cpu/scratch.h | 2 -- mlx/backend/cpu/simd/highway_simd.h | 13 +++------ mlx/backend/cpu/threading/base.h | 13 +++------ mlx/backend/cpu/threading/common.h | 5 ++-- mlx/backend/cpu/threading/config.cpp | 8 ++--- mlx/backend/cpu/threading/config.h | 10 +++---- .../cpu/threading/openblas/thread_pool.cpp | 5 ++-- .../cpu/threading/openblas/thread_pool.h | 3 +- mlx/backend/no_gpu/primitives.cpp | 6 ++-- tests/highway_kernel_tests.cpp | 29 +++++++------------ tests/highway_quantized_tests.cpp | 11 +++---- 17 files changed, 51 insertions(+), 95 deletions(-) diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 7d813f9ea5..00aae41dc2 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -102,9 +102,8 @@ void matmul( std::min(pool.max_threads(), std::max(1, static_cast(M / 8))); } - // A short input (M < 16), such as an embedder's 8-token query: split the - // columns instead, so that pinning OpenBLAS to one thread never leaves a - // large GEMM on one core. Each slice writes its own columns of out. + // 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 = diff --git a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h index 287fdc268d..a7008d5e46 100644 --- a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -18,9 +18,8 @@ namespace mlx::core::detail { constexpr int LOWP_MIN_BATCHES_PER_THREAD = 4; -// Thread-local scratch buffer for low-precision <-> f32 conversion, borrowed -// through ScratchLease. Avoids mmap/munmap cycles and page faults from repeated -// large allocations. +// 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; diff --git a/mlx/backend/cpu/highway_info.h b/mlx/backend/cpu/highway_info.h index 5ea6af6d05..d3cce930a6 100644 --- a/mlx/backend/cpu/highway_info.h +++ b/mlx/backend/cpu/highway_info.h @@ -32,11 +32,8 @@ MLX_API void set_targets_for_test(int64_t targets); // does not know. MLX_API const char* target_name(int64_t target); -// What a family's kernels did since the last reset_stats(). `executed` is the -// OR of every target whose kernel ran. `highway_calls` is 1 once a dispatched -// kernel ran, and `fallback_calls` once an entry point sent a call to code that -// is not dynamically dispatched: both count to 1 and stop, so that recording -// in a row loop writes shared memory only once. +// 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; @@ -55,9 +52,8 @@ MLX_API void record_sgemm_column_split(); } // namespace mlx::core::cpu::highway_info -// For the kernels. MLX_HIGHWAY_RECORD goes inside HWY_NAMESPACE code, where -// HWY_TARGET is the target that code was compiled for. Fully qualified, -// because the kernels' own namespaces hold an unrelated `highway`. +// 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) diff --git a/mlx/backend/cpu/highway_utils.h b/mlx/backend/cpu/highway_utils.h index 0384603768..40a6d53218 100644 --- a/mlx/backend/cpu/highway_utils.h +++ b/mlx/backend/cpu/highway_utils.h @@ -15,11 +15,8 @@ namespace HWY_NAMESPACE { namespace hn = hwy::HWY_NAMESPACE; -// Highway emulates float16 -> float32 where a target has no conversion -// instruction (x86 before AVX2, EMU128, SCALAR), and reads exponent 31 as a -// finite exponent there: inf became 65536. Lanes with exponent 31 take -// float32's inf, or a quiet NaN with the same payload, as the instructions -// give. simd/highway_simd.h has the same function for the facade. +// 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; diff --git a/mlx/backend/cpu/precision.h b/mlx/backend/cpu/precision.h index 943c5103f6..0a2ae248c3 100644 --- a/mlx/backend/cpu/precision.h +++ b/mlx/backend/cpu/precision.h @@ -7,11 +7,10 @@ namespace mlx::core::cpu { -// Whether affine quantized matmul may round activations to int8 per group -// (the fast path of ml-explore/mlx#3019). Off unless MLX_CPU_QUANTIZED_INT8 is -// a nonzero integer at first use, or until set_quantized_int8(true). -// Process-wide. +// 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). diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index d93ceb7f89..7ea049aa07 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -1181,9 +1181,8 @@ void _qmm_dispatch_transpose( // 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's dequantizer reads 32 / bits values per uint32 word, which - // is how MLX packs 2, 4 and 8 bits. 3, 5 and 6 bits are packed as a byte - // stream, so they take the row kernels below at every 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); diff --git a/mlx/backend/cpu/scratch.h b/mlx/backend/cpu/scratch.h index bce35b0bb2..5540499044 100644 --- a/mlx/backend/cpu/scratch.h +++ b/mlx/backend/cpu/scratch.h @@ -13,8 +13,6 @@ namespace mlx::core::cpu { // Bytes of kernel scratch every thread keeps between operations, process-wide. -// MLX_API gives the static default visibility, so that a shared library and -// the code linked against it count in one place. MLX_API inline std::atomic& scratch_retained() { static std::atomic bytes{0}; return bytes; diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 538a07bdbb..99b54dbe98 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -129,11 +129,8 @@ LaneTypeT* lane_ptr(T* ptr) { return reinterpret_cast*>(ptr); } -// Highway emulates float16 -> float32 where a target has no conversion -// instruction (x86 before AVX2, EMU128, SCALAR), and reads exponent 31 as a -// finite exponent there: inf became 65536. Lanes with exponent 31 take -// float32's inf, or a quiet NaN with the same payload, as the instructions -// give. highway_utils.h has the same function for the dispatched kernels. +// 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; @@ -848,10 +845,8 @@ inline Simd fma(Simd x, Simd y, U z) { return out; #else if constexpr (std::is_floating_point_v) { - // Without FMA instructions MulAdd rounds twice, and fma promises one - // rounding (base_simd.h's std::fma): MLX's polynomials rely on it. This - // is the static target's path, SSE2 on x86-64, which runs every - // elementwise kernel; glibc's fma uses the CPU's FMA where it has one. + // 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]; diff --git a/mlx/backend/cpu/threading/base.h b/mlx/backend/cpu/threading/base.h index 128d854397..8272ff7315 100644 --- a/mlx/backend/cpu/threading/base.h +++ b/mlx/backend/cpu/threading/base.h @@ -8,12 +8,8 @@ namespace mlx::core::cpu { /** - * Pure virtual interface for platform-specific thread pool implementations. - * - * This interface abstracts the threading mechanism so different platforms - * can use their respective thread pools: - * - macOS: Grand Central Dispatch (GCD) - * - Linux/Windows: persistent threading with optional OpenBLAS coordination + * Pure virtual interface for the thread pool implementation: persistent + * threading with optional OpenBLAS coordination (openblas/thread_pool.cpp). */ class ThreadPoolBackend { public: @@ -40,9 +36,8 @@ class ThreadPoolBackend { }; /** - * Factory function to create the platform-specific thread pool backend. - * Implemented in platform-specific files (accelerate/thread_pool.mm, - * openblas/thread_pool.cpp). + * Factory function to create the thread pool backend, implemented in + * openblas/thread_pool.cpp. */ std::unique_ptr create_thread_pool_backend(); diff --git a/mlx/backend/cpu/threading/common.h b/mlx/backend/cpu/threading/common.h index 39b1eabd56..8d7e23581c 100644 --- a/mlx/backend/cpu/threading/common.h +++ b/mlx/backend/cpu/threading/common.h @@ -14,9 +14,8 @@ namespace mlx::core::cpu { * Thread pool for CPU backend parallelism. * * Provides a simple interface for parallel execution of work across multiple - * threads. Uses platform-native thread pools for optimal performance: - * - macOS: Grand Central Dispatch (GCD) - * - Linux/Windows: persistent threading with optional OpenBLAS coordination + * threads: persistent threading with optional OpenBLAS coordination, in builds + * with Highway kernels. * * Usage: * auto& pool = ThreadPool::instance(); diff --git a/mlx/backend/cpu/threading/config.cpp b/mlx/backend/cpu/threading/config.cpp index 0c7fdca9e1..d93a9b7bda 100644 --- a/mlx/backend/cpu/threading/config.cpp +++ b/mlx/backend/cpu/threading/config.cpp @@ -1,3 +1,4 @@ +// Copyright © 2026 Apple Inc. // Copyright © 2026 Osaurus AI. All rights reserved. // SPDX-License-Identifier: MIT @@ -17,11 +18,8 @@ #include #endif -// Physical core detection -- AVX2/FMA workloads get no benefit from SMT -// (hyperthreads share the same SIMD execution units, L1/L2 cache, and memory -// bandwidth). Using physical core count avoids over-subscription and reduces -// atomic/mutex contention in the thread pool. Benchmarked: 16 physical cores -// is +5-7% faster than logical core count for quantized LLM inference. +// #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() { diff --git a/mlx/backend/cpu/threading/config.h b/mlx/backend/cpu/threading/config.h index 7db97c9e9d..a83c8e8372 100644 --- a/mlx/backend/cpu/threading/config.h +++ b/mlx/backend/cpu/threading/config.h @@ -19,8 +19,8 @@ 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 vmlx reports the error at model load. + // 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; }; @@ -47,10 +47,8 @@ using Topology = std::function>(int cpu)>; MLX_API int count_physical_cores( const std::vector& cpus, const Topology& topology); -// The tightest cgroup v2 cpu.max from the process's cgroup, named by the "0::" -// line of `self_cgroup` (/proc/self/cgroup's text), up to `root` -// (/sys/fs/cgroup). nullopt without a v2 line, for a relative path, or without -// a limit. +// 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); diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.cpp b/mlx/backend/cpu/threading/openblas/thread_pool.cpp index 83c92b4162..552d44ea38 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -235,9 +235,8 @@ void CPUThreadPool::parallel_for( return; } - // A task that calls parallel_for runs the inner range itself, every slot in - // turn: the workers are busy with the outer call, and dispatch_mtx_ is not - // recursive. Callers size per-slot state by n_threads, so each slot runs. + // 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); diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.h b/mlx/backend/cpu/threading/openblas/thread_pool.h index 245322f64f..506eeee23e 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.h +++ b/mlx/backend/cpu/threading/openblas/thread_pool.h @@ -58,8 +58,7 @@ class CPUThreadPool : public ThreadPoolBackend { // MLX's stream_generate uses a separate generation_stream, so two // StreamThreads may call parallel_for simultaneously. Since all task // state (task_ptr_, started_, done_, etc.) is shared, concurrent calls - // must be serialized. The GCD backend (macOS) handles this implicitly - // via dispatch_apply; we need an explicit mutex. + // must be serialized. std::mutex dispatch_mtx_; std::mutex mtx_; // worker sleep/wake coordination diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index 9f93b0d8d5..13847bd841 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -35,10 +35,8 @@ bool fast::ScaledDotProductAttention::use_fallback( bool force_fused, Stream s) { #if defined(MLX_USE_HIGHWAY_KERNELS) - // Use native CPU kernel for inference (handles causal, array mask, sinks) - // The native CPU kernel takes float32, float16 and bfloat16, and one head - // dimension of at most 256 (its stack buffers) for queries, keys and values. - // Everything else composes. + // Use native CPU kernel for inference (handles causal, array mask, sinks). + // It takes float32, float16 and bfloat16, one head dim up to 256. const bool native_type = q.dtype() == float32 || q.dtype() == float16 || q.dtype() == bfloat16; if (s.device == Device::cpu && !output_logsumexp && native_type && diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index abc13f54f5..9c1cbe3fc7 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -14,10 +14,8 @@ using namespace mlx::core; namespace { -// Every |got - reference| is at most c * eps32 * sum_k |a_ik b_kj|. The -// reference and the magnitude are computed in float64 by MLX's own ops on the -// CPU. That makes an fp32 kernel's rounding bound rigorous for any summation -// order with c = K + 2, while an index or precision bug exceeds it. +// |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, @@ -146,9 +144,8 @@ TEST_CASE("highway float64 elementwise math computes in double") { } TEST_CASE("highway integer power with a negative exponent") { - // base_simd.h's rule (hwy/base, lines 249-267): a signed integer to a - // negative power is 0, for every base, 1 included. #3019's facade looped - // forever here. + // 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 = { @@ -177,22 +174,16 @@ TEST_CASE("highway fp16 sum keeps each thread's partial in float") { } TEST_CASE("highway bf16 sum does not depend on the thread count") { - // 2^20 + 3 ones, then -2^20: the sum is exactly 3. Every thread's partial is - // exact in float; rounded to bf16 before they are combined, the total is - // never 3 for any pool of 2 to 64 threads (0 with 2, 4, 8, 16 or 32, 4096 - // with 6, -8192 with 12). A plain count of ones is no test: at many pool - // sizes each partial happens to be exact in bf16. item on a bf16 array - // would read four bytes of a two-byte buffer, so widen first. + // 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") { - // MLX's erfinv computes t = fma(a, -a, 1). Where Highway's MulAdd rounds a * - // a first, near |a| = 1 the result keeps few of its bits: 64 units in the - // last place at 0.99983, where one rounding (the scalar code's std::fma) - // keeps the worst over this range to about 2.1. + // 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) { @@ -219,8 +210,8 @@ TEST_CASE("highway facade fma rounds once on every target") { } TEST_CASE("highway float16 keeps inf and nan") { - // Highway emulates float16 -> float32 where a target has no conversion - // instruction, and reads exponent 31 as finite there: inf became 65536. + // 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); diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp index 3c35757ebe..bc86cf8456 100644 --- a/tests/highway_quantized_tests.cpp +++ b/tests/highway_quantized_tests.cpp @@ -75,10 +75,8 @@ TEST_CASE("highway gather_qmm merges experts without the byte-packing bug") { namespace { -// One group of `values` through qqmm against a quantized identity, which -// returns the activations exactly as QQMatmul quantized and dequantized them. -// The identity quantizes exactly: mxfp4 stores 1 as 4 with scale 2^-2, mxfp8 as -// 256 with scale 2^-8. +// `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, @@ -113,9 +111,8 @@ TEST_CASE("highway qqmm mxfp4 rounds half to even on the e2m1 grid") { } TEST_CASE("highway qqmm mxfp8 rounds the block scale up") { - // amax / 448 = 1.3: a nearest E8M0 scale of 1 would saturate the block's - // largest element to 448. Rounding the scale up to 2 keeps it: 582.4 / 2 = - // 291.2, which E4M3 rounds to 288, so the element returns as 576. + // 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); From fcb6aeea23ae8d4eb1460180f652471164518161 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 28 Sep 2026 08:53:39 +0200 Subject: [PATCH 35/65] Keep the sign of zero in the Highway facade's floor, ceil and rint Below SSE4, Highway emulates Floor, Ceil and Round, and the emulation can return +0 where C returns -0. The facade is compiled at Highway's static target, and MLX's own sources get no ISA flags, so a default x86-64 build runs it at SSE2. There MLX's floor, ceil and round lost the sign of zero, and so did trunc, which ops.cpp builds from ceil and floor. The new test compares the four with C's functions on 16 values in float32, float64, bfloat16 and float16, sign of zero included. Before this change it failed 48 of its 512 checks, each on the sign, the same in all four dtypes: - floor(-0) gave +0; - ceil(-0), ceil(-0.25), ceil(-0.5) and ceil(-0.75) gave +0; - round(-0), round(-0.25) and round(-0.5) gave +0; - trunc gave +0 for the four inputs where ceil did. vmlx's kernel tests found it once their exact comparison told the two zeros apart: "ceil float32: 23 of 4099 differ; element 445 is 0.0, not -0.0". Highway's own Floor, Ceil and Round differ from C the same way at SSSE3, and match it at SSE4 and AVX2. A result rounded to an integer has its input's sign, so the facade's floor, ceil and rint now copy the input's sign onto Highway's result. The new test passes all 512 checks, and the x86 suite all 295 cases it ran when this was written, on MLX 0.32.2 (the 16 CPU-JIT cases run only in GCC builds). --- mlx/backend/cpu/simd/highway_simd.h | 8 ++-- tests/highway_kernel_tests.cpp | 59 +++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 99b54dbe98..b55b8d1b4d 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -751,13 +751,15 @@ inline Simd sqrt(Simd a) { } } +// 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::Floor(a.value); + out.value = hn::CopySign(hn::Floor(a.value), a.value); return out; } else { return a; @@ -770,7 +772,7 @@ inline Simd ceil(Simd a) { return Simd(ceil(Simd(a))); } else if constexpr (std::is_floating_point_v) { Simd out; - out.value = hn::Ceil(a.value); + out.value = hn::CopySign(hn::Ceil(a.value), a.value); return out; } else { return a; @@ -783,7 +785,7 @@ inline Simd rint(Simd a) { return Simd(rint(Simd(a))); } else if constexpr (std::is_floating_point_v) { Simd out; - out.value = hn::Round(a.value); + out.value = hn::CopySign(hn::Round(a.value), a.value); return out; } else { return a; diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 9c1cbe3fc7..0c685a0c77 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -1,7 +1,9 @@ // Copyright © 2026 Osaurus AI. All rights reserved. // SPDX-License-Identifier: MIT +#include #include +#include #include "doctest/doctest.h" @@ -264,6 +266,63 @@ TEST_CASE("highway bf16 sin and cos of lanes past 2^23") { } } +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; From 2109bbe403bc2e004c1746a56d0812c4ee0cea81 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:35:32 +0200 Subject: [PATCH 36/65] Fix a stale slot claim and a missed first call in the CPU pool #3019's thread pool had two races: - A worker checked task_gen_ and started_ < nth, then claimed a slot with a separate started_.fetch_add. A worker that stalled between the two claimed a slot of the next parallel_for. It then ran that call's task with the old call's nth, or took a slot index and did not run it, so that the call never returned, or let the call return while a slot still ran. - A worker announced ready_ before it read gen_. If the first parallel_for came in between, the worker missed it; with one worker (MLX_CPU_THREADS=2), that call never returned. Also, stop_ was a plain bool that workers read without the lock. Two new tests hold a worker at these points through a test hook, cpu::detail::set_pool_test_hook, in pools that cpu::detail::make_thread_pool builds at a given size. Before this change both failed: - a pool of two whose worker is held after it announces ready_: "the first parallel_for did not return in 5 s"; - a worker held at a claim of a call with 3 slots, then let go in a call with 2: "slot 1 ran with nth 3"; with 2 slots, then 3: "slot 1 ran with nth 2". Now one compare-and-swap claims a slot, on a word that holds the call's generation, its slot count and the next slot: it fails once the call has changed, and nth comes from the same word as the slot. A worker reads gen_ before it announces ready_, and stop_ is atomic. The resets at the end of parallel_for go, since a late worker finds no free slot. Without a hook set, each hook point costs one relaxed load. The two tests pass, also in 50 of 50 repeated runs, and so does the x86-64 suite, on MLX 0.32.2 when this was written: Clang, 297 of 297 cases, also with MLX_CPU_THREADS=1; GCC Debug, 313 of 313; a shared library build, 297 of 297. On arm64, the pool alone under GCC 12's ThreadSanitizer, with two callers of 20000 calls each: the old pool hung in 3 of 3 runs, within its first 2000 calls, with started_ equal to nth, done_ one short and every worker asleep; one run first reported 5 data races, the first on task_ptr_. The new pool finished 143 of 143 runs with no report. --- mlx/backend/cpu/threading/config.h | 13 + .../cpu/threading/openblas/thread_pool.cpp | 100 ++++---- .../cpu/threading/openblas/thread_pool.h | 14 +- tests/highway_threading_tests.cpp | 237 ++++++++++++++++++ 4 files changed, 314 insertions(+), 50 deletions(-) diff --git a/mlx/backend/cpu/threading/config.h b/mlx/backend/cpu/threading/config.h index a83c8e8372..5cae3c78eb 100644 --- a/mlx/backend/cpu/threading/config.h +++ b/mlx/backend/cpu/threading/config.h @@ -4,6 +4,7 @@ #pragma once #include +#include #include #include #include @@ -11,6 +12,7 @@ #include #include "mlx/api.h" +#include "mlx/backend/cpu/threading/base.h" namespace mlx::core::cpu { @@ -59,6 +61,17 @@ MLX_API ThreadConfig resolve_thread_config( 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 index 552d44ea38..8449760439 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.cpp +++ b/mlx/backend/cpu/threading/openblas/thread_pool.cpp @@ -87,6 +87,15 @@ int get_default_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) { @@ -102,8 +111,10 @@ void CPUThreadPool::run_slot(int slot, int nth) { in_parallel_for = false; } -CPUThreadPool::CPUThreadPool() - : max_threads_(std::min(get_default_threads(), MAX_WORKERS + 1)) { +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. @@ -149,17 +160,37 @@ CPUThreadPool::~CPUThreadPool() { // 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); - uint64_t my_gen = gen_.load(std::memory_order_acquire); + 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_, task_n_threads_, - // started_, done_), so we can access them without the mutex. + // 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 = @@ -173,24 +204,10 @@ void CPUThreadPool::worker_loop(int worker_id) { } if (woken_by_spin) { - // Fast path: skip mutex entirely. Task state is visible via the - // acquire load on wake_gen (happens-before from the main thread's - // release store on gen_). task_ptr_ is a raw pointer (naturally - // atomic on x86-64), so no std::function access race. + // Fast path: skip mutex entirely. if (stop_) return; - { - if (task_gen_.load(std::memory_order_acquire) != my_gen) - continue; - int nth = task_n_threads_.load(std::memory_order_acquire); - if (nth > 0 && started_.load(std::memory_order_relaxed) < nth) { - int slot = started_.fetch_add(1, std::memory_order_acq_rel); - if (slot < nth) { - run_slot(slot, nth); - done_.fetch_add(1, std::memory_order_acq_rel); - } - } - } + claim_slot(worker_id, my_gen); continue; } @@ -212,16 +229,7 @@ void CPUThreadPool::worker_loop(int worker_id) { // Release mutex immediately -- task state is visible via gen_ acquire // (happens-before from parallel_for's gen_.fetch_add release). lk.unlock(); - if (task_gen_.load(std::memory_order_acquire) != my_gen) - continue; - int nth = task_n_threads_.load(std::memory_order_acquire); - if (nth <= 0 || started_.load(std::memory_order_relaxed) >= nth) - continue; - int slot = started_.fetch_add(1, std::memory_order_acq_rel); - if (slot >= nth) - continue; - run_slot(slot, nth); - done_.fetch_add(1, std::memory_order_acq_rel); + claim_slot(worker_id, my_gen); } } } @@ -245,7 +253,7 @@ void CPUThreadPool::parallel_for( } // Serialize concurrent parallel_for calls from different CPU streams. - // All task state (task_ptr_, started_, done_, etc.) is shared, so + // 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. @@ -260,13 +268,8 @@ void CPUThreadPool::parallel_for( // Requires mutex for gen_ update (cv_ lost-wakeup safety) and // per-worker wake_gen writes. - // Set up task state. task_ptr_ is a raw pointer (naturally atomic on - // x86-64). All relaxed stores below become visible to workers via the - // gen_.fetch_add(release) below, which provides happens-before for any - // thread that observes the new gen_ via acquire load. + // Set up the task. The release store to claim_ below publishes it. task_ptr_ = &f; - task_n_threads_.store(n_threads, std::memory_order_relaxed); - started_.store(1, std::memory_order_relaxed); // slot 0 reserved for main done_.store(0, std::memory_order_relaxed); int wake_count = std::min(needed_workers, n_workers); @@ -282,7 +285,10 @@ void CPUThreadPool::parallel_for( 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; - task_gen_.store(new_gen, std::memory_order_release); + // 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. @@ -317,12 +323,6 @@ void CPUThreadPool::parallel_for( } } - // Reset task state so late-waking workers (from spin or cv_wait) - // won't pass the started_ < task_n_threads_ check with stale values. - task_gen_.store(0, std::memory_order_release); - task_n_threads_.store(0, std::memory_order_release); - task_ptr_ = nullptr; - if (first_error_) { std::exception_ptr error = first_error_; first_error_ = nullptr; @@ -338,6 +338,16 @@ 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. diff --git a/mlx/backend/cpu/threading/openblas/thread_pool.h b/mlx/backend/cpu/threading/openblas/thread_pool.h index 506eeee23e..e4b1ee973b 100644 --- a/mlx/backend/cpu/threading/openblas/thread_pool.h +++ b/mlx/backend/cpu/threading/openblas/thread_pool.h @@ -32,6 +32,8 @@ namespace mlx::core::cpu { 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) @@ -41,6 +43,8 @@ class CPUThreadPool : public ThreadPoolBackend { 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. @@ -57,7 +61,7 @@ class CPUThreadPool : public ThreadPoolBackend { // 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_, started_, done_, etc.) is shared, concurrent calls + // state (task_ptr_, claim_, done_, etc.) is shared, concurrent calls // must be serialized. std::mutex dispatch_mtx_; @@ -65,14 +69,14 @@ class CPUThreadPool : public ThreadPoolBackend { std::condition_variable cv_; const std::function* task_ptr_ = nullptr; - std::atomic task_n_threads_{0}; - std::atomic started_{0}; + // 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 task_gen_{0}; std::atomic sleeping_count_{0}; // workers currently in cv_.wait - bool stop_ = false; + std::atomic stop_{false}; // The first exception any slot of the current parallel_for threw. std::mutex error_mtx_; diff --git a/tests/highway_threading_tests.cpp b/tests/highway_threading_tests.cpp index c16ab2b420..4e6292a3c4 100644 --- a/tests/highway_threading_tests.cpp +++ b/tests/highway_threading_tests.cpp @@ -13,8 +13,13 @@ using namespace mlx::core; #include #include +#include #include #include +#include +#include +#include +#include #include #include @@ -189,3 +194,235 @@ TEST_CASE("highway pool size agrees with the thread configuration") { // 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"); + } +} From 8469702fc411b55c534e760789597e988e238d0e Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:41:19 +0200 Subject: [PATCH 37/65] Read each lane as C++ does when a vector becomes Simd The facade built Simd from a vector with Highway's MaskFromVec, which Highway defines only for lanes of all zeros or all ones. x86 reads each lane's top bit, and NEON one bit per lane, bit i of lane i, so on x86 a nonzero lane with its top bit clear read as false. Compare each lane with zero, as static_cast does. A test checks every lane, for 8, 32 and 64-bit lanes. --- mlx/backend/cpu/simd/highway_simd.h | 8 ++- tests/CMakeLists.txt | 6 ++ tests/highway_simd_tests.cpp | 89 +++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 tests/highway_simd_tests.cpp diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index b55b8d1b4d..5570d70207 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -177,9 +177,15 @@ struct BoolSimdBase { 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; - hn::StoreMaskBits(d, hn::MaskFromVec(value.value), bits); + // 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 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 560d9a43b8..98893a901e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -55,6 +55,12 @@ if(MLX_BUILD_CPU AND MLX_USE_HIGHWAY) 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) diff --git a/tests/highway_simd_tests.cpp b/tests/highway_simd_tests.cpp new file mode 100644 index 0000000000..5aa98fd53a --- /dev/null +++ b/tests/highway_simd_tests.cpp @@ -0,0 +1,89 @@ +// 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; + +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); +} From 35e3d6a731223e71a92518b4f31bc5313955f725 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:32:34 +0200 Subject: [PATCH 38/65] Tell cores apart by the CPUs they hold, not by core_id The pool's default counted distinct (physical_package_id, core_id) pairs, but core_id is not unique within a package on every kernel. x86 kernels from 5.3 until a fix in 6.1 (later also in 5.10 and 5.15) number cores per die on CPUs that report dies in CPUID leaf 0x1F, and since Linux 6.0 device-tree systems restart core_id in each cluster of a package. Cores that shared a pair counted once, so the pool came out smaller than the machine. Key each core by its package and the first CPU of its core_cpus_list (thread_siblings_list before Linux 5.3), read under a root that tests point at a synthetic tree. On AMD family 15h the kernel lists the two cores of a compute unit together, so the pool counts compute units. --- mlx/backend/cpu/threading/config.cpp | 37 +++++++++++-------- mlx/backend/cpu/threading/config.h | 9 +++-- tests/highway_threading_tests.cpp | 54 ++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 17 deletions(-) diff --git a/mlx/backend/cpu/threading/config.cpp b/mlx/backend/cpu/threading/config.cpp index d93a9b7bda..46f62dfb18 100644 --- a/mlx/backend/cpu/threading/config.cpp +++ b/mlx/backend/cpu/threading/config.cpp @@ -90,6 +90,25 @@ int count_physical_cores( 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) { @@ -167,20 +186,6 @@ std::vector allowed_cpus() { return cpus; } -std::optional> sysfs_topology(int cpu) { - const std::string base = - "/sys/devices/system/cpu/cpu" + std::to_string(cpu) + "/topology/"; - std::ifstream core_file(base + "core_id"); - int core = 0; - int package = 0; - if (!(core_file >> core)) { - return std::nullopt; - } - std::ifstream package_file(base + "physical_package_id"); - package_file >> package; - return std::make_pair(package, core); -} - std::string read_file(const char* path) { std::ifstream in(path); std::ostringstream text; @@ -195,7 +200,9 @@ const ThreadConfig& thread_config() { ThreadConfig resolved = detail::resolve_thread_config( std::getenv("MLX_CPU_THREADS"), allowed_cpus(), - sysfs_topology, + [](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) diff --git a/mlx/backend/cpu/threading/config.h b/mlx/backend/cpu/threading/config.h index 5cae3c78eb..406c5e4188 100644 --- a/mlx/backend/cpu/threading/config.h +++ b/mlx/backend/cpu/threading/config.h @@ -43,12 +43,17 @@ MLX_API std::optional parse_thread_count( // 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 (package, core) pairs among `cpus`. A CPU with no topology counts as -// a core of its own. +// 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( diff --git a/tests/highway_threading_tests.cpp b/tests/highway_threading_tests.cpp index 4e6292a3c4..7e093963bd 100644 --- a/tests/highway_threading_tests.cpp +++ b/tests/highway_threading_tests.cpp @@ -86,6 +86,60 @@ TEST_CASE("highway physical cores are counted within the affinity mask") { 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); From 814aef88e705c23fee9d5232fd9b2a49db2a3e07 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:24:56 +0200 Subject: [PATCH 39/65] Test the mxfp8 decode at every Highway target At every target the CPU runs, a matmul whose mxfp8 weights hold 0x7F and 0xFF gives NaN in exactly the outputs of those weight rows, every other output equals the one dequantize gives, and so does every finite code times an identity matrix; the test checks, for each matmul, that the kernel ran at that target. Highway widens float16 natively at some targets and by emulation at others. This case and the rms_norm one now unpin the targets however they end, so that no later case runs pinned. --- tests/highway_info_tests.cpp | 82 ++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/highway_info_tests.cpp b/tests/highway_info_tests.cpp index 38499f3a85..8fba2eed1d 100644 --- a/tests/highway_info_tests.cpp +++ b/tests/highway_info_tests.cpp @@ -28,6 +28,14 @@ float relative_error(const array& got, const array& reference) { 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") { @@ -40,6 +48,7 @@ TEST_CASE("highway info names what was compiled and what the CPU supports") { } 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)); @@ -56,7 +65,80 @@ TEST_CASE("highway rms_norm records the target that ran, on every 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") { From 3b95ae3c3e206a941454f7f62c798c50566fe6ff Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:55:00 +0200 Subject: [PATCH 40/65] Return early from #3019's CPU kernels for an empty array #3019's threaded loops for strided binary ops, general copies and strided unary ops, and its native RMSNorm and LayerNorm, divide an element count by an inner extent, which is 0 for an empty array that keeps a zero-sized dimension through the collapse, or for a norm's input whose last dimension is 0. Integer division by zero traps on x86-64; MLX's own code runs zero times there, or composes the norms from other ops. Return first when there are no elements; the unary loop gets the same guard, though no op is known to reach it. A test runs each case on the CPU: on x86-64, the binary and copy loops and both norms crashed with SIGFPE. --- mlx/backend/cpu/binary.h | 3 +++ mlx/backend/cpu/copy.cpp | 3 +++ mlx/backend/cpu/norms.cpp | 6 ++++++ mlx/backend/cpu/unary.h | 3 +++ tests/ops_tests.cpp | 24 ++++++++++++++++++++++++ 5 files changed, 39 insertions(+) diff --git a/mlx/backend/cpu/binary.h b/mlx/backend/cpu/binary.h index b053e0fb48..e53ceeb4ff 100644 --- a/mlx/backend/cpu/binary.h +++ b/mlx/backend/cpu/binary.h @@ -175,6 +175,9 @@ void binary_op_dispatch_dims( a_it.step(); b_it.step(); #else + if (size == 0) { + return; + } int64_t num_iterations = size / stride; // Check if parallelization is beneficial diff --git a/mlx/backend/cpu/copy.cpp b/mlx/backend/cpu/copy.cpp index 2aaa7bdae1..59159e3c32 100644 --- a/mlx/backend/cpu/copy.cpp +++ b/mlx/backend/cpu/copy.cpp @@ -130,6 +130,9 @@ void copy_general_general( in.step(); out.step(); #else + if (size == 0) { + return; + } int64_t num_iterations = size / stride; // Check if parallelization is beneficial diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp index 87235b01a7..f3954beb13 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -495,6 +495,9 @@ void RMSNorm::eval_cpu( 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; @@ -657,6 +660,9 @@ void LayerNorm::eval_cpu( 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; diff --git a/mlx/backend/cpu/unary.h b/mlx/backend/cpu/unary.h index 6707165019..4a0e870ce0 100644 --- a/mlx/backend/cpu/unary.h +++ b/mlx/backend/cpu/unary.h @@ -108,6 +108,9 @@ void unary_op(const array& a, array& out, Op) { it.step(); #else + if (a.size() == 0) { + return; + } size_t num_iterations = a.size() / inner_shape; // Check if parallelization is beneficial diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index a9d85f4813..503d5c1ee5 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4931,3 +4931,27 @@ TEST_CASE( 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()); +} From 204dd3ce2dbc3450b35e209e9ccc5fb58c277176 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:02:14 +0200 Subject: [PATCH 41/65] Widen float16 sums and products under Highway MLX 0.32.3 (#4387) sums and multiplies float16 in float only where the SIMD width is 1, since wider float16 vectors are faster in float16. The Highway facade computes float16 lanes in float, so its strided and general reductions gained nothing from float16 and rounded every step: sum(ones({4096, 8}, float16), 0) gave 2048 per column, where a Linux build without Highway gives 4096. Widen float16 for sum and product under Highway, whatever the width. A test sums and multiplies float16 columns whose exact results float16 steps cannot reach. --- mlx/backend/cpu/reduce.cpp | 7 +++++++ tests/highway_kernel_tests.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index bcf3bd2f90..b8332c064d 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -74,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; }; diff --git a/tests/highway_kernel_tests.cpp b/tests/highway_kernel_tests.cpp index 0c685a0c77..b0709865a9 100644 --- a/tests/highway_kernel_tests.cpp +++ b/tests/highway_kernel_tests.cpp @@ -175,6 +175,32 @@ TEST_CASE("highway fp16 sum keeps each thread's partial in float") { 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. From eeae4258ab382d462206232146c045dfef465f72 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:38:58 +0200 Subject: [PATCH 42/65] Keep the norms' input copy alive until their tasks run #3019's RMSNorm and LayerNorm copy an input that has gaps or a last stride other than 1, then dispatch tasks that read the copy through a raw pointer. Nothing registers the copy with the encoder, so it is freed when eval_cpu returns, while the copy task and the norm task may still be queued. The CPU allocator puts a freed buffer back in its cache, where a new allocation can take it while those tasks still use it, and ASan never sees the free. With the cache off, ASan reports it. At the old #18 tree, whose norms.cpp differs from this commit's parent only by the empty-array guards, this commit's test failed under ASan in 5 of 5 runs, the free coming from RMSNorm::eval_cpu's return: ==3417==ERROR: AddressSanitizer: heap-use-after-free on address 0xffff6b215208 at pc 0xaaaad788d1ec bp 0xffff6bbee3a0 sp 0xffff6bbee3b8 WRITE of size 4 at 0xffff6b215208 thread T13 With only RMSNorm fixed, 5 of 5 runs reported the same from LayerNorm::eval_cpu. Register the copy as a temporary, as MLX's logsumexp does; then 5 of 5 runs report nothing. The test turns the buffer cache off and compares both norms of a transposed input with the norms of its contiguous copy, 50 times. --- mlx/backend/cpu/norms.cpp | 2 ++ tests/ops_tests.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp index f3954beb13..90395c8b04 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -486,6 +486,7 @@ void RMSNorm::eval_cpu( 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 @@ -651,6 +652,7 @@ void LayerNorm::eval_cpu( 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 diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 503d5c1ee5..90a77b269d 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4955,3 +4955,41 @@ TEST_CASE("test empty arrays in the Highway CPU kernels") { CHECK(l.shape() == Shape{3, 0}); CHECK(array_equal(l, x, cpu).item()); } + +TEST_CASE("test norms of a non-contiguous input") { + // A transposed input makes the native norms copy it; with no buffer cache, a + // copy freed before its tasks run is freed for real, which ASan reports. + struct RestoreCacheLimit { + size_t limit; + ~RestoreCacheLimit() { + set_cache_limit(limit); + } + } 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()); + } +} From 75f1ceb04f254c19f45d1211afe972d8967f224e Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:59:38 +0200 Subject: [PATCH 43/65] Copy the norms' weight and bias when their stride is not 1 #3019's native RMSNorm and LayerNorm read weight and bias through plain pointers with stride 1. fast::rms_norm and fast::layer_norm pass a weight or bias that has the output type as it is, and cast any other, and the cast keeps a broadcast's stride 0: a broadcast stays flagged contiguous, so AsType copies it as a vector, strides and all. So a broadcast (stride 0) of any type, or a stepped slice (stride 2) of the output type, reaches these kernels, which then read the wrong elements. For a broadcast of a single value they read past its one-element buffer (from the code, not run). Metal and CUDA pass each stride to their kernels. Without this fix, on x86-64 with Highway, this commit's test failed all six of its checks, for a broadcast and a stepped weight and bias, each as the first one did: tests/ops_tests.cpp:5025: ERROR: CHECK( array_equal( fast::rms_norm(x, p, 1e-5f, cpu), fast::rms_norm(x, pc, 1e-5f, cpu), cpu) .item() ) is NOT correct! values: CHECK( false ) A build without Highway composes the norms from other ops, and passed all six. Copy a weight or bias whose stride is not 1, as the norms already copy an input they cannot read with its strides, and register the copy with the encoder. The test turns the CPU buffer cache off, as the test before it does, and compares rms_norm and layer_norm with each strided weight or bias against the same norm with its contiguous copy. --- mlx/backend/cpu/norms.cpp | 20 ++++++++++++-- tests/ops_tests.cpp | 58 +++++++++++++++++++++++++++++++++------ 2 files changed, 67 insertions(+), 11 deletions(-) diff --git a/mlx/backend/cpu/norms.cpp b/mlx/backend/cpu/norms.cpp index 90395c8b04..04343d1111 100644 --- a/mlx/backend/cpu/norms.cpp +++ b/mlx/backend/cpu/norms.cpp @@ -479,7 +479,7 @@ void RMSNorm::eval_cpu( return; } auto& in_x = inputs[0]; - auto& weight = inputs[1]; + array weight = inputs[1]; auto& out = outputs[0]; // Non-contiguous inputs are copied to contiguous layout @@ -504,6 +504,11 @@ void RMSNorm::eval_cpu( 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); @@ -644,8 +649,8 @@ void LayerNorm::eval_cpu( return; } auto& in_x = inputs[0]; - auto& weight = inputs[1]; - auto& bias = inputs[2]; + array weight = inputs[1]; + array bias = inputs[2]; auto& out = outputs[0]; // Non-contiguous inputs are copied to contiguous layout @@ -671,6 +676,15 @@ void LayerNorm::eval_cpu( 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); diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 90a77b269d..cef5cdacee 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -4956,15 +4956,20 @@ TEST_CASE("test empty arrays in the Highway CPU kernels") { 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; with no buffer cache, a - // copy freed before its tasks run is freed for real, which ASan reports. - struct RestoreCacheLimit { - size_t limit; - ~RestoreCacheLimit() { - set_cache_limit(limit); - } - } restore{set_cache_limit(0)}; + // 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]() { @@ -4993,3 +4998,40 @@ TEST_CASE("test norms of a non-contiguous input") { .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()); + } +} From b64de7ad971804c225a600fde09cb4a88efe0683 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:03:48 +0200 Subject: [PATCH 44/65] Copy rope's offsets and freqs when their stride is not 1 #3019's native RoPE reads offsets and freqs through plain pointers with stride 1. fast::rope casts the offsets only when they are not 4 bytes wide, and the freqs to float32, and neither cast changes a broadcast's stride. So broadcast offsets or freqs (stride 0), or stepped ones (stride 2) that need no cast, reach this kernel, which then reads the wrong positions or frequencies. For a broadcast of a single value it reads past its one-element buffer (from the code, not run). Metal and CUDA pass both strides to their kernels. Without this fix, on x86-64 with Highway, this commit's test failed all four of its checks, for broadcast and stepped offsets and freqs, each as the first one did: tests/ops_tests.cpp:5056: ERROR: 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() ) is NOT correct! values: CHECK( false ) A build without Highway composes rope from other ops, and passed all four. Copy offsets or freqs whose stride is not 1, as rope already copies an input that it cannot read with its strides, and register the copy with the encoder. The test turns the CPU buffer cache off and compares rope with each strided offsets or freqs against rope with its contiguous copy. --- mlx/backend/cpu/rope.cpp | 19 ++++++++++++++++--- tests/ops_tests.cpp | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/mlx/backend/cpu/rope.cpp b/mlx/backend/cpu/rope.cpp index 83a07e41ce..609f5005e2 100644 --- a/mlx/backend/cpu/rope.cpp +++ b/mlx/backend/cpu/rope.cpp @@ -498,16 +498,29 @@ void RoPE::eval_cpu( out.set_data(allocator::malloc(out.nbytes())); // Get offset - auto& offset_arr = inputs[1]; + 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(inputs[2]); + encoder.set_input_array(*freqs); } encoder.set_output_array(out); if (made_copy) { @@ -533,7 +546,7 @@ void RoPE::eval_cpu( using DType = decltype(dummy); const DType* x_ptr = x.data(); const int* off_ptr = offset_arr.data(); - const float* freq_ptr = has_freqs ? inputs[2].data() : nullptr; + const float* freq_ptr = has_freqs ? freqs->data() : nullptr; DType* out_ptr = out.data(); encoder.dispatch([=, &pool]() { diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index cef5cdacee..d96d40526f 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -5035,3 +5035,40 @@ TEST_CASE("test norms of a strided weight and bias") { .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()); + } +} From e8725f033ad0434b144b7a5f56a1ee3072fc730a Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:07:48 +0200 Subject: [PATCH 45/65] Copy sdpa's sinks when they are not row-contiguous #3019's native ScaledDotProductAttention passes the sinks to its kernels as they are, as if they were always contiguous, and the Highway kernel reads sinks[h] through a plain pointer with stride 1 (sdpa_highway.cpp:373). fast::scaled_dot_product_attention only casts the sinks to the output type (fast.cpp:924), and the cast keeps a broadcast's stride 0. So broadcast sinks (stride 0), or stepped ones (stride 2) that need no cast, reach this kernel, which then reads the wrong sink values. For a broadcast of a single value it reads past its one-element buffer (from the code, not run). Without this fix, on x86-64 with Highway, this commit's test failed both of its checks, for broadcast and stepped sinks, each as the first one did: tests/ops_tests.cpp:5102: ERROR: 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() ) is NOT correct! values: CHECK( false ) A build without Highway composes the attention from other ops, and passed both. Copy sinks that are not row-contiguous, as the function already copies q, k, v and the mask, and register the copy with the encoder. The test turns the CPU buffer cache off and compares sdpa with each strided sinks array against sdpa with its contiguous copy. --- mlx/backend/cpu/sdpa.cpp | 10 +++++++--- tests/ops_tests.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp index 5332fd5447..bdc3f9b83c 100644 --- a/mlx/backend/cpu/sdpa.cpp +++ b/mlx/backend/cpu/sdpa.cpp @@ -808,9 +808,10 @@ void ScaledDotProductAttention::eval_cpu( ? std::optional(ensure_contiguous(inputs[3])) : std::nullopt; - // Sinks is 1D (n_q_heads,), always contiguous - auto sinks_arr = - has_sinks_ ? std::optional(inputs.back()) : 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); @@ -847,6 +848,9 @@ void ScaledDotProductAttention::eval_cpu( 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_; diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index d96d40526f..e8a41764ef 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -5072,3 +5072,33 @@ TEST_CASE("test rope with strided offsets and freqs") { .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()); + } +} From 1adba0acd1e15c4d2750df788546491c7b77b453 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:34:54 +0200 Subject: [PATCH 46/65] Reject an unquantized weight in QQMatmul under Highway Without Highway, the CPU QQMatmul supports only a quantized w and one row of x, and throws "[QQMatmul] NYI for the general case" for any other input. qqmm passes an unquantized w as {x, w}, or with nvfp4 global scales as {x, w, global_scale_x, global_scale_w}; QQMatmul::vjp builds both. It also accepts scales with an unquantized w, since it checks the scales only for a quantized one. #3019's QQMatmul, which Highway builds use, has no path for a w that it must quantize: it reads inputs[2] as the packed scales and w as packed values in every case. So with scales, it computes from the wrong data. With global scales only, it takes global_scale_x, one float32, as the scales and reads N*K/16 bytes from it, for an N by K w (from the code, not run). With {x, w} only, it reads inputs[2], past the end of its inputs. Without this fix, on x86-64 with Highway, this commit's test failed its checks with scales and with global scales, and then crashed in its check of {x, w} only: tests/ops_tests.cpp:5127: ERROR: CHECK_THROWS_WITH_AS( sum(with_scales, cpu).item(), "[QQMatmul] NYI for the general case", std::runtime_error ) did NOT throw at all! tests/ops_tests.cpp:5141: ERROR: CHECK_THROWS_WITH_AS( sum(with_global_scales, cpu).item(), "[QQMatmul] NYI for the general case", std::runtime_error ) did NOT throw at all! tests/ops_tests.cpp:5106: FATAL ERROR: test case CRASHED: SIGSEGV - Segmentation violation signal A build without Highway passed all three checks. Throw the same error for any unquantized w, with or without scales or global scales, before anything reads the inputs, as the CPU code without Highway does. More than one row of x, which that code refuses, stays supported (from the code; no test covers it). The test sums each result before it reads a value, so that the matmul runs, and checks for that exact error. --- mlx/backend/cpu/quantized_highway_backend.cpp | 4 ++ tests/ops_tests.cpp | 52 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 7ea049aa07..3da4f75518 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -2711,6 +2711,10 @@ void fast::ConvertFP8::eval_cpu( } void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { + // 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) { diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index e8a41764ef..a06fa21b50 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -5102,3 +5102,55 @@ TEST_CASE("test sdpa with strided sinks") { .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); +} From 1d7f24786c333534a2c6176fd1f558e0cf844324 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:38:53 +0200 Subject: [PATCH 47/65] Take sdpa's composed path when keys and values differ in length fast::scaled_dot_product_attention checks that keys and values have the same number of heads (fast.cpp:790), but not the same length. Without Highway, the composed path then raises an error, since its matmul of the scores and the values checks their shapes as the graph is built (fast.cpp:886, ops.cpp:3506). With Highway, use_fallback sends such inputs to #3019's native kernel, which uses the keys' length for the values too (sdpa_highway.cpp:366), so it reads past the end of shorter values, and the wrong rows of longer ones (both read from the code, not run). Without this fix, on x86-64 with Highway, this commit's test failed its only check: tests/ops_tests.cpp:5168: ERROR: CHECK_THROWS_AS( fast::scaled_dot_product_attention( q, k, v, 0.0625f, "", std::nullopt, std::nullopt, false, cpu), std::invalid_argument ) did NOT throw at all! A build without Highway composes the attention, and passed. Send keys and values of different lengths to the composed path, which then raises its error as it does without Highway, and add the same condition to the kernel's own guard. The test builds sdpa with values shorter than the keys and checks that this raises std::invalid_argument before anything is evaluated. --- mlx/backend/cpu/sdpa.cpp | 9 +++++---- mlx/backend/no_gpu/primitives.cpp | 6 ++++-- tests/ops_tests.cpp | 13 +++++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/mlx/backend/cpu/sdpa.cpp b/mlx/backend/cpu/sdpa.cpp index bdc3f9b83c..5bc998d092 100644 --- a/mlx/backend/cpu/sdpa.cpp +++ b/mlx/backend/cpu/sdpa.cpp @@ -770,11 +770,12 @@ void ScaledDotProductAttention::eval_cpu( "[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) { + 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 one head " - "dimension of at most 256 for queries, keys and values. This should " - "have been caught by use_fallback."); + "[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) diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index 13847bd841..b4cdd7e24b 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -36,11 +36,13 @@ bool fast::ScaledDotProductAttention::use_fallback( 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. + // 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) { + q.shape(-1) == v.shape(-1) && q.shape(-1) <= 256 && + k.shape(-2) == v.shape(-2)) { return false; } #endif // MLX_USE_HIGHWAY_KERNELS diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index a06fa21b50..d8e6dacffd 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -5154,3 +5154,16 @@ TEST_CASE("test qqmm with an unquantized weight") { "[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); +} From f3b3b94e5b510fb6cbb20db4c22207029a4a54b8 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:11:10 +0200 Subject: [PATCH 48/65] Bound sdpa's per-lane buffers at compile time #3019's native sdpa kernel keeps four buffers of 16 floats (dots, exp_arr and tmp in sdpa_single_head, v_tmp in sdpa_accum_values), each for one float vector of hn::Lanes(df) lanes, but nothing states that limit. It holds on every target built today: Highway builds only for x86-64, whose float vectors have 4, 8 or 16 lanes, and #18, which adds Linux arm64, disables every SVE target. A wider target, such as SVE with vectors of more than 512 bits, would overrun the buffers without a sign. GCC's Release builds also warn at the tail loop that fills dots, 15 times with GCC 12 (once per target from AVX2 to AVX3_SPR and per type) and 12 times with GCC 11: mlx/backend/cpu/sdpa_highway.cpp:229:29: warning: iteration 2147483634 invokes undefined behavior [-Waggressive-loop-optimizations] The warning is a false positive: those targets have 8 or 16 lanes, a multiple of four, so the tail loop runs zero times. GCC Debug builds and Clang do not warn. Size the four buffers by one constant, kMaxLanes, and check at compile time that hn::MaxLanes is at most kMaxLanes, so that a wider target fails to compile instead. Start the tail loop at lanes / 4 * 4, where the loop over four rows stops, so that GCC can see its range. The warning goes, and the kernel computes the same values. --- mlx/backend/cpu/sdpa_highway.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/mlx/backend/cpu/sdpa_highway.cpp b/mlx/backend/cpu/sdpa_highway.cpp index c015feca72..41190127a1 100644 --- a/mlx/backend/cpu/sdpa_highway.cpp +++ b/mlx/backend/cpu/sdpa_highway.cpp @@ -34,6 +34,12 @@ 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; @@ -170,7 +176,7 @@ void sdpa_accum_values( } else { const int remaining = head_dim - offset; for (int r = 0; r < rows; ++r) { - alignas(64) float v_tmp[16] = {}; + alignas(64) float v_tmp[kMaxLanes] = {}; for (int j = 0; j < remaining; ++j) { v_tmp[j] = static_cast(values[r * head_dim + offset + j]); } @@ -220,12 +226,11 @@ void sdpa_single_head( int s = 0; for (; s + lanes <= effective_len; s += lanes) { - alignas(64) float dots[16]; - int b = 0; - for (; b + 4 <= lanes; b += 4) { + 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 (; b < lanes; ++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); } @@ -248,7 +253,7 @@ void sdpa_single_head( 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[16]; + alignas(64) float exp_arr[kMaxLanes]; hn::StoreU(vexp, df, exp_arr); for (int b = 0; b < lanes; b += 4) { sdpa_accum_values( @@ -307,7 +312,7 @@ void sdpa_single_head( if (i * lanes + lanes <= head_dim) { store_f32_as_typed(df, result, output, i * lanes); } else { - alignas(64) float tmp[16]; + alignas(64) float tmp[kMaxLanes]; hn::StoreU(result, df, tmp); const int remaining = head_dim - i * lanes; for (int j = 0; j < remaining; ++j) { From ca35adaa6a58f4589c24f2452ec9ce99f3eb4e88 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:31:17 +0100 Subject: [PATCH 49/65] Add convert_in_range for Highway vectors The CPU float-to-integer saturation calls convert_in_range on Simd in math.h's sincos. highway_simd.h had no vector overload, so a Linux build with MLX_USE_HIGHWAY did not compile once both were present. The overload uses the vector's own converting constructor, as the Highway build did before at this place. --- mlx/backend/cpu/simd/highway_simd.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 5570d70207..a76718e29b 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -1031,5 +1031,16 @@ 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(); From a4d45df0a8ccfbb6772bcbf77e65029b61ba284e Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:51:23 +0100 Subject: [PATCH 50/65] Saturate float to integer conversions in the Highway Simd type Highway's ConvertTo gives a target-dependent result for NaN, and the fallback for lanes of different sizes used a plain cast. Both now give the result of saturating_cast, as the other Simd backends do. --- mlx/backend/cpu/simd/highway_simd.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index a76718e29b..968b30c0af 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -282,7 +282,13 @@ struct Simd { !highway_detail::is_half_v && !highway_detail::is_half_v && !std::is_same_v && !std::is_same_v && sizeof(T) == sizeof(U)) { - value = hn::ConvertTo(D(), other.value); + 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( @@ -294,7 +300,7 @@ struct Simd { alignas(64) T tmp_out[N]; other.store(tmp_in); for (int i = 0; i < N; ++i) { - tmp_out[i] = static_cast(tmp_in[i]); + tmp_out[i] = saturating_cast(tmp_in[i]); } value = load(tmp_out).value; } From 74477bb5f798376214b75db8dd536f2e1aba1b4a Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:52:10 +0100 Subject: [PATCH 51/65] Take the sum order of the Highway Simd type in the block sum tests Highway builds reduce with their own lane count and order. Also cover rms_norm over a long row. --- tests/ops_tests.cpp | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 8a8df54be5..3864bba355 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -11,6 +11,9 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/simd/base_simd.h" +#if defined(MLX_USE_HIGHWAY_KERNELS) +#include "mlx/backend/cpu/simd/simd.h" +#endif #include "mlx/backend/cuda/cuda.h" #include "mlx/mlx.h" #include "mlx/primitives.h" @@ -7637,7 +7640,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) +constexpr int sum_lanes = mlx::core::simd::max_size; +#elif defined(MLX_USE_ACCELERATE) && !defined(__x86_64__) constexpr int sum_lanes = 8; #else constexpr int sum_lanes = 1; @@ -7654,12 +7659,17 @@ float lane_order_sum(const std::vector& x) { lanes[j] = lanes[j] + x[i + j]; } } +#if defined(MLX_USE_HIGHWAY_KERNELS) + float total = + mlx::core::simd::sum(mlx::core::simd::load(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]; } @@ -7777,6 +7787,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; From 5e52728f8826a3f9c49acf4b582e78ceff0c90bb Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:54:42 +0100 Subject: [PATCH 52/65] Keep the Highway Simd type out of ops_tests.cpp simd.h declares a global bfloat16_t on arm64, which is ambiguous there. --- tests/highway_simd_tests.cpp | 9 +++++++++ tests/ops_tests.cpp | 13 ++++++------- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/highway_simd_tests.cpp b/tests/highway_simd_tests.cpp index 5aa98fd53a..95fe571902 100644 --- a/tests/highway_simd_tests.cpp +++ b/tests/highway_simd_tests.cpp @@ -13,6 +13,15 @@ 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. diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 3864bba355..e75016483e 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -11,9 +11,6 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/simd/base_simd.h" -#if defined(MLX_USE_HIGHWAY_KERNELS) -#include "mlx/backend/cpu/simd/simd.h" -#endif #include "mlx/backend/cuda/cuda.h" #include "mlx/mlx.h" #include "mlx/primitives.h" @@ -7641,7 +7638,10 @@ 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_HIGHWAY_KERNELS) -constexpr int sum_lanes = mlx::core::simd::max_size; +// 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); +const int sum_lanes = highway_float_lanes(); #elif defined(MLX_USE_ACCELERATE) && !defined(__x86_64__) constexpr int sum_lanes = 8; #else @@ -7651,7 +7651,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) { @@ -7660,8 +7660,7 @@ float lane_order_sum(const std::vector& x) { } } #if defined(MLX_USE_HIGHWAY_KERNELS) - float total = - mlx::core::simd::sum(mlx::core::simd::load(lanes.data())); + float total = highway_reduce_sum(lanes.data()); #else for (int n = N / 2; n >= 1; n /= 2) { for (int j = 0; j < n; j++) { From 2916b318c67def3ba3937b5a2a7e7d8be7bd274c Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:56:38 +0100 Subject: [PATCH 53/65] Declare the Highway test hooks outside the anonymous namespace --- tests/ops_tests.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index e75016483e..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); @@ -7638,9 +7644,6 @@ 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_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); const int sum_lanes = highway_float_lanes(); #elif defined(MLX_USE_ACCELERATE) && !defined(__x86_64__) constexpr int sum_lanes = 8; From a430b14e6a5942180f7e1023a5e24008998ca283 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:59:07 +0100 Subject: [PATCH 54/65] Sum long rows in blocks in the Highway norm kernels Highway builds have their own LayerNorm and RMSNorm kernels. They now sum as the CPU reductions do. --- mlx/backend/cpu/norms_highway.cpp | 250 +++++++++++++++++------------- 1 file changed, 139 insertions(+), 111 deletions(-) diff --git a/mlx/backend/cpu/norms_highway.cpp b/mlx/backend/cpu/norms_highway.cpp index eeda814a0f..d9809a6236 100644 --- a/mlx/backend/cpu/norms_highway.cpp +++ b/mlx/backend/cpu/norms_highway.cpp @@ -6,6 +6,7 @@ // 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" @@ -30,6 +31,9 @@ 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, @@ -43,30 +47,34 @@ void rms_norm_row_f32( const int lanes = static_cast(hn::Lanes(d)); float total = 0.0f; int i = 0; - 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 <= width; 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 <= width; i += lanes) { - const V vals = hn::LoadU(d, x + i); - sum_sq = hn::MulAdd(vals, vals, sum_sq); - } + 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); + } - total = hn::ReduceSum(d, sum_sq); - for (; i < width; ++i) { - total += x[i] * x[i]; + 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); @@ -107,31 +115,35 @@ void rms_norm_row_half( const int lanes = static_cast(hn::Lanes(d)); float total = 0.0f; int i = 0; - 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 <= width; 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 <= width; i += lanes) { - const V vals = load_typed_as_f32(d, x, i); - sum_sq = hn::MulAdd(vals, vals, sum_sq); - } + 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); + } - total = hn::ReduceSum(d, sum_sq); - for (; i < width; ++i) { - const float val = static_cast(x[i]); - total += val * val; + 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); @@ -172,46 +184,54 @@ void layer_norm_row_f32( using V = hn::Vec; const int lanes = static_cast(hn::Lanes(d)); - V sum0 = hn::Zero(d); - V sum1 = hn::Zero(d); - + float total = 0.0f; int i = 0; - for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { - sum = hn::Add(sum, hn::LoadU(d, x + i)); - } + 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 total = hn::ReduceSum(d, sum); - for (; i < width; ++i) { - total += 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); - V variance_sum0 = hn::Zero(d); - V variance_sum1 = hn::Zero(d); - + float variance = 0.0f; i = 0; - for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { - const V diff = hn::Sub(hn::LoadU(d, x + i), vmean); - variance_sum = hn::MulAdd(diff, diff, variance_sum); - } + 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 variance = hn::ReduceSum(d, variance_sum); - for (; i < width; ++i) { - const float diff = x[i] - mean; - variance += diff * diff; + float block = hn::ReduceSum(d, variance_sum); + for (; i < end; ++i) { + const float diff = x[i] - mean; + block += diff * diff; + } + variance += block; } variance /= width; @@ -256,46 +276,54 @@ void layer_norm_row_half( using V = hn::Vec; const int lanes = static_cast(hn::Lanes(d)); - V sum0 = hn::Zero(d); - V sum1 = hn::Zero(d); - + float total = 0.0f; int i = 0; - for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { - sum = hn::Add(sum, load_typed_as_f32(d, x, i)); - } + 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 total = hn::ReduceSum(d, sum); - for (; i < width; ++i) { - total += static_cast(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); - V variance_sum0 = hn::Zero(d); - V variance_sum1 = hn::Zero(d); - + float variance = 0.0f; i = 0; - for (; i + 2 * lanes <= width; 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 <= width; i += lanes) { - const V diff = hn::Sub(load_typed_as_f32(d, x, i), vmean); - variance_sum = hn::MulAdd(diff, diff, variance_sum); - } + 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 variance = hn::ReduceSum(d, variance_sum); - for (; i < width; ++i) { - const float diff = static_cast(x[i]) - mean; - variance += diff * diff; + 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; From 97c141ce0ab4075f1f25e79bae03afd753478c2a Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:02:51 +0100 Subject: [PATCH 55/65] Test an E8M0 scale of 0xFF in Highway builds --- tests/highway_quantized_tests.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/highway_quantized_tests.cpp b/tests/highway_quantized_tests.cpp index bc86cf8456..2d51a699e2 100644 --- a/tests/highway_quantized_tests.cpp +++ b/tests/highway_quantized_tests.cpp @@ -95,6 +95,19 @@ std::vector through_qqmm( } // 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. From a073c53b26814401458f3e57aef6de8a8b1f12f4 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:07:39 +0100 Subject: [PATCH 56/65] Decode an E8M0 scale of 0xFF as NaN in the Highway quantized code --- mlx/backend/cpu/quantized_highway.cpp | 4 +++- mlx/backend/cpu/quantized_highway_backend.cpp | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/mlx/backend/cpu/quantized_highway.cpp b/mlx/backend/cpu/quantized_highway.cpp index bf4d1457ff..a08225bae8 100644 --- a/mlx/backend/cpu/quantized_highway.cpp +++ b/mlx/backend/cpu/quantized_highway.cpp @@ -908,7 +908,9 @@ float dequantize_fp_scale( bfloat16_t f; uint16_t i; } out; - out.i = encoded == 0 ? 0x40 : (static_cast(encoded) << 7); + out.i = encoded == 0 + ? 0x40 + : (encoded == 0xFF ? 0x7FC0 : (static_cast(encoded) << 7)); return static_cast(out.f) * scale_factor; } } diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 3da4f75518..8637771301 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -172,7 +172,8 @@ static inline T dequantize_scale(uint8_t s) { uint16_t i; }; FOrI out; - out.i = (s == 0 ? 0x40 : (static_cast(s) << 7)); + out.i = (s == 0) ? 0x40 + : (s == 0xFF ? 0x7FC0 : (static_cast(s) << 7)); return static_cast(out.f); } } From 2536f9cd11c882b72b987febaa111d75c08a81cc Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:07:39 +0100 Subject: [PATCH 57/65] Return early from empty quantized matmuls in Highway builds K = 0 divided by zero, as in quantized.cpp before the same guard. --- mlx/backend/cpu/quantized_highway_backend.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 8637771301..40af1fcde6 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -2,6 +2,7 @@ #if defined(MLX_USE_HIGHWAY_KERNELS) // #3019's quantized.cpp: builds without Highway compile quantized.cpp instead. +#include #include #include #include @@ -2388,9 +2389,31 @@ void quantize_dequantize_fp_dispatch( } } +// 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) { + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return true; + } + if (x.shape(-1) != 0) { + return false; + } + out.set_data(allocator::malloc(out.nbytes())); + auto& encoder = cpu::get_command_encoder(stream); + encoder.set_output_array(out); + encoder.dispatch([out_ptr = out.data(), nbytes = out.nbytes()]() { + std::memset(out_ptr, 0, nbytes); + }); + return true; +} + } // namespace void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { + if (empty_qmm_cpu(inputs[0], out, stream())) { + return; + } auto& x_pre = inputs[0]; auto& w_pre = inputs[1]; auto& scales_pre = inputs[2]; @@ -2444,6 +2467,9 @@ 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())) { + return; + } auto& x_pre = inputs[0]; auto& w_pre = inputs[1]; auto& scales_pre = inputs[2]; From 5a644034f5c3ecf94440f7050438d1594eff45e0 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:07:39 +0100 Subject: [PATCH 58/65] Use the scalar integer divide and remainder in Highway's vector forms The scalar forms define y == 0 and INT_MIN / -1, which trap on x86-64. --- mlx/backend/cpu/simd/highway_simd.h | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 968b30c0af..53b691939c 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -552,8 +552,9 @@ MLX_HIGHWAY_ARITHMETIC(operator*, Mul) 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 static_cast(x / y); }); + 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 { @@ -563,13 +564,14 @@ inline Simd operator/(Simd a, Simd b) { } } -// As base_simd.h's divide: an integer quotient by zero is 0. Each lane divides -// as a scalar: hn::Div is implementation-defined for y == 0 and INT_MIN / -1. +// 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 y == 0 ? T(0) : static_cast(x / y); }); + return highway_detail::map_integer_binary(a, b, [](T x, T y) { + return divide(Simd(x), Simd(y)).value; + }); } else { return a / b; } @@ -884,17 +886,7 @@ 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) { - // As base_simd.h: a remainder by zero is the dividend. - if (y == 0) { - return x; - } - T r = static_cast(x % y); - if constexpr (std::is_signed_v) { - if (r != 0 && ((r < 0) != (y < 0))) { - r = static_cast(r + y); - } - } - return r; + return remainder(Simd(x), Simd(y)).value; }); } else { return highway_detail::map_binary(a, b, [](auto x, auto y) { From a275efd6cf62bc89d6cd7257c1a50d778a54767d Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:07:40 +0100 Subject: [PATCH 59/65] Use the scalar integer pow in Highway's vector form The scalar form multiplies with wraparound, without signed overflow. --- mlx/backend/cpu/simd/highway_simd.h | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/mlx/backend/cpu/simd/highway_simd.h b/mlx/backend/cpu/simd/highway_simd.h index 53b691939c..15a8e6a900 100644 --- a/mlx/backend/cpu/simd/highway_simd.h +++ b/mlx/backend/cpu/simd/highway_simd.h @@ -903,20 +903,7 @@ 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) { - T result = 1; - if constexpr (std::is_signed_v) { - if (y < 0) { - return T(0); - } - } - while (y) { - if (y & 1) { - result = static_cast(result * x); - } - y = static_cast(y >> 1); - x = static_cast(x * x); - } - return result; + return pow(Simd(x), Simd(y)).value; }); } else { return highway_detail::map_binary( From acf0c66976557f022258157b6adf116345d4a796 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:15:33 +0100 Subject: [PATCH 60/65] Return early from an empty qqmm in Highway builds K = 0 or N = 0 trapped on x86-64 with an integer division by zero. --- mlx/backend/cpu/quantized_highway_backend.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index 40af1fcde6..c526c2bd34 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -2738,6 +2738,9 @@ void fast::ConvertFP8::eval_cpu( } void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { + if (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"); From 6beda62b84ede3c5fbed0d1581b4c11b9fcd887d Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:18:24 +0100 Subject: [PATCH 61/65] Accumulate in float32 in the Highway affine quantized matmul The scalar paths (_qmm, _qmm_t_cols and _qmm_t's sequential loop) summed in the input type, as quantized.cpp did before ml-explore/mlx#4803. The SIMD and BLAS paths already sum in float32. --- mlx/backend/cpu/quantized_highway_backend.cpp | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index c526c2bd34..a60975db11 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -226,24 +226,26 @@ void _qmm( 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(result, result + N, 0); + std::fill(acc.begin(), acc.end(), 0.0f); for (int k = 0; k < K; k++) { - T* result_local = result; - T xi = *x++; + float* result_local = acc.data(); + float xi = *x++; for (int n = 0; n < N; n += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; + 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) { - T wl[pack_factor]; - extract_bits(w_local, wl); + 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); @@ -255,7 +257,7 @@ void _qmm( #pragma clang loop unroll(full) for (int p = 0; p < pack_factor; p++) { (*result_local++) += - xi * (scale * static_cast(wi & bitmask) + bias); + xi * (scale * static_cast(wi & bitmask) + bias); if (bits != 8) { wi >>= bits; } @@ -265,6 +267,7 @@ void _qmm( } } + std::copy(acc.begin(), acc.end(), result); result += N; } } @@ -300,19 +303,19 @@ void _qmm_t_cols( const T* scales_local = scales_base; const T* biases_local = biases_base; const T* x_local = x; - T sum = 0; + float sum = 0; // float32, as quantized.cpp since ml-explore/mlx#4803 for (int k = 0; k < K; k += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; + 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) { - T wl[pack_factor]; - extract_bits(w_local, wl); + float wl[pack_factor]; + extract_bits(w_local, wl); #pragma clang loop unroll(full) for (int p = 0; p < pack_factor; p++) { - sum += x_local[p] * (scale * wl[p] + bias); + sum += static_cast(x_local[p]) * (scale * wl[p] + bias); } w_local += bytes_per_pack; x_local += pack_factor; @@ -320,7 +323,7 @@ void _qmm_t_cols( uint8_t wi = *w_local++; #pragma clang loop unroll(full) for (int p = 0; p < pack_factor; p++) { - sum += (*x_local++) * (scale * static_cast(wi & bitmask) + bias); + sum += static_cast(*x_local++) * (scale * static_cast(wi & bitmask) + bias); if (bits != 8) { wi >>= bits; } @@ -399,18 +402,18 @@ void _qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0; // float32, as quantized.cpp since ml-explore/mlx#4803 for (int k = 0; k < K; k += group_size) { - T scale = *scales_local++; - T bias = *biases_local++; + 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) { - T wl[pack_factor]; - extract_bits(w_local, wl); + float wl[pack_factor]; + extract_bits(w_local, wl); #pragma clang loop unroll(full) for (int p = 0; p < pack_factor; p++) { - sum += x_local[p] * (scale * wl[p] + bias); + sum += static_cast(x_local[p]) * (scale * wl[p] + bias); } w_local += bytes_per_pack; x_local += pack_factor; @@ -418,8 +421,8 @@ void _qmm_t( uint8_t wi = *w_local++; #pragma clang loop unroll(full) for (int p = 0; p < pack_factor; p++) { - sum += (*x_local++) * - (scale * static_cast(wi & bitmask) + bias); + sum += static_cast(*x_local++) * + (scale * static_cast(wi & bitmask) + bias); if (bits != 8) { wi >>= bits; } From 35a2a85bc22dde2f2a8365b5915df5851132f4be Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:56:55 +0100 Subject: [PATCH 62/65] Keep the CPU on promoting quantized matmuls in Highway builds The CPU's mixed bf16/f16 quantized path (#11) is in quantized.cpp, which Highway builds do not compile. Their kernels read the f16 scales as bf16, so the mixed path gave wrong values. Highway builds now promote on the CPU as before, until the Highway kernels read f16 scales. --- mlx/ops.cpp | 6 ++++++ tests/quantized_stream_tests.cpp | 22 +++++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/mlx/ops.cpp b/mlx/ops.cpp index d8babb07b8..07854e1a36 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -4799,6 +4799,12 @@ namespace { // biases. CUDA's qmv reads them as the output type, so CUDA promotes. The // CPU shares Metal's shape conditions so the output dtype matches. bool reads_mixed_bf16_f16(const Stream& s) { +#if defined(MLX_USE_HIGHWAY_KERNELS) + // The Highway CPU kernels read the scales as the type of x. + if (s.device == Device::cpu) { + return false; + } +#endif return s.device == Device::cpu || (s.device == Device::gpu && metal::is_available()); } diff --git a/tests/quantized_stream_tests.cpp b/tests/quantized_stream_tests.cpp index 24d2beab81..7b60cea460 100644 --- a/tests/quantized_stream_tests.cpp +++ b/tests/quantized_stream_tests.cpp @@ -7,6 +7,18 @@ using namespace mlx::core; +namespace { + +// The Highway CPU kernels do not read bf16 x with f16 scales, so the op +// promotes there. +#if defined(MLX_USE_HIGHWAY_KERNELS) +constexpr bool cpu_reads_mixed = false; +#else +constexpr bool cpu_reads_mixed = true; +#endif + +} // namespace + TEST_CASE("test empty gather output constructs without dividing by zero") { for (auto device : {Device::cpu, Device::gpu}) { if (!is_available(device)) { @@ -84,7 +96,9 @@ TEST_CASE("test mixed affine gather storage follows the selected consumer") { stream); const bool matrix = sorted && rows >= 16 && rows / experts >= 4; const bool mixed_vector = - (device == Device::cpu || metal::is_available()) && !matrix; + (device == Device::cpu ? cpu_reads_mixed + : metal::is_available()) && + !matrix; CHECK(output.dtype() == (mixed_vector ? bfloat16 : float32)); CHECK(output.primitive().stream() == stream); auto expected = broadcast_to( @@ -268,7 +282,8 @@ TEST_CASE("test mixed bf16 and f16 quantized_matmul") { // sums, rounded once. The inputs and references are built on the CPU. auto cpu = new_stream(Device::cpu); for (auto device : {Device::cpu, Device::gpu}) { - if (!is_available(device)) { + if (!is_available(device) || + (device == Device::cpu && !cpu_reads_mixed)) { continue; } auto s = new_stream(device); @@ -309,7 +324,8 @@ TEST_CASE("test mixed bf16 and f16 gather_qmm") { auto expert = array({0}, uint32); auto one = [&](const array& a) { return expand_dims(a, 0, cpu); }; for (auto device : {Device::cpu, Device::gpu}) { - if (!is_available(device)) { + if (!is_available(device) || + (device == Device::cpu && !cpu_reads_mixed)) { continue; } auto s = new_stream(device); From 0a10b88cebf16174bbb6c5898a45beb503d76aa7 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:38:56 +0100 Subject: [PATCH 63/65] Pass lda and ldb to simd_gemm in the Highway low-precision GEMM simd_gemm now takes the leading dimensions (#26). The Highway path already passes them to cblas_sgemm, but not to simd_gemm, so it did not compile with both changes and would read a strided operand as dense. --- mlx/backend/cpu/gemms/simd_low_precision_gemm.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h index a7008d5e46..8a7b4cfa64 100644 --- a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -397,6 +397,8 @@ void matmul_lowp( M, N, K, + lda, + ldb, alpha, beta); } From e61dd69fb1e39d9055353c186291384719584f83 Mon Sep 17 00:00:00 2001 From: Eric Date: Sun, 22 Nov 2026 05:56:12 -0800 Subject: [PATCH 64/65] Preserve mixed-scale and one-bit CPU quantization in Highway builds --- mlx/backend/cpu/CMakeLists.txt | 3 +- .../cpu/gemms/simd_low_precision_gemm.h | 24 ++++--- mlx/backend/cpu/quantized.cpp | 45 ++++++++++--- mlx/backend/cpu/quantized_highway.h | 30 +++++++++ mlx/backend/cpu/quantized_highway_backend.cpp | 63 +++++++++---------- mlx/ops.cpp | 6 -- tests/quantized_stream_tests.cpp | 22 +------ tests/upstream_metal_kernel_tests.cpp | 4 +- 8 files changed, 114 insertions(+), 83 deletions(-) diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index defb8a614e..5bfdad4c06 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -161,8 +161,7 @@ target_sources( ${CMAKE_CURRENT_BINARY_DIR}/compiled_preamble.cpp) if(MLX_USE_HIGHWAY) - # quantized.cpp's Highway counterpart (quantized.cpp compiles to nothing - # here), and the Highway kernels' dispatch counters. + # 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) diff --git a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h index 8a7b4cfa64..0bd0eec137 100644 --- a/mlx/backend/cpu/gemms/simd_low_precision_gemm.h +++ b/mlx/backend/cpu/gemms/simd_low_precision_gemm.h @@ -235,13 +235,17 @@ void matmul_lowp( size_t N = b_shape[ndim - 1]; size_t K = a_shape[ndim - 1]; - if (batch_size > 1) { - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; + // 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, @@ -315,16 +319,10 @@ void matmul_lowp( 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 && N * K >= 65536) { + 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) { - size_t a_rows = a_transposed ? K : M; - size_t b_rows = b_transposed ? N : K; - size_t a_elems = a_rows * lda; - size_t b_elems = b_rows * ldb; - size_t out_elems = M * ldc; - cpu::ScratchLease gemm_scratch( lowp_gemm_buffer(), a_elems + b_elems + out_elems); float* a_f32 = gemm_scratch.data(); diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index b57e502b0b..0147b3335a 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -1,6 +1,4 @@ // Copyright © 2023-2026 Apple Inc. -#if !defined(MLX_USE_HIGHWAY_KERNELS) -// Builds with Highway compile quantized_highway_backend.cpp instead. #include @@ -8,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" @@ -990,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) { @@ -1009,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]; @@ -1057,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]; @@ -1349,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]; @@ -1399,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) { @@ -1440,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()); @@ -1502,5 +1532,6 @@ 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) + +} // namespace mlx::core diff --git a/mlx/backend/cpu/quantized_highway.h b/mlx/backend/cpu/quantized_highway.h index ed9b1d06bb..a4d6e6ccf5 100644 --- a/mlx/backend/cpu/quantized_highway.h +++ b/mlx/backend/cpu/quantized_highway.h @@ -19,6 +19,36 @@ 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, diff --git a/mlx/backend/cpu/quantized_highway_backend.cpp b/mlx/backend/cpu/quantized_highway_backend.cpp index a60975db11..37d3fccdb1 100644 --- a/mlx/backend/cpu/quantized_highway_backend.cpp +++ b/mlx/backend/cpu/quantized_highway_backend.cpp @@ -2392,37 +2392,23 @@ void quantize_dequantize_fp_dispatch( } } -// 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) { - if (out.size() == 0) { - out.set_data(allocator::malloc(0)); - return true; - } - if (x.shape(-1) != 0) { - return false; - } - out.set_data(allocator::malloc(out.nbytes())); - auto& encoder = cpu::get_command_encoder(stream); - encoder.set_output_array(out); - encoder.dispatch([out_ptr = out.data(), nbytes = out.nbytes()]() { - std::memset(out_ptr, 0, nbytes); - }); - return true; -} } // namespace -void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { - if (empty_qmm_cpu(inputs[0], out, stream())) { - return; - } +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) { + 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 { @@ -2469,18 +2455,22 @@ 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())) { - return; - } +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(), + 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]; @@ -2636,10 +2626,13 @@ void dispatch_quantize( w_ptr, out_ptr, scales_ptr, biases_ptr, bits, group_size, w.size()); } -void fast::Quantize::eval_cpu( +void cpu::quantize_affine_highway( const std::vector& inputs, - std::vector& outputs) { - auto ensure_row_contiguous = [s = stream()](const array& arr) { + 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 { @@ -2655,7 +2648,7 @@ void fast::Quantize::eval_cpu( 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()); + auto& encoder = cpu::get_command_encoder(stream); if (copied) { encoder.add_temporary(w); } @@ -2741,7 +2734,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; } // No path here quantizes w; quantized.cpp raises the same error. diff --git a/mlx/ops.cpp b/mlx/ops.cpp index 07854e1a36..d8babb07b8 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -4799,12 +4799,6 @@ namespace { // biases. CUDA's qmv reads them as the output type, so CUDA promotes. The // CPU shares Metal's shape conditions so the output dtype matches. bool reads_mixed_bf16_f16(const Stream& s) { -#if defined(MLX_USE_HIGHWAY_KERNELS) - // The Highway CPU kernels read the scales as the type of x. - if (s.device == Device::cpu) { - return false; - } -#endif return s.device == Device::cpu || (s.device == Device::gpu && metal::is_available()); } diff --git a/tests/quantized_stream_tests.cpp b/tests/quantized_stream_tests.cpp index 7b60cea460..24d2beab81 100644 --- a/tests/quantized_stream_tests.cpp +++ b/tests/quantized_stream_tests.cpp @@ -7,18 +7,6 @@ using namespace mlx::core; -namespace { - -// The Highway CPU kernels do not read bf16 x with f16 scales, so the op -// promotes there. -#if defined(MLX_USE_HIGHWAY_KERNELS) -constexpr bool cpu_reads_mixed = false; -#else -constexpr bool cpu_reads_mixed = true; -#endif - -} // namespace - TEST_CASE("test empty gather output constructs without dividing by zero") { for (auto device : {Device::cpu, Device::gpu}) { if (!is_available(device)) { @@ -96,9 +84,7 @@ TEST_CASE("test mixed affine gather storage follows the selected consumer") { stream); const bool matrix = sorted && rows >= 16 && rows / experts >= 4; const bool mixed_vector = - (device == Device::cpu ? cpu_reads_mixed - : metal::is_available()) && - !matrix; + (device == Device::cpu || metal::is_available()) && !matrix; CHECK(output.dtype() == (mixed_vector ? bfloat16 : float32)); CHECK(output.primitive().stream() == stream); auto expected = broadcast_to( @@ -282,8 +268,7 @@ TEST_CASE("test mixed bf16 and f16 quantized_matmul") { // sums, rounded once. The inputs and references are built on the CPU. auto cpu = new_stream(Device::cpu); for (auto device : {Device::cpu, Device::gpu}) { - if (!is_available(device) || - (device == Device::cpu && !cpu_reads_mixed)) { + if (!is_available(device)) { continue; } auto s = new_stream(device); @@ -324,8 +309,7 @@ TEST_CASE("test mixed bf16 and f16 gather_qmm") { auto expert = array({0}, uint32); auto one = [&](const array& a) { return expand_dims(a, 0, cpu); }; for (auto device : {Device::cpu, Device::gpu}) { - if (!is_available(device) || - (device == Device::cpu && !cpu_reads_mixed)) { + if (!is_available(device)) { continue; } auto s = new_stream(device); 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); From b6e5b8a42a394be12e3cecad7be5fa57db33b15d Mon Sep 17 00:00:00 2001 From: Eric Date: Sun, 22 Nov 2026 08:02:58 -0800 Subject: [PATCH 65/65] Guard optional Highway dispatch in SwiftPM builds --- mlx/backend/cpu/norms_highway_dispatch.cpp | 2 ++ mlx/backend/cpu/quantized_highway_dispatch.cpp | 2 ++ mlx/backend/cpu/rope_highway_dispatch.cpp | 2 ++ mlx/backend/cpu/sdpa_highway_dispatch.cpp | 2 ++ 4 files changed, 8 insertions(+) diff --git a/mlx/backend/cpu/norms_highway_dispatch.cpp b/mlx/backend/cpu/norms_highway_dispatch.cpp index 3de7ba211d..5cb59d916d 100644 --- a/mlx/backend/cpu/norms_highway_dispatch.cpp +++ b/mlx/backend/cpu/norms_highway_dispatch.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/norms_highway.h" @@ -228,3 +229,4 @@ void layer_norm_highway_bfloat16( } } // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/quantized_highway_dispatch.cpp b/mlx/backend/cpu/quantized_highway_dispatch.cpp index 2fd2685f5b..751aeafd25 100644 --- a/mlx/backend/cpu/quantized_highway_dispatch.cpp +++ b/mlx/backend/cpu/quantized_highway_dispatch.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/quantized_highway.h" @@ -329,3 +330,4 @@ void fp_qmm_t_highway( } } // namespace mlx::core +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/rope_highway_dispatch.cpp b/mlx/backend/cpu/rope_highway_dispatch.cpp index 73656c24ee..4c1c6a2776 100644 --- a/mlx/backend/cpu/rope_highway_dispatch.cpp +++ b/mlx/backend/cpu/rope_highway_dispatch.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/rope_highway.h" @@ -118,3 +119,4 @@ int rope_non_traditional_highway_reverse( } } // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS) diff --git a/mlx/backend/cpu/sdpa_highway_dispatch.cpp b/mlx/backend/cpu/sdpa_highway_dispatch.cpp index e0c3a51ff8..2f3f633253 100644 --- a/mlx/backend/cpu/sdpa_highway_dispatch.cpp +++ b/mlx/backend/cpu/sdpa_highway_dispatch.cpp @@ -1,4 +1,5 @@ // Copyright © 2026 Apple Inc. +#if defined(MLX_USE_HIGHWAY_KERNELS) #include "mlx/backend/cpu/sdpa_highway.h" @@ -128,3 +129,4 @@ void sdpa_highway( } } // namespace mlx::core::fast +#endif // defined(MLX_USE_HIGHWAY_KERNELS)