diff --git a/.github/actions/build-docs/action.yml b/.github/actions/build-docs/action.yml index 794f09e2f7..bc91577755 100644 --- a/.github/actions/build-docs/action.yml +++ b/.github/actions/build-docs/action.yml @@ -6,7 +6,7 @@ runs: steps: - name: Setup machine id: setup - uses: ./.github/actions/setup + uses: $/.github/actions/setup with: ccache-key: 'release' ccache-save: false @@ -28,7 +28,7 @@ runs: # Do it manually because upload-pages-artifact requires gtar - name: Upload artifact id: upload-artifact - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v7.0.2 with: name: github-pages path: artifact.tar diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 7439e1bfb7..be48656d9e 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -105,7 +105,7 @@ runs: - name: Cache JIT-compiled CUDA kernels if: runner.os == 'Linux' && startsWith(inputs.toolkit, 'cuda') - uses: actions/cache@v5 + uses: actions/cache@v5.1.0 with: path: /tmp/mlx-ptx-cache key: >- diff --git a/.github/actions/test-array-api/action.yml b/.github/actions/test-array-api/action.yml index 3a049beaf7..e7886c6dfd 100644 --- a/.github/actions/test-array-api/action.yml +++ b/.github/actions/test-array-api/action.yml @@ -5,7 +5,7 @@ runs: using: 'composite' steps: - name: Checkout array-api-tests - uses: actions/checkout@v7 + uses: actions/checkout@v7.0.1 with: repository: data-apis/array-api-tests ref: 'ef5b39f1190d54dca0d9a12646033d2d123afdd5' # v2026.09.08 diff --git a/.github/actions/test-wheel/action.yml b/.github/actions/test-wheel/action.yml index 5976e768ef..208c92d79c 100644 --- a/.github/actions/test-wheel/action.yml +++ b/.github/actions/test-wheel/action.yml @@ -16,13 +16,13 @@ runs: run: python -c "import sys; print(f'version={sys.version_info.major}.{sys.version_info.minor}')" >> $GITHUB_OUTPUT - name: Download frontend packages - uses: actions/download-artifact@v8 + uses: actions/download-artifact@v8.0.2 with: pattern: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ steps.python.outputs.version }} path: wheelhouse - name: Download backend packages - uses: actions/download-artifact@v8 + uses: actions/download-artifact@v8.0.2 with: pattern: backend-${{ inputs.toolkit}}-${{ runner.os }}-${{ runner.arch }} path: wheelhouse diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000000..8c45b17692 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,98 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/build_and_test.yml': + - 'actions/cache@v5.1.0' + - 'actions/checkout@v7.0.1' + - 'actions/upload-artifact@v7.0.2' + - 'astral-sh/setup-uv@v8.2.0' + - 'hendrikmuhs/ccache-action@v1.2.23' + - 'pre-commit/action@v3.0.1' + '.github/workflows/documentation.yml': + - 'actions/cache@v5.1.0' + - 'actions/checkout@v7.0.1' + - 'actions/deploy-pages@v5.0.1' + - 'actions/upload-artifact@v7.0.2' + - 'astral-sh/setup-uv@v8.2.0' + - 'hendrikmuhs/ccache-action@v1.2.23' + '.github/workflows/pico-validation.yml': + - 'actions/checkout@v7.0.1' + - 'actions/setup-python@v6.2.0' + '.github/workflows/release.yml': + - 'actions/cache@v5.1.0' + - 'actions/checkout@v7.0.1' + - 'actions/deploy-pages@v5.0.1' + - 'actions/download-artifact@v8.0.2' + - 'actions/upload-artifact@v7.0.2' + - 'astral-sh/setup-uv@v8.2.0' + - 'hendrikmuhs/ccache-action@v1.2.23' + - 'pypa/gh-action-pypi-publish@release/v1' + '.github/workflows/update_bypass_list.yml': + - 'actions/checkout@v7.0.1' +dependencies: + 'actions/cache@v4': + ref: 'v4' + commit: 'sha1-0057852bfaa89a56745cba8c7296529d2fc39830' + owner_id: 44036562 + repo_id: 215566462 + 'actions/cache@v5.1.0': + ref: 'v5.1.0' + commit: 'sha1-caa296126883cff596d87d8935842f9db880ef25' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/deploy-pages@v5.0.1': + ref: 'v5.0.1' + commit: 'sha1-368f82528645a54fb793d4d04e342629a3f51346' + owner_id: 44036562 + repo_id: 438112499 + 'actions/download-artifact@v8.0.2': + ref: 'v8.0.2' + commit: 'sha1-9000827ccba6bdab643e8b6fd33ac0654aef8333' + owner_id: 44036562 + repo_id: 192626254 + 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405': + ref: 'v6.2.0' + commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@v6.2.0': + ref: 'v6.2.0' + commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405' + owner_id: 44036562 + repo_id: 192625525 + 'actions/upload-artifact@v7.0.2': + ref: 'v7.0.2' + commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9' + owner_id: 44036562 + repo_id: 192625955 + 'astral-sh/setup-uv@v8.2.0': + ref: 'v8.2.0' + commit: 'sha1-fac544c07dec837d0ccb6301d7b5580bf5edae39' + owner_id: 115962839 + repo_id: 846733598 + 'hendrikmuhs/ccache-action@v1.2.23': + ref: 'v1.2.23' + commit: 'sha1-d62db5f07c26379fc4b4e0916f098a92573c3b03' + owner_id: 7126422 + repo_id: 319035161 + 'pre-commit/action@v3.0.1': + ref: 'v3.0.1' + commit: 'sha1-2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd' + owner_id: 6943086 + repo_id: 204199630 + uses: + - 'actions/cache@v4' + 'pypa/gh-action-pypi-publish@release/v1': + ref: 'release/v1' + commit: 'sha1-7245906fb61fa33a13554f9d5fb856fe61758086' + owner_id: 647025 + repo_id: 178055147 + uses: + - 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405' diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 95fce91d6c..22a97f86b7 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -21,7 +21,7 @@ jobs: name: Check Lint runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 - uses: pre-commit/action@v3.0.1 - name: Test check_stream_args.py shell: bash @@ -62,12 +62,12 @@ jobs: 'ubuntu-22.04')) }} steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup id: setup with: toolkit: ${{ matrix.toolkit }} - - uses: ./.github/actions/build + - uses: $/.github/actions/build with: cmake-args: ${{ steps.setup.outputs.cmake-args }} # For MSVC, Ninja/Release is the only config supported by ccache. @@ -75,9 +75,9 @@ jobs: - name: Check generated Python stubs with ty if: matrix.os == 'Linux' && matrix.arch == 'x86_64' && matrix.toolkit == 'cpu' run: uvx ty check python/mlx/core - - uses: ./.github/actions/test-linux + - uses: $/.github/actions/test-linux if: matrix.os == 'Linux' && (matrix.toolkit == 'cpu' || matrix.arch == 'x86_64') - - uses: ./.github/actions/test-windows + - uses: $/.github/actions/test-windows if: matrix.os == 'Windows' && matrix.toolkit == 'cpu' mac_build: @@ -91,8 +91,8 @@ jobs: runs-on: [self-hosted, macos] needs: check_lint steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup id: setup with: toolkit: ${{ matrix.toolkit }} @@ -109,10 +109,10 @@ jobs: run: | uv pip install build setuptools uv run python -m build -w - - uses: ./.github/actions/test-macos + - uses: $/.github/actions/test-macos with: toolkit: ${{ matrix.toolkit }} - - uses: ./.github/actions/test-array-api + - uses: $/.github/actions/test-array-api if: matrix.toolkit == 'metal' build_documentation: @@ -120,8 +120,8 @@ jobs: runs-on: ubuntu-22.04 needs: check_lint steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/build-docs linux_sanitizer_build_and_test: name: Linux Sanitizer Tests (${{ matrix.sanitizer }}) @@ -135,7 +135,7 @@ jobs: runs-on: ubuntu-22.04-arm steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@v7.0.1 - name: Install Dependencies run: | @@ -173,7 +173,7 @@ jobs: image: fedora:42 steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@v7.0.1 - name: CPP Build Test - No Release run: | diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index cdbf319f01..8a5f5ee1bb 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -10,8 +10,8 @@ jobs: build: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/build-docs deploy: needs: build @@ -25,4 +25,4 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@v5.0.1 diff --git a/.github/workflows/pico-validation.yml b/.github/workflows/pico-validation.yml new file mode 100644 index 0000000000..ce1cbfb246 --- /dev/null +++ b/.github/workflows/pico-validation.yml @@ -0,0 +1,45 @@ +name: Pico integration validation + +on: + pull_request: + push: + branches: [pico/integration] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pico-validation-${{ github.ref }} + cancel-in-progress: true + +jobs: + native-cpu: + if: github.repository == 'ronaldmannak/mlx' || github.repository == 'PicoMLX/mlx' + runs-on: macos-26 + timeout-minutes: 45 + env: + CMAKE_ARGS: -DMLX_BUILD_METAL=OFF -DMLX_BUILD_TESTS=OFF -DMLX_BUILD_EXAMPLES=OFF + CMAKE_BUILD_PARALLEL_LEVEL: 3 + DEVICE: cpu + steps: + - uses: actions/checkout@v7.0.1 + - uses: actions/setup-python@v6.2.0 + with: + python-version: '3.12' + - name: Build the current native sources and Python bridge + run: python -m pip install -e . numpy pytest cmake + - name: Build native C++ tests in a persistent directory + run: | + cmake -S . -B build/pico-cpu -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=14.0 \ + -DMLX_BUILD_METAL=OFF -DMLX_BUILD_TESTS=ON \ + -DMLX_BUILD_EXAMPLES=OFF -DMLX_BUILD_PYTHON_BINDINGS=OFF + cmake --build build/pico-cpu --target tests --parallel 3 + - name: Run native C++ tests + run: DEVICE=cpu ./build/pico-cpu/tests/tests + - name: Verify row-aware attention and partitioning + run: | + python -m pytest -q python/tests/test_fast_sdpa.py -k 'left_padding or kv_offsets' + python -m pytest -q python/tests/test_ops.py -k argpartition + python -m pytest -q python/tests/test_quantized.py -k nvfp4_global_scale_float16_cpu diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 56beb9d982..ef9bf4c66e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,8 +33,8 @@ jobs: if: github.repository == 'ml-explore/mlx' runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/build-docs + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/build-docs deploy_documentation: name: Deploy documentation @@ -50,7 +50,7 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@v5.0.1 build_frontend: name: ${{ matrix.os }} (python-${{ matrix.python-version }}, ${{ matrix.arch }}) @@ -75,19 +75,19 @@ jobs: PYPI_RELEASE: 1 DEV_RELEASE: ${{ inputs.dev-release && 1 || 0 }} steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup id: setup with: python-version: ${{ matrix.python-version }} ccache-key: 'release' ccache-save: false - - uses: ./.github/actions/build-wheel + - uses: $/.github/actions/build-wheel with: cmake-args: ${{ steps.setup.outputs.cmake-args }} build-backend: false - run: unzip -l wheelhouse/*.whl - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@v7.0.2 with: name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }} path: wheelhouse/mlx-*.whl @@ -118,18 +118,18 @@ jobs: }} env: *build-env steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup id: setup with: toolkit: ${{ matrix.toolkit }} ccache-key: 'release' - - uses: ./.github/actions/build-wheel + - uses: $/.github/actions/build-wheel with: cmake-args: ${{ steps.setup.outputs.cmake-args }} build-frontend: false - run: unzip -l wheelhouse/*.whl - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@v7.0.2 with: name: backend-${{ matrix.toolkit }}-${{ runner.os }}-${{ runner.arch }} path: wheelhouse/*.whl @@ -144,8 +144,8 @@ jobs: runs-on: [self-hosted, macos] env: *build-env steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup id: setup with: toolkit: 'metal' @@ -153,25 +153,25 @@ jobs: ccache-key: 'release' ccache-save: ${{ matrix.python-version == '3.10' }} - name: Build macOS 14 package - uses: ./.github/actions/build-wheel + uses: $/.github/actions/build-wheel with: macos-target: '14.0' cmake-args: ${{ steps.setup.outputs.cmake-args }} build-backend: ${{ matrix.python-version == '3.10' }} - name: Build macOS 15 package - uses: ./.github/actions/build-wheel + uses: $/.github/actions/build-wheel with: macos-target: '15.0' cmake-args: ${{ steps.setup.outputs.cmake-args }} build-backend: ${{ matrix.python-version == '3.10' }} - name: Build macOS 26 package - uses: ./.github/actions/build-wheel + uses: $/.github/actions/build-wheel with: macos-target: '26.2' cmake-args: ${{ steps.setup.outputs.cmake-args }} build-backend: ${{ matrix.python-version == '3.10' }} - name: Build macOS 27 package - uses: ./.github/actions/build-wheel + uses: $/.github/actions/build-wheel with: macos-target: '27.0' cmake-args: ${{ steps.setup.outputs.cmake-args }} @@ -179,14 +179,14 @@ jobs: - name: Display content of the wheels run: for WHEEL in wheelhouse/*.whl; do unzip -l $WHEEL; echo; done - name: Upload frontend packages - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v7.0.2 with: name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }} path: wheelhouse/mlx-*.whl if-no-files-found: error - name: Upload backend packages if: matrix.python-version == '3.10' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v7.0.2 with: name: backend-metal-${{ runner.os }}-${{ runner.arch }} path: wheelhouse/mlx_metal-*.whl @@ -226,12 +226,12 @@ jobs: 'ubuntu-22.04')) }} steps: - - uses: actions/checkout@v7 - - uses: ./.github/actions/setup + - uses: actions/checkout@v7.0.1 + - uses: $/.github/actions/setup with: toolkit: ${{ matrix.toolkit }} use-ccache: false - - uses: ./.github/actions/test-wheel + - uses: $/.github/actions/test-wheel with: toolkit: ${{ matrix.toolkit }} @@ -245,7 +245,7 @@ jobs: name: *pypi-env url: https://pypi.org/p/mlx steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@v8.0.2 with: pattern: frontend-* merge-multiple: true @@ -268,7 +268,7 @@ jobs: name: *pypi-env url: https://pypi.org/p/mlx-cuda steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@v8.0.2 with: pattern: backend-cuda* merge-multiple: true @@ -291,7 +291,7 @@ jobs: name: *pypi-env url: https://pypi.org/p/mlx-cpu steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@v8.0.2 with: pattern: backend-cpu-* merge-multiple: true @@ -314,7 +314,7 @@ jobs: name: *pypi-env url: https://pypi.org/p/mlx-metal steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@v8.0.2 with: pattern: backend-metal-* path: dist diff --git a/.github/workflows/update_bypass_list.yml b/.github/workflows/update_bypass_list.yml index f5ecb25f7a..ab3f99e3c4 100644 --- a/.github/workflows/update_bypass_list.yml +++ b/.github/workflows/update_bypass_list.yml @@ -18,7 +18,7 @@ jobs: if: github.repository == 'ml-explore/mlx' runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 - env: # Can only use PAT with permissions: admin:org_hook, public_repo GITHUB_TOKEN: ${{ secrets.ZCBENZ_TOKEN_UPDATE_BYPASS_LIST }} diff --git a/CMakeLists.txt b/CMakeLists.txt index ece8f46e8f..ecabcb7a0b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -124,6 +124,14 @@ if(USE_UBSAN) else() list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=undefined) list(APPEND SANITIZER_LINK_FLAGS -fsanitize=undefined) + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + # Not part of the installed targets, and nvcc does not know this flag. + list( + APPEND + SANITIZER_COMPILE_FLAGS + "$<$:$>" + ) + endif() endif() endif() @@ -133,8 +141,6 @@ if(USE_TSAN) FATAL_ERROR "ThreadSanitizer (TSan) is not supported by the MSVC compiler. Please use Clang or GCC." ) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") - message(FATAL_ERROR "ThreadSanitizer (TSan) is not supported on macOS.") else() list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=thread) list(APPEND SANITIZER_LINK_FLAGS -fsanitize=thread) @@ -268,7 +274,7 @@ if(WIN32) endblock() target_include_directories(mlx PRIVATE "${dlfcn-win32_SOURCE_DIR}/src") target_sources(mlx PRIVATE "${dlfcn-win32_SOURCE_DIR}/src/dlfcn.c") - target_link_libraries(mlx PRIVATE Psapi.lib) + target_link_libraries(mlx PRIVATE psapi) endif() if(MLX_BUILD_CPU) @@ -285,7 +291,7 @@ if(MLX_BUILD_CPU) target_link_libraries(mlx PUBLIC ${ACCELERATE_LIBRARY}) add_compile_definitions(MLX_USE_ACCELERATE) add_compile_definitions(ACCELERATE_NEW_LAPACK) - elseif(WIN32) + elseif(WIN32 AND NOT BLA_VENDOR) if(CMAKE_SYSTEM_PROCESSOR STREQUAL "ARM64") set(OPENBLAS_ZIP "OpenBLAS-0.3.33-woa64-dll.zip") set(OPENBLAS_LIB "openblas") diff --git a/cmake/tsan_suppressions.txt b/cmake/tsan_suppressions.txt new file mode 100644 index 0000000000..2ffbd0542a --- /dev/null +++ b/cmake/tsan_suppressions.txt @@ -0,0 +1,5 @@ +# Use with: TSAN_OPTIONS=suppressions= +# +# Metal runs completion handlers on its own threads, and passes the handler to +# them in a way that TSan cannot see. Ignore the races it reports for it. +race:MTL::CommandBuffer::addCompletedHandler diff --git a/cmake/ubsan_ignorelist.txt b/cmake/ubsan_ignorelist.txt new file mode 100644 index 0000000000..50089a03f5 --- /dev/null +++ b/cmake/ubsan_ignorelist.txt @@ -0,0 +1,5 @@ +# metal-cpp calls release() on a null pointer when it assigns a NS::SharedPtr. +# This is a no-op in Objective-C, but undefined behavior in C++. +[undefined] +src:*/Foundation/NSObject.hpp +src:*/Foundation/NSSharedPtr.hpp diff --git a/docs/src/python/array.rst b/docs/src/python/array.rst index e68524d5a4..118095dde6 100644 --- a/docs/src/python/array.rst +++ b/docs/src/python/array.rst @@ -61,5 +61,6 @@ Array array.swapaxes array.transpose array.T + array.mT array.var array.view diff --git a/docs/src/python/devices_and_streams.rst b/docs/src/python/devices_and_streams.rst index 7743cd5d0f..e1041a38d8 100644 --- a/docs/src/python/devices_and_streams.rst +++ b/docs/src/python/devices_and_streams.rst @@ -13,6 +13,7 @@ Devices and Streams ThreadLocalStream default_device set_default_device + is_available default_stream new_stream new_thread_local_stream diff --git a/docs/src/python/distributed.rst b/docs/src/python/distributed.rst index e743a6178e..20653a97b3 100644 --- a/docs/src/python/distributed.rst +++ b/docs/src/python/distributed.rst @@ -5,9 +5,8 @@ Distributed Communication ========================== -MLX provides a distributed communication package using MPI. The MPI library is -loaded at runtime; if MPI is available then distributed communication is also -made available. +MLX supports distributed communication with the MPI, Ring, JACCL, and NCCL +backends. See :ref:`usage_distributed` for backend availability and setup. .. autosummary:: :toctree: _autosummary diff --git a/docs/src/python/fast.rst b/docs/src/python/fast.rst index ed4103a0af..8206594908 100644 --- a/docs/src/python/fast.rst +++ b/docs/src/python/fast.rst @@ -14,6 +14,7 @@ Fast gated_delta_update rope scaled_dot_product_attention + gated_delta_update metal_kernel cuda_kernel precompiled_cuda_kernel diff --git a/docs/src/python/memory_management.rst b/docs/src/python/memory_management.rst index b0564bd0f2..e35710ed51 100644 --- a/docs/src/python/memory_management.rst +++ b/docs/src/python/memory_management.rst @@ -12,6 +12,7 @@ Memory Management reset_peak_memory get_cache_memory set_memory_limit + get_memory_limit set_cache_limit set_wired_limit clear_cache diff --git a/docs/src/python/metal.rst b/docs/src/python/metal.rst index 83a363c3ba..8022302d9f 100644 --- a/docs/src/python/metal.rst +++ b/docs/src/python/metal.rst @@ -7,6 +7,7 @@ Metal :toctree: _autosummary is_available + is_nax_available device_info start_capture stop_capture diff --git a/docs/src/python/nn.rst b/docs/src/python/nn.rst index 00f7f95456..829914877c 100644 --- a/docs/src/python/nn.rst +++ b/docs/src/python/nn.rst @@ -175,6 +175,7 @@ In detail: value_and_grad quantize average_gradients + utils.checkpoint .. toctree:: diff --git a/docs/src/python/nn/distributed.rst b/docs/src/python/nn/distributed.rst index 23998b71a3..67f75f7f23 100644 --- a/docs/src/python/nn/distributed.rst +++ b/docs/src/python/nn/distributed.rst @@ -17,6 +17,12 @@ create sharded layers from existing :class:`Modules `. shard_inplace fully_shard +.. currentmodule:: mlx.nn.utils +.. autosummary:: + :toctree: _autosummary + + clip_grad_norm_sharded + Layers ^^^^^^ diff --git a/docs/src/python/ops.rst b/docs/src/python/ops.rst index 52790680ff..298a64ebbc 100644 --- a/docs/src/python/ops.rst +++ b/docs/src/python/ops.rst @@ -127,6 +127,7 @@ Operations logical_xor logsumexp matmul + matrix_transpose max maximum mean diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 753dcb8ad9..b7256b07c7 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -114,6 +114,13 @@ Metal Enable the faster Metal CPU/GPU synchronization path. The default is ``0``. This requires Metal 3.2 or later (macOS 15 or later, or iOS 18 or later). +.. envvar:: MLX_METAL_RUNTIME_COMPILE + + Allow building Metal libraries from source at runtime. The default is + ``1``. Set it to ``0`` to throw instead when a kernel needs a library that + has not been loaded yet. Libraries loaded earlier, including ones loaded by + name from a ``.metallib``, are still used. + .. envvar:: MLX_CONV_WINOGRAD Allow the Winograd algorithm for 3x3 ``conv2d``. The default is ``1``. Set diff --git a/mlx.pc.in b/mlx.pc.in index a202028b1f..c0f46551c9 100644 --- a/mlx.pc.in +++ b/mlx.pc.in @@ -37,7 +37,7 @@ set_and_check(MLX_LIBRARY_DIRS @PACKAGE_CMAKE_INSTALL_LIBDIR@) set_and_check(MLX_INCLUDE_DIRS @PACKAGE_CMAKE_INSTALL_INCLUDEDIR@) set(MLX_LIBRARIES mlx) -find_library(MLX_LIBRARY mlx PATHS ${MLX_LIBRARY_DIRS}) +get_target_property(MLX_LIBRARY mlx LOCATION) if (@MLX_BUILD_ACCELERATE@) set(MLX_BUILD_ACCELERATE @MLX_BUILD_ACCELERATE@) diff --git a/mlx/allocator.h b/mlx/allocator.h index 82bc87401d..760bf20865 100644 --- a/mlx/allocator.h +++ b/mlx/allocator.h @@ -85,6 +85,9 @@ class MLX_API Allocator { MLX_API Allocator& allocator(); +// Whether the active memory is above the memory limit. +MLX_API bool over_memory_limit(); + using Deleter = std::function; // The allocator owns data from malloc diff --git a/mlx/backend/common/common.cpp b/mlx/backend/common/common.cpp index 81dc5c1a07..e317fe8586 100644 --- a/mlx/backend/common/common.cpp +++ b/mlx/backend/common/common.cpp @@ -147,6 +147,7 @@ void shared_buffer_reshape( const Strides& out_strides, array& out) { auto flags = in.flags(); + auto data_size = in.data_size(); if (flags.row_contiguous) { // For row contiguous reshapes: // - Shallow copy the buffer @@ -160,8 +161,12 @@ void shared_buffer_reshape( check_contiguity(out.shape(), out_strides); flags.row_contiguous = row_contiguous; flags.col_contiguous = col_contiguous; + if (row_contiguous || col_contiguous) { + flags.contiguous = true; + data_size = out.size(); + } } - out.copy_shared_buffer(in, out_strides, flags, in.data_size()); + out.copy_shared_buffer(in, out_strides, flags, data_size); } void Split::eval( diff --git a/mlx/backend/common/reduce.cpp b/mlx/backend/common/reduce.cpp index ceef464007..322c2225f0 100644 --- a/mlx/backend/common/reduce.cpp +++ b/mlx/backend/common/reduce.cpp @@ -39,7 +39,8 @@ ReductionPlan get_reduction_plan(const array& x, const std::vector& axes) { Shape shape = {x.shape(axes[0])}; Strides strides = {x.strides()[axes[0]]}; for (int i = 1; i < axes.size(); i++) { - if (axes[i] - 1 == axes[i - 1] && x.shape(axes[i]) > 1) { + if (axes[i] - 1 == axes[i - 1] && x.shape(axes[i]) > 1 && + static_cast(shape.back()) * x.shape(axes[i]) <= INT32_MAX) { shape.back() *= x.shape(axes[i]); strides.back() = x.strides()[axes[i]]; } else { @@ -94,7 +95,8 @@ ReductionPlan get_reduction_plan(const array& x, const std::vector& axes) { auto b = reductions[i - 1]; // b.stride = a.shape * a.stride then a and b are contiguous - if (b.second == a.first * a.second) { + if (b.second == a.first * a.second && + static_cast(a.first) * b.first <= INT32_MAX) { reductions.erase(reductions.begin() + i); reductions[i - 1] = std::make_pair(a.first * b.first, a.second); } diff --git a/mlx/backend/cpu/CMakeLists.txt b/mlx/backend/cpu/CMakeLists.txt index 6192a189a4..ee7cc204b0 100644 --- a/mlx/backend/cpu/CMakeLists.txt +++ b/mlx/backend/cpu/CMakeLists.txt @@ -18,7 +18,7 @@ set(COMPILE_DEPS unary_ops.h binary_ops.h) -if(WIN32) +if(CMAKE_HOST_WIN32) set(SHELL_EXT ps1) set(SHELL_CMD powershell -ExecutionPolicy Bypass -File) else() diff --git a/mlx/backend/cpu/conv.cpp b/mlx/backend/cpu/conv.cpp index 442629fbea..ca579b6876 100644 --- a/mlx/backend/cpu/conv.cpp +++ b/mlx/backend/cpu/conv.cpp @@ -1,6 +1,7 @@ // Copyright © 2023-2024 Apple Inc. #include +#include #include #include "mlx/backend/cpu/copy.h" @@ -1239,10 +1240,23 @@ void conv_3D_cpu( void Convolution::eval_cpu(const std::vector& inputs, array& out) { out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } auto& in = inputs[0]; auto& wt = inputs[1]; + // Return 0s if either input is empty + if (in.size() == 0 || wt.size() == 0) { + 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; + } + // 3D convolution if (in.ndim() == (3 + 2)) { return conv_3D_cpu( diff --git a/mlx/backend/cpu/gemms/bnns.cpp b/mlx/backend/cpu/gemms/bnns.cpp index 2ec0fd4e23..45c2a10747 100644 --- a/mlx/backend/cpu/gemms/bnns.cpp +++ b/mlx/backend/cpu/gemms/bnns.cpp @@ -71,7 +71,7 @@ void matmul_bnns( /* BNNSDataLayout layout = */ BNNSDataLayoutRowMajorMatrix, /* size_t size[BNNS_MAX_TENSOR_DIMENSION] = */ - {lda, (M * K) / lda, 0, 0, 0, 0, 0, 0}, + {a_transposed ? M : K, a_transposed ? K : M, 0, 0, 0, 0, 0, 0}, /* size_t stride[BNNS_MAX_TENSOR_DIMENSION] = */ {1, lda, 0, 0, 0, 0, 0, 0}, @@ -90,7 +90,7 @@ void matmul_bnns( /* BNNSDataLayout layout = */ BNNSDataLayoutRowMajorMatrix, /* size_t size[BNNS_MAX_TENSOR_DIMENSION] = */ - {ldb, (K * N) / ldb, 0, 0, 0, 0, 0, 0}, + {b_transposed ? K : N, b_transposed ? N : K, 0, 0, 0, 0, 0, 0}, /* size_t stride[BNNS_MAX_TENSOR_DIMENSION] = */ {1, ldb, 0, 0, 0, 0, 0, 0}, @@ -111,7 +111,7 @@ void matmul_bnns( /* size_t size[BNNS_MAX_TENSOR_DIMENSION] = */ {N, M, 0, 0, 0, 0, 0, 0}, /* size_t stride[BNNS_MAX_TENSOR_DIMENSION] = */ - {1, N, 0, 0, 0, 0, 0, 0}, + {1, ldc, 0, 0, 0, 0, 0, 0}, /* void * _Nullable data = */ nullptr, /* BNNSDataType data_type = */ bnns_dtype, diff --git a/mlx/backend/cpu/gemms/simd_bf16.cpp b/mlx/backend/cpu/gemms/simd_bf16.cpp index 58f5964b6e..f64456dc92 100644 --- a/mlx/backend/cpu/gemms/simd_bf16.cpp +++ b/mlx/backend/cpu/gemms/simd_bf16.cpp @@ -37,6 +37,9 @@ void matmul( M, N, K, + lda, + ldb, + ldc, alpha, beta); } diff --git a/mlx/backend/cpu/gemms/simd_fp16.cpp b/mlx/backend/cpu/gemms/simd_fp16.cpp index 93467da868..f74f062b3b 100644 --- a/mlx/backend/cpu/gemms/simd_fp16.cpp +++ b/mlx/backend/cpu/gemms/simd_fp16.cpp @@ -37,6 +37,9 @@ void matmul( M, N, K, + lda, + ldb, + ldc, alpha, beta); } diff --git a/mlx/backend/cpu/gemms/simd_gemm.h b/mlx/backend/cpu/gemms/simd_gemm.h index a23c7dea33..b1a2ec3f33 100644 --- a/mlx/backend/cpu/gemms/simd_gemm.h +++ b/mlx/backend/cpu/gemms/simd_gemm.h @@ -15,6 +15,7 @@ void load_block( AccT* out, int M, int N, + int ld, int i, int j, bool transpose) { @@ -22,14 +23,14 @@ void load_block( for (int ii = 0; ii < block_size && i * block_size + ii < M; ++ii) { for (int jj = 0; jj < block_size && j * block_size + jj < N; ++jj) { out[jj * block_size + ii] = - in[(i * block_size + ii) * N + j * block_size + jj]; + in[(i * block_size + ii) * ld + j * block_size + jj]; } } } else { for (int ii = 0; ii < block_size && i * block_size + ii < M; ++ii) { for (int jj = 0; jj < block_size && j * block_size + jj < N; ++jj) { out[ii * block_size + jj] = - in[(i * block_size + ii) * N + j * block_size + jj]; + in[(i * block_size + ii) * ld + j * block_size + jj]; } } } @@ -45,6 +46,9 @@ void simd_gemm( int M, int N, int K, + int lda, + int ldb, + int ldc, float alpha, float beta) { constexpr int block_size = 16; @@ -65,14 +69,14 @@ void simd_gemm( for (; k < K / block_size; k++) { // Load a and b blocks if (a_trans) { - load_block(a, a_block, K, M, k, i, true); + load_block(a, a_block, K, M, lda, k, i, true); } else { - load_block(a, a_block, M, K, i, k, false); + load_block(a, a_block, M, K, lda, i, k, false); } if (b_trans) { - load_block(b, b_block, N, K, j, k, false); + load_block(b, b_block, N, K, ldb, j, k, false); } else { - load_block(b, b_block, K, N, k, j, true); + load_block(b, b_block, K, N, ldb, k, j, true); } // Multiply and accumulate @@ -91,14 +95,14 @@ void simd_gemm( if (last_k_block_size) { // Load a and b blocks if (a_trans) { - load_block(a, a_block, K, M, k, i, true); + load_block(a, a_block, K, M, lda, k, i, true); } else { - load_block(a, a_block, M, K, i, k, false); + load_block(a, a_block, M, K, lda, i, k, false); } if (b_trans) { - load_block(b, b_block, N, K, j, k, false); + load_block(b, b_block, N, K, ldb, j, k, false); } else { - load_block(b, b_block, K, N, k, j, true); + load_block(b, b_block, K, N, ldb, k, j, true); } // Multiply and accumulate @@ -123,7 +127,7 @@ void simd_gemm( // Store for (int ii = 0; ii < block_size && i * block_size + ii < M; ++ii) { for (int jj = 0; jj < block_size && j * block_size + jj < N; ++jj) { - auto c_idx = (i * block_size + ii) * N + j * block_size + jj; + auto c_idx = (i * block_size + ii) * ldc + j * block_size + jj; if (beta != 0) { c[c_idx] = static_cast( alpha * c_block[ii * block_size + jj] + beta * c[c_idx]); diff --git a/mlx/backend/cpu/indexing.cpp b/mlx/backend/cpu/indexing.cpp index 15a2af3cb9..45fbdfcc60 100644 --- a/mlx/backend/cpu/indexing.cpp +++ b/mlx/backend/cpu/indexing.cpp @@ -416,6 +416,9 @@ void Scatter::eval_cpu(const std::vector& inputs, array& out) { auto ctype = src.flags().row_contiguous ? CopyType::Vector : CopyType::General; copy_cpu(src, out, ctype, stream()); + if (updates.size() == 0) { + return; + } auto& encoder = cpu::get_command_encoder(stream()); std::vector inds; @@ -578,7 +581,9 @@ void masked_scatter_impl(const array& mask, const array& src, array& out) { for (size_t b = 0; b < batch_count; ++b) { size_t src_consumed = 0; - src_it.seek(b * src_batch_size); + if (src_batch_size > 0) { + src_it.seek(b * src_batch_size); + } for (size_t i = 0; i < mask_batch_size; ++i) { if (mask_ptr[mask_it.loc]) { diff --git a/mlx/backend/cpu/inverse.cpp b/mlx/backend/cpu/inverse.cpp index a02c48b149..f48707bb1e 100644 --- a/mlx/backend/cpu/inverse.cpp +++ b/mlx/backend/cpu/inverse.cpp @@ -120,6 +120,9 @@ void inverse_impl( inv, a.flags().row_contiguous ? CopyType::Vector : CopyType::General, stream); + if (a.size() == 0) { + return; + } const int N = a.shape(-1); const size_t num_matrices = a.size() / (N * N); diff --git a/mlx/backend/cpu/luf.cpp b/mlx/backend/cpu/luf.cpp index 2e396f4b70..46d36ee080 100644 --- a/mlx/backend/cpu/luf.cpp +++ b/mlx/backend/cpu/luf.cpp @@ -47,7 +47,10 @@ void luf_impl( row_indices.set_data(allocator::malloc(row_indices.nbytes())); auto pivots_ptr = pivots.data(); auto row_indices_ptr = row_indices.data(); - size_t num_matrices = a.size() / (M * N); + size_t num_matrices = 1; + for (int i = 0; i < a.ndim() - 2; ++i) { + num_matrices *= a.shape(i); + } auto& encoder = cpu::get_command_encoder(stream); encoder.set_input_array(a); encoder.set_output_array(lu); @@ -56,16 +59,18 @@ void luf_impl( encoder.dispatch( [a_ptr, pivots_ptr, row_indices_ptr, num_matrices, M, N, K]() mutable { - int info; + int info = 0; for (size_t i = 0; i < num_matrices; ++i) { // Compute LU factorization of A - getrf( - /* m */ &M, - /* n */ &N, - /* a */ a_ptr, - /* lda */ &M, - /* ipiv */ reinterpret_cast(pivots_ptr), - /* info */ &info); + if (K > 0) { + getrf( + /* m */ &M, + /* n */ &N, + /* a */ a_ptr, + /* lda */ &M, + /* ipiv */ reinterpret_cast(pivots_ptr), + /* info */ &info); + } if (info < 0) { std::stringstream ss; diff --git a/mlx/backend/cpu/masked_mm.cpp b/mlx/backend/cpu/masked_mm.cpp index db38f39424..245965fd87 100644 --- a/mlx/backend/cpu/masked_mm.cpp +++ b/mlx/backend/cpu/masked_mm.cpp @@ -114,6 +114,9 @@ void BlockMaskedMM::eval_cpu(const std::vector& inputs, array& out) { "[BlockMaskedMM::eval] Currently only supports float32."); } out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } auto& a_pre = inputs[0]; auto& b_pre = inputs[1]; diff --git a/mlx/backend/cpu/primitives.cpp b/mlx/backend/cpu/primitives.cpp index 406e08eb34..8b00e7c980 100644 --- a/mlx/backend/cpu/primitives.cpp +++ b/mlx/backend/cpu/primitives.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -254,11 +255,14 @@ void RandomBits::eval_cpu(const std::vector& inputs, array& out) { // keys has shape (N1, ..., NK, 2) // out has shape (N1, ..., NK, M1, M2, ...) auto& keys = inputs[0]; - size_t num_keys = keys.size() / 2; + out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } + size_t num_keys = keys.size() / 2; size_t elems_per_key = out.size() / num_keys; size_t bytes_per_key = out.itemsize() * elems_per_key; - out.set_data(allocator::malloc(out.nbytes())); auto kptr = inputs[0].data(); auto cptr = out.data(); @@ -271,9 +275,12 @@ void RandomBits::eval_cpu(const std::vector& inputs, array& out) { num_keys, kshape = keys.shape(), kstrides = keys.strides()]() mutable { + auto store = [](char* cptr, size_t loc, uint32_t v) { + std::memcpy(cptr + sizeof(v) * loc, &v, sizeof(v)); + }; auto copy_remaining = [&](char* cptr, size_t loc, uint32_t v) { if (4 * loc + 4 <= bytes_per_key) { - reinterpret_cast(cptr)[loc] = v; + store(cptr, loc, v); } else { std::copy( reinterpret_cast(&v), @@ -286,7 +293,6 @@ void RandomBits::eval_cpu(const std::vector& inputs, array& out) { auto half_size = out_skip / 2; bool even = out_skip % 2 == 0; for (int i = 0; i < num_keys; ++i, cptr += bytes_per_key) { - auto ptr = reinterpret_cast(cptr); // Get ith key auto kidx = 2 * i; auto k1_elem = elem_to_loc(kidx, kshape, kstrides); @@ -295,12 +301,13 @@ void RandomBits::eval_cpu(const std::vector& inputs, array& out) { std::pair count{0, half_size + !even}; for (; count.first + 1 < half_size; count.first++, count.second++) { - std::tie(ptr[count.first], ptr[count.second]) = - random::threefry2x32_hash(key, count); + auto [first, second] = random::threefry2x32_hash(key, count); + store(cptr, count.first, first); + store(cptr, count.second, second); } if (count.first < half_size) { auto rb = random::threefry2x32_hash(key, count); - ptr[count.first++] = rb.first; + store(cptr, count.first++, rb.first); copy_remaining(cptr, count.second, rb.second); } if (!even) { @@ -399,15 +406,19 @@ void View::eval_cpu(const std::vector& inputs, array& out) { strides.back() = 1; } auto flags = in.flags(); + auto data_size = in.data_size() * ibytes / obytes; if (ibytes != obytes) { // Last axis size can change contiguity auto [_, row_contiguous, col_contiguous] = check_contiguity(out.shape(), strides); flags.row_contiguous = row_contiguous; flags.col_contiguous = col_contiguous; + if (row_contiguous || col_contiguous) { + flags.contiguous = true; + data_size = out.size(); + } } - out.copy_shared_buffer( - in, strides, flags, in.data_size() * ibytes / obytes); + out.copy_shared_buffer(in, strides, flags, data_size); } else { auto tmp = array( in.shape(), in.dtype() == bool_ ? uint8 : in.dtype(), nullptr, {}); diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index fefa5a372c..c02f64e33d 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -1,5 +1,7 @@ // Copyright © 2023-2026 Apple Inc. +#include + #include "mlx/backend/common/quantized.h" #include "mlx/backend/common/unary.h" #include "mlx/backend/cpu/copy.h" @@ -15,6 +17,9 @@ namespace mlx::core { namespace { +constexpr float F8E4M3_MAX = 448.0f; +constexpr float F4E2M1_MAX = 6.0f; + array ensure_row_contiguous( const array& arr, cpu::CommandEncoder& encoder, @@ -28,7 +33,7 @@ array ensure_row_contiguous( } }; -// Row accumulator for the non-transposed affine kernel, taken from the +// Row accumulator for the non-transposed kernels, taken from the // allocator so it is served by the buffer cache. Empty when transposed. array qmm_accumulator( const array& out, @@ -481,7 +486,9 @@ void fp_qmm( const uint8_t* scales, int M, int N, - int K) { + int K, + float* acc, + float inv_scale_enc) { constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; @@ -489,28 +496,28 @@ void fp_qmm( const uint8_t* w_local = (const uint8_t*)w; const uint8_t* scales_local = scales; - std::fill(result, result + N, 0); + std::fill(acc, acc + N, 0.0f); for (int k = 0; k < K; k++) { - T* result_local = result; - T xi = *x++; + float* result_local = acc; + float xi = *x++; for (int n = 0; n < N; n += group_size) { - T scale = dequantize_scale(*scales_local++); + float scale = dequantize_scale(*scales_local++) * + inv_scale_enc; 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]); + (*result_local++) += xi * scale * FP4_LUT[w_local[0] & 0xf]; + (*result_local++) += xi * scale * FP4_LUT[(w_local[0] >> 4) & 0xf]; } else { (*result_local++) += - xi * scale * static_cast(detail::FromFP8{}(w_local[0])); + xi * scale * static_cast(detail::FromFP8{}(w_local[0])); } w_local++; } } } + std::copy(acc, acc + N, result); result += N; } } @@ -523,7 +530,8 @@ void fp_qmm_t( const uint8_t* scales, int M, int N, - int K) { + int K, + float inv_scale_enc = 1.0f) { constexpr int pack_factor = get_pack_factor(bits, 8); constexpr int packs_in_group = group_size / pack_factor; @@ -533,25 +541,26 @@ void fp_qmm_t( for (int n = 0; n < N; n++) { const T* x_local = x; - T sum = 0; + float sum = 0.0f; for (int k = 0; k < K; k += group_size) { - T scale = dequantize_scale(*scales_local++); + float scale = dequantize_scale(*scales_local++) * + inv_scale_enc; - T gsum = 0; + float gsum = 0.0f; 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]); + gsum += static_cast(*x_local++) * FP4_LUT[w_local[0] & 0xf]; + gsum += static_cast(*x_local++) * + FP4_LUT[(w_local[0] >> 4) & 0xf]; } else { - gsum += - (*x_local++) * static_cast(detail::FromFP8{}(w_local[0])); + gsum += static_cast(*x_local++) * + static_cast(detail::FromFP8{}(w_local[0])); } w_local++; } sum += scale * gsum; } - *result = sum; + *result = static_cast(sum); result++; } @@ -589,7 +598,8 @@ void fp_qmm_t_simd( const uint8_t* scales, int M, int N, - int K) { + int K, + float inv_scale_enc = 1.0f) { constexpr int pack_factor = get_pack_factor(bits, 32); constexpr int packs_in_group = group_size / pack_factor; constexpr int S = simd::max_size; @@ -605,7 +615,8 @@ void fp_qmm_t_simd( simd::Simd acc(0); auto x_local = x; for (int k = 0; k < K; k += group_size) { - T scale = dequantize_scale(*scales_local++); + float scale = dequantize_scale(*scales_local++) * + inv_scale_enc; simd::Simd g_acc(0); for (int kw = 0; kw < packs_in_group; kw += packs_per_simd) { @@ -635,16 +646,21 @@ void fp_qmm_dispatch_transpose( int M, int N, int K, - bool transposed_w) { + bool transposed_w, + float* acc, + float inv_scale_enc = 1.0f) { 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); + fp_qmm_t_simd( + result, x, w, scales, M, N, K, inv_scale_enc); } else { - fp_qmm_t(result, x, w, scales, M, N, K); + fp_qmm_t( + result, x, w, scales, M, N, K, inv_scale_enc); } } else { - fp_qmm(result, x, w, scales, M, N, K); + fp_qmm( + result, x, w, scales, M, N, K, acc, inv_scale_enc); } } @@ -654,7 +670,9 @@ void fp_qmm_dispatch_mode( const array& x, const array& w, const array& scales, - bool transposed_w) { + bool transposed_w, + array& acc, + float inv_scale_enc) { int K = x.shape(-1); int M = x.ndim() > 1 ? x.shape(-2) : 1; int N = out.shape(-1); @@ -675,7 +693,9 @@ void fp_qmm_dispatch_mode( M, N, K, - transposed_w); + transposed_w, + acc.data(), + inv_scale_enc); } } @@ -687,13 +707,18 @@ void fp_qmm_dispatch_typed( const array& scales, int group_size, int bits, - bool transposed_w) { + bool transposed_w, + array& acc, + float inv_scale_enc) { if (bits == 8) { - fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, acc, inv_scale_enc); } 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, acc, inv_scale_enc); } else { - fp_qmm_dispatch_mode(out, x, w, scales, transposed_w); + fp_qmm_dispatch_mode( + out, x, w, scales, transposed_w, acc, inv_scale_enc); } } @@ -704,19 +729,45 @@ void fp_qmm_dispatch( const array& scales, int group_size, int bits, - bool transposed_w) { + bool transposed_w, + array& acc, + float inv_scale_enc = 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, + acc, + inv_scale_enc); 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, + acc, + inv_scale_enc); 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, + acc, + inv_scale_enc); break; default: throw std::invalid_argument( @@ -843,7 +894,8 @@ void fp_bs_qmm_dispatch_mode( const array& scales, const array& lhs_indices, const array& rhs_indices, - bool transposed_w) { + bool transposed_w, + array& acc) { int K = x.shape(-1); int M = x.shape(-2); int N = out.shape(-1); @@ -872,7 +924,8 @@ void fp_bs_qmm_dispatch_mode( M, N, K, - transposed_w); + transposed_w, + acc.data()); } } @@ -886,16 +939,17 @@ void fp_bs_qmm_dispatch_typed( const array& rhs_indices, int group_size, int bits, - bool transposed_w) { + bool transposed_w, + array& acc) { if (bits == 8) { fp_bs_qmm_dispatch_mode( - out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + out, x, w, scales, lhs_indices, rhs_indices, transposed_w, acc); } else if (group_size == 32) { fp_bs_qmm_dispatch_mode( - out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + out, x, w, scales, lhs_indices, rhs_indices, transposed_w, acc); } else { fp_bs_qmm_dispatch_mode( - out, x, w, scales, lhs_indices, rhs_indices, transposed_w); + out, x, w, scales, lhs_indices, rhs_indices, transposed_w, acc); } } @@ -908,7 +962,8 @@ void fp_bs_qmm_dispatch( const array& rhs_indices, int group_size, int bits, - bool transposed_w) { + bool transposed_w, + array& acc) { switch (x.dtype()) { case float32: fp_bs_qmm_dispatch_typed( @@ -920,7 +975,8 @@ void fp_bs_qmm_dispatch( rhs_indices, group_size, bits, - transposed_w); + transposed_w, + acc); break; case float16: fp_bs_qmm_dispatch_typed( @@ -932,7 +988,8 @@ void fp_bs_qmm_dispatch( rhs_indices, group_size, bits, - transposed_w); + transposed_w, + acc); break; case bfloat16: fp_bs_qmm_dispatch_typed( @@ -944,7 +1001,8 @@ void fp_bs_qmm_dispatch( rhs_indices, group_size, bits, - transposed_w); + transposed_w, + acc); break; default: throw std::invalid_argument( @@ -965,6 +1023,16 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { auto scales = ensure_row_contiguous(scales_pre, encoder, stream()); out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } + if (x.size() == 0) { + encoder.set_output_array(out); + encoder.dispatch([out_ptr = out.data(), nbytes = out.nbytes()]() { + std::memset(out_ptr, 0, nbytes); + }); + return; + } encoder.set_input_array(x); encoder.set_input_array(w); @@ -987,14 +1055,16 @@ void QuantizedMatmul::eval_cpu(const std::vector& inputs, array& out) { out, x, w, scales, biases, group_size_, bits_, transpose_, acc); }); } else { + auto acc = qmm_accumulator(out, transpose_, encoder); 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), + acc = array::unsafe_weak_copy(acc), group_size_ = group_size_, bits_ = bits_, transpose_ = transpose_]() mutable { - fp_qmm_dispatch(out, x, w, scales, group_size_, bits_, transpose_); + fp_qmm_dispatch(out, x, w, scales, group_size_, bits_, transpose_, acc); }); } } @@ -1026,6 +1096,16 @@ void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { auto scales = ensure_row_contiguous_last_dims(scales_pre); out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } + if (x.size() == 0) { + encoder.set_output_array(out); + encoder.dispatch([out_ptr = out.data(), nbytes = out.nbytes()]() { + std::memset(out_ptr, 0, nbytes); + }); + return; + } encoder.set_input_array(x); encoder.set_input_array(w); @@ -1062,12 +1142,14 @@ void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { acc); }); } else { + auto acc = qmm_accumulator(out, transpose_, encoder); 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), + acc = array::unsafe_weak_copy(acc), group_size_ = group_size_, bits_ = bits_, transpose_ = transpose_]() mutable { @@ -1080,7 +1162,8 @@ void GatherQMM::eval_cpu(const std::vector& inputs, array& out) { rhs_indices, group_size_, bits_, - transpose_); + transpose_, + acc); }); } } @@ -1144,7 +1227,8 @@ void fp_quantize_dequantize( array& out_arr, int bits, int group_size, - size_t w_size) { + size_t w_size, + float scale_enc = 1.0f) { auto w = w_arr.data(); auto out = out_arr.data(); @@ -1154,24 +1238,26 @@ void fp_quantize_dequantize( 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 = std::max(scale, std::abs(static_cast(w[idx + j]))); } - scale /= bits == 4 ? 6.0f : 448.0f; + scale /= bits == 4 ? F4E2M1_MAX : F8E4M3_MAX; + scale *= scale_enc; if (group_size == 16) { scale = dequantize_scale(detail::ToFP8()(scale)); } else { scale = dequantize_scale(to_fp8_e8m0_round_up(scale)); } + float scale_enc_b = (scale == 0.0f) ? 0.0f : (scale_enc / scale); for (int j = 0; j < group_size; ++j) { - float w_el = scale == 0 ? 0.0f : w[idx + j] / scale; + float w_el = static_cast(w[idx + j]) * scale_enc_b; 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); + out[idx + j] = static_cast((scale / scale_enc) * output); } } } @@ -1180,13 +1266,17 @@ void dispatch_quantize_dequantize( const array& w, array& out, int bits, - int group_size) { + int group_size, + float scale_enc = 1.0f) { if (w.dtype() == float16) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); + fp_quantize_dequantize( + w, out, bits, group_size, w.size(), scale_enc); } else if (w.dtype() == bfloat16) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); + fp_quantize_dequantize( + w, out, bits, group_size, w.size(), scale_enc); } else if (w.dtype() == float32) { - fp_quantize_dequantize(w, out, bits, group_size, w.size()); + fp_quantize_dequantize( + w, out, bits, group_size, w.size(), scale_enc); } else { throw std::runtime_error( "[quantize_dequantize] Only supports floating point inputs"); @@ -1356,9 +1446,15 @@ void fast::ConvertFP8::eval_cpu( case bfloat16: unary_op(in, out, detail::ToFP8()); break; - default: + case float32: unary_op(in, out, detail::ToFP8()); break; + case float64: + unary_op(in, out, detail::ToFP8()); + break; + default: + throw std::runtime_error( + "[fast::ConvertFP8::eval_cpu] Unsupported input type."); } } else { switch (out.dtype()) { @@ -1368,52 +1464,85 @@ void fast::ConvertFP8::eval_cpu( case bfloat16: unary_op(in, out, detail::FromFP8()); break; - default: + case float32: unary_op(in, out, detail::FromFP8()); break; + case float64: + unary_op(in, out, detail::FromFP8()); + break; + default: + throw std::runtime_error( + "[fast::ConvertFP8::eval_cpu] Unsupported output type."); } } }); } void QQMatmul::eval_cpu(const std::vector& inputs, array& out) { + bool w_quantized = (inputs[1].dtype() == uint32); + if (!w_quantized) { + throw std::runtime_error("[QQMatmul] Weights must be quantized."); + } + 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); - } - 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"); + 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()); + bool has_global_scales = + (mode_ == QuantizationMode::Nvfp4 && inputs.size() == 5); + std::optional global_scale_x; + std::optional global_scale_w; + if (has_global_scales) { + global_scale_x = ensure_row_contiguous(inputs[3], encoder, stream()); + global_scale_w = ensure_row_contiguous(inputs[4], 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); + } + encoder.set_input_array(x); + 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); + auto acc = qmm_accumulator(out, true, encoder); + 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), + acc = array::unsafe_weak_copy(acc), + global_scale_x = global_scale_x + ? array::unsafe_weak_copy(*global_scale_x) + : array({}, float32, nullptr, {}), + global_scale_w = global_scale_w + ? array::unsafe_weak_copy(*global_scale_w) + : array({}, float32, nullptr, {}), + has_global_scales, + group_size = group_size_, + bits = bits_]() mutable { + float scale_enc_x = 1.0f; + float inv_scale_enc_w = 1.0f; + if (has_global_scales) { + scale_enc_x = (F8E4M3_MAX * F4E2M1_MAX) / *global_scale_x.data(); + inv_scale_enc_w = + *global_scale_w.data() / (F8E4M3_MAX * F4E2M1_MAX); + } + dispatch_quantize_dequantize(x, xhat, bits, group_size, scale_enc_x); + fp_qmm_dispatch( + out, xhat, w, scales, group_size, bits, true, acc, inv_scale_enc_w); + }); } void GatherQQMM::eval_cpu(const std::vector& inputs, array& out) { diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index cd4911e898..edd7efa4bf 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -158,6 +158,12 @@ void reduction_op( array& out, const std::vector& axes, U init) { + // Nothing to reduce just initialize the output + if (x.size() == 0) { + std::fill_n(out.data(), out.size(), init); + return; + } + ReductionPlan plan = get_reduction_plan(x, axes); auto in_ptr = x.data(); diff --git a/mlx/backend/cpu/scan.cpp b/mlx/backend/cpu/scan.cpp index 6632e44e7a..c896f837b3 100644 --- a/mlx/backend/cpu/scan.cpp +++ b/mlx/backend/cpu/scan.cpp @@ -229,7 +229,7 @@ void scan_dispatch( auto op = [](U y, T x) { if constexpr (is_floating_point_v) { if (std::isnan(y) || std::isnan(static_cast(x))) { - return std::numeric_limits::quiet_NaN(); + return static_cast(std::numeric_limits::quiet_NaN()); } } return x < y ? x : y; @@ -242,7 +242,7 @@ void scan_dispatch( auto op = [](U y, T x) { if constexpr (is_floating_point_v) { if (std::isnan(y) || std::isnan(static_cast(x))) { - return std::numeric_limits::quiet_NaN(); + return static_cast(std::numeric_limits::quiet_NaN()); } } return x < y ? y : x; diff --git a/mlx/backend/cpu/simd/math.h b/mlx/backend/cpu/simd/math.h index 5ed10e9693..45fd9db979 100644 --- a/mlx/backend/cpu/simd/math.h +++ b/mlx/backend/cpu/simd/math.h @@ -6,6 +6,18 @@ namespace mlx::core::simd { +template +inline To bit_cast(const From& from) { + static_assert(sizeof(To) == sizeof(From)); +#if defined(_MSC_VER) && !defined(__clang__) + return __builtin_bit_cast(To, from); +#else + To to; + __builtin_memcpy(&to, &from, sizeof(To)); + return to; +#endif +} + constexpr float inf = std::numeric_limits::infinity(); /** @@ -51,11 +63,17 @@ Simd exp(Simd in) { x = fma(x, fpart, 1.000000000000000f); // generate 2**ipart in the floating point representation using integer - // bitshifting - Simd epart = (Simd(ipart) + 127) << 23; + // bitshifting. Adding 1.5 * 2**23 puts the integer value of ipart in the + // low bits of the mantissa, which avoids a float to int conversion that is + // undefined for inf, nan and large values. The result is only used for + // |x| <= 88, the selects below handle the rest. Unsigned math wraps. + auto ibits = bit_cast>(ipart + 12582912.0f); + constexpr uint32_t bias = 127u - 0x4B400000u; + Simd epart = (ibits + bias) << 23; // Deal with NaN and Inf - auto result = select(isnan(x_init), x_init, (*(Simd*)&epart) * x); + auto result = + select(isnan(x_init), x_init, bit_cast>(epart) * x); result = select(x_init > 88.0f, Simd(inf), result); result = select(x_init < -88.0f, Simd(0), result); return Simd(result); diff --git a/mlx/backend/cpu/unary_ops.h b/mlx/backend/cpu/unary_ops.h index 64e20c65da..4650b5d5b1 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "mlx/backend/cpu/simd/simd.h" @@ -117,13 +118,36 @@ Simd fp32_to_bits(Simd x) { return *(Simd*)(&x); } +// Narrow double to float with round-to-odd: when the conversion is inexact, +// pick the neighboring float whose last mantissa bit is set. Rounding that +// float to a much narrower format (fp8) then gives the same result as +// rounding the double directly. Plain round-to-nearest can land exactly on an +// fp8 tie and round the wrong way, e.g. 1.0625 + 2^-30 must encode as 1.125, +// not 1.0. +template +Simd narrow_round_to_odd(Simd x) { + Simd f = x; + Simd back = f; + auto bits = fp32_to_bits(f); + auto needs_fix = (back != x) && ((bits & 1u) == 0u); + // f is the neighbor on one side of x; step one ulp to the other side. + auto overshot = abs(back) > abs(x); + auto fixed = select(overshot, bits - 1u, bits + 1u); + return fp32_from_bits(select(needs_fix, fixed, bits)); +} + struct ToFP8 { template Simd operator()(Simd f) { uint32_t fp8_max = 543 << 21; auto denorm_mask = Simd(141 << 23); Simd f_bits; - Simd f32 = f; + Simd f32; + if constexpr (std::is_same_v) { + f32 = narrow_round_to_odd(f); + } else { + f32 = f; + } f_bits = fp32_to_bits(f32); Simd result = 0u; auto sign = f_bits & 0x80000000; @@ -160,7 +184,13 @@ struct FromFP8 { 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) { +#if defined(MLX_SIMD_LIBRARY_VERSION) && MLX_SIMD_LIBRARY_VERSION < 6 + // The legacy NEON FP16 specialization only provides eight-lane vectors. + constexpr bool has_fp16_simd = N == 1 || N == simd::max_size; +#else + constexpr bool has_fp16_simd = N <= simd::max_size; +#endif + if constexpr (has_fp16_simd) { auto converted = *(Simd*)(&u); out = converted * 256.0; } else { diff --git a/mlx/backend/cuda/allocator.cpp b/mlx/backend/cuda/allocator.cpp index 4c44ed3826..ff755c0f84 100644 --- a/mlx/backend/cuda/allocator.cpp +++ b/mlx/backend/cuda/allocator.cpp @@ -18,6 +18,7 @@ #include #include +#include #include namespace mlx::core { @@ -190,10 +191,14 @@ CudaAllocator::malloc_async(size_t size, int device, cudaStream_t stream) { CudaBuffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { // If we have a lot of memory pressure try to reclaim memory from the cache. - int64_t mem_to_free = - get_active_memory() + get_cache_memory() + size - get_memory_limit(); - if (mem_to_free > 0) { - buffer_cache_.release_cached_buffers(mem_to_free); + auto cache_size = buffer_cache_.cache_size(); + assert(active_memory_ <= std::numeric_limits::max() - cache_size); + assert( + size <= + std::numeric_limits::max() - active_memory_ - cache_size); + size_t mem_required = active_memory_ + cache_size + size; + if (auto limit = memory_limit_locked(); mem_required > limit) { + buffer_cache_.release_cached_buffers(mem_required - limit); } // Try the scalar pool first @@ -225,7 +230,7 @@ CudaAllocator::malloc_async(size_t size, int device, cudaStream_t stream) { // If any cuda memory pool has too much reserved memory, clear some // memory from the cache. This prevents graph / kernel execution failing // from OOM - if (get_cache_memory() > 0) { + if (buffer_cache_.cache_size() > 0) { for (auto p : mem_pools_) { if (p) { size_t used = 0; @@ -243,8 +248,9 @@ CudaAllocator::malloc_async(size_t size, int device, cudaStream_t stream) { peak_memory_ = std::max(active_memory_, peak_memory_); // Maintain the cache below the requested limit. - if (get_cache_memory() > max_pool_size_) { - buffer_cache_.release_cached_buffers(get_cache_memory() - max_pool_size_); + if (buffer_cache_.cache_size() > max_pool_size_) { + buffer_cache_.release_cached_buffers( + buffer_cache_.cache_size() - max_pool_size_); } lock.unlock(); // Copy to unified memory here if the buffer is not on the right device. @@ -277,7 +283,7 @@ void CudaAllocator::free(Buffer buffer) { std::unique_lock lock(mutex_); active_memory_ -= buf->size; - if (get_cache_memory() < max_pool_size_) { + if (buffer_cache_.cache_size() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); } else { free_cuda_buffer(buf); @@ -342,10 +348,12 @@ void CudaAllocator::free_async(CudaBuffer& buf, cudaStream_t stream) { } size_t CudaAllocator::get_active_memory() const { + std::lock_guard lock(mutex_); return active_memory_; } size_t CudaAllocator::get_peak_memory() const { + std::lock_guard lock(mutex_); return peak_memory_; } @@ -355,6 +363,16 @@ void CudaAllocator::reset_peak_memory() { } size_t CudaAllocator::get_memory_limit() { + std::lock_guard lock(mutex_); + return memory_limit_locked(); +} + +bool CudaAllocator::over_memory_limit() { + std::lock_guard lock(mutex_); + return active_memory_ > memory_limit_locked(); +} + +size_t CudaAllocator::memory_limit_locked() { #ifdef _WIN32 int device = default_device().index; return std::min( @@ -371,6 +389,7 @@ size_t CudaAllocator::set_memory_limit(size_t limit) { } size_t CudaAllocator::get_cache_memory() const { + std::lock_guard lock(mutex_); return buffer_cache_.cache_size(); } @@ -433,6 +452,10 @@ bool can_reuse_alien_buffer(void* ptr) { return true; } +bool over_memory_limit() { + return cu::allocator().over_memory_limit(); +} + } // namespace allocator size_t get_active_memory() { diff --git a/mlx/backend/cuda/allocator.h b/mlx/backend/cuda/allocator.h index f0416c0839..dc71086a64 100644 --- a/mlx/backend/cuda/allocator.h +++ b/mlx/backend/cuda/allocator.h @@ -62,19 +62,21 @@ class CudaAllocator : public allocator::Allocator { size_t get_peak_memory() const; void reset_peak_memory(); size_t get_memory_limit(); + bool over_memory_limit(); size_t set_memory_limit(size_t limit); size_t get_cache_memory() const; size_t set_cache_limit(size_t limit); void clear_cache(); private: + size_t memory_limit_locked(); void free_cuda_buffer(CudaBuffer* buf); void free_async(CudaBuffer& buf, cudaStream_t stream = nullptr); CudaAllocator(); friend CudaAllocator& allocator(); - std::mutex mutex_; + mutable std::mutex mutex_; size_t memory_limit_; size_t free_limit_; size_t total_memory_; diff --git a/mlx/backend/cuda/arange.cu b/mlx/backend/cuda/arange.cu index a7986c7ef1..e5f2a1ef2e 100644 --- a/mlx/backend/cuda/arange.cu +++ b/mlx/backend/cuda/arange.cu @@ -38,11 +38,11 @@ __global__ void arange(T* out, IdxT size, T start, T step) { void Arange::eval_gpu(const std::vector& inputs, array& out) { nvtx3::scoped_range r("Arange::eval_gpu"); + auto& encoder = cu::get_command_encoder(stream()); + out.set_data(cu::malloc_async(out.nbytes(), encoder)); if (out.size() == 0) { return; } - auto& encoder = cu::get_command_encoder(stream()); - out.set_data(cu::malloc_async(out.nbytes(), encoder)); encoder.set_output_array(out); dispatch_int_float_types(out.dtype(), "Arange", [&](auto type_tag) { diff --git a/mlx/backend/cuda/arg_reduce.cu b/mlx/backend/cuda/arg_reduce.cu index 39abb274aa..61aa1ecbce 100644 --- a/mlx/backend/cuda/arg_reduce.cu +++ b/mlx/backend/cuda/arg_reduce.cu @@ -152,6 +152,9 @@ void ArgReduce::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); out.set_data(cu::malloc_async(out.nbytes(), encoder)); + if (out.size() == 0) { + return; + } // Prepare the shapes, strides and axis arguments. Shape shape = remove_index(in.shape(), axis_); diff --git a/mlx/backend/cuda/compiled.cpp b/mlx/backend/cuda/compiled.cpp index a363cf9c31..66698ea7a5 100644 --- a/mlx/backend/cuda/compiled.cpp +++ b/mlx/backend/cuda/compiled.cpp @@ -228,6 +228,15 @@ void Compiled::eval_gpu( nvtx3::scoped_range r("Compiled::eval_gpu"); auto& s = stream(); + // All outputs have the same shape + if (outputs[0].size() == 0) { + auto& encoder = cu::get_command_encoder(s); + for (auto& out : outputs) { + out.set_data(cu::malloc_async(0, encoder)); + } + return; + } + // Determine the work per thread for the vectorized reads/writes. We take it // as 16 over the max itemsize for the outputs. Another heuristic could be // over the max itemsize of all arrays. diff --git a/mlx/backend/cuda/conv.cpp b/mlx/backend/cuda/conv.cpp index 42bd2e8331..3019142b31 100644 --- a/mlx/backend/cuda/conv.cpp +++ b/mlx/backend/cuda/conv.cpp @@ -258,17 +258,30 @@ void init_cudnn_conv_cache() { conv_cache(); } +void clear_cudnn_conv_cache() { + conv_cache().clear(); +} + void Convolution::eval_gpu(const std::vector& inputs, array& out_) { nvtx3::scoped_range r("Convolution::eval_gpu"); + auto& s = stream(); + auto& encoder = cu::get_command_encoder(s); if (out_.size() == 0) { + out_.set_data(cu::malloc_async(0, encoder)); return; } - auto& s = stream(); - auto& encoder = cu::get_command_encoder(s); assert(inputs.size() == 2); array in = inputs[0]; array wt = inputs[1]; + + // Return 0s if either input is empty + if (in.size() == 0 || wt.size() == 0) { + array zero(0, out_.dtype()); + fill_gpu(zero, out_, s); + encoder.add_temporary(std::move(zero)); + return; + } array out = out_; out.set_data(cu::malloc_async(out.nbytes(), encoder)); Dtype dtype = out.dtype(); diff --git a/mlx/backend/cuda/copy.cu b/mlx/backend/cuda/copy.cu index a19d15550d..74b2711b8f 100644 --- a/mlx/backend/cuda/copy.cu +++ b/mlx/backend/cuda/copy.cu @@ -99,11 +99,11 @@ void copy_gpu_inplace( } void fill_gpu(const array& in, array& out, const Stream& s) { + auto& encoder = cu::get_command_encoder(s); + out.set_data(cu::malloc_async(out.nbytes(), encoder)); if (out.size() == 0) { return; } - auto& encoder = cu::get_command_encoder(s); - out.set_data(cu::malloc_async(out.nbytes(), encoder)); encoder.set_input_array(in); encoder.set_output_array(out); copy_contiguous(encoder, CopyType::Scalar, in, out, 0, 0); diff --git a/mlx/backend/cuda/cross_entropy.cu b/mlx/backend/cuda/cross_entropy.cu index 23b0689be3..e7d8299769 100644 --- a/mlx/backend/cuda/cross_entropy.cu +++ b/mlx/backend/cuda/cross_entropy.cu @@ -135,6 +135,9 @@ void CrossEntropy::eval_gpu( std::vector& outputs) { nvtx3::scoped_range r("CrossEntropy::eval_gpu"); assert(inputs.size() == 2); // logits and target + if (inputs[0].size() == 0) { + throw std::invalid_argument("[cross_entropy] Received empty array."); + } auto& s = stream(); auto& out = outputs[0]; auto& encoder = cu::get_command_encoder(s); @@ -179,6 +182,9 @@ void CrossEntropyVJP::eval_gpu( std::vector& outputs) { nvtx3::scoped_range r("CrossEntropyVJP::eval_gpu"); assert(inputs.size() == 4); // logits, target, loss, cotangent + if (inputs[0].size() == 0) { + throw std::invalid_argument("[cross_entropy] Received empty array."); + } auto& s = stream(); auto& out = outputs[0]; auto& encoder = cu::get_command_encoder(s); diff --git a/mlx/backend/cuda/cudnn_utils.cpp b/mlx/backend/cuda/cudnn_utils.cpp index eee33068c6..e5c6b0dde2 100644 --- a/mlx/backend/cuda/cudnn_utils.cpp +++ b/mlx/backend/cuda/cudnn_utils.cpp @@ -2,7 +2,8 @@ #include "mlx/backend/cuda/cudnn_utils.h" #include "mlx/backend/cuda/device.h" -#include "mlx/backend/gpu/device_info.h" + +#include namespace mlx::core { @@ -48,16 +49,37 @@ inline auto nhwc_to_nchw(const array& x) { return std::make_tuple(std::move(shape), std::move(strides)); } -auto& cudnn_handles_cache() { - struct CudnnHandle { - ~CudnnHandle() { - if (handle) { - CHECK_CUDNN_ERROR(cudnnDestroy(handle)); +class CudnnHandle { + public: + explicit CudnnHandle(cu::Device& device) : device_(device) { + device_.make_current(); + CHECK_CUDNN_ERROR(cudnnCreate(&handle_)); + } + + ~CudnnHandle() { + if (handle_) { + try { + device_.make_current(); + cudnnDestroy(handle_); + } catch (...) { } } - cudnnHandle_t handle{nullptr}; - }; - static thread_local std::vector cache(gpu::device_count()); + } + + CudnnHandle(const CudnnHandle&) = delete; + CudnnHandle& operator=(const CudnnHandle&) = delete; + + cudnnHandle_t handle() const { + return handle_; + } + + private: + cu::Device& device_; + cudnnHandle_t handle_{nullptr}; +}; + +auto& cudnn_handles_cache() { + static thread_local std::unordered_map cache; return cache; } @@ -78,18 +100,19 @@ void check_cudnn_error(const char* name, fe::error_t err) { } cudnnHandle_t get_cudnn_handle(cu::Device& device) { - auto& storage = cudnn_handles_cache().at(device.cuda_device()); - if (!storage.handle) { - device.make_current(); - CHECK_CUDNN_ERROR(cudnnCreate(&storage.handle)); - } - return storage.handle; + auto& cache = cudnn_handles_cache(); + auto it = cache.try_emplace(device.cuda_device(), device).first; + return it->second.handle(); } void init_cudnn_handles_cache() { cudnn_handles_cache(); } +void clear_cudnn_handles_cache() { + cudnn_handles_cache().clear(); +} + fe::error_t DnnGraph::prepare() { RETURN_IF_ERROR(validate()); try { diff --git a/mlx/backend/cuda/cudnn_utils.h b/mlx/backend/cuda/cudnn_utils.h index 40820e5921..785629db77 100644 --- a/mlx/backend/cuda/cudnn_utils.h +++ b/mlx/backend/cuda/cudnn_utils.h @@ -29,8 +29,11 @@ void check_cudnn_error(const char* name, fe::error_t err); cudnnHandle_t get_cudnn_handle(cu::Device& device); void init_cudnn_handles_cache(); +void clear_cudnn_handles_cache(); void init_cudnn_conv_cache(); +void clear_cudnn_conv_cache(); void init_cudnn_sdpa_cache(); +void clear_cudnn_sdpa_cache(); // Return pointer alignment of |x|'s data. inline uint8_t get_alignment(const array& x) { diff --git a/mlx/backend/cuda/device/qmm_sm80.cuh b/mlx/backend/cuda/device/qmm_sm80.cuh index 5fea5b51b2..f52c597a44 100644 --- a/mlx/backend/cuda/device/qmm_sm80.cuh +++ b/mlx/backend/cuda/device/qmm_sm80.cuh @@ -25,6 +25,15 @@ union SharedStorage { } epilogue; }; +template +inline constexpr auto make_pipeline_depth(TileM bM) { + if constexpr (is_static_v) { + return Int<(TileM::value == 128 ? 2 : 3)>{}; + } else { + return bM == 128 ? 2 : 3; + } +} + template inline constexpr auto make_smem_layouts(CtaTiler cta_tiler) { // Note: Kernel launcher assumes cosize being same for all KMajor. @@ -34,7 +43,7 @@ inline constexpr auto make_smem_layouts(CtaTiler cta_tiler) { auto swizzle_ab = composition(Swizzle<3,3,3>{}, Layout>, Stride<_8,Stride<_1,_64>>>{}); - auto bP = Int<3>{}; // pipeline + auto bP = make_pipeline_depth(bM); auto sA_layout = tile_to_shape(swizzle_ab, make_shape(bM, bK, bP)); auto sB_layout = tile_to_shape(swizzle_ab, make_shape(bN, bK, bP)); @@ -52,7 +61,7 @@ inline constexpr auto make_tiled_mma() { cuda::std::is_same_v, SM80_16x8x16_F32F16F16F32_TN, SM80_16x8x16_F32BF16BF16F32_TN>; - if constexpr (TileM >= 32) { + if constexpr (TileM >= 32 && TileM != 128) { return make_tiled_mma(Atom{}, Layout>{}, Tile<_32,_32,_16>{}); } else { return make_tiled_mma(Atom{}, Layout>{}, Tile<_16,_32,_16>{}); diff --git a/mlx/backend/cuda/eval.cpp b/mlx/backend/cuda/eval.cpp index 9f8d24e033..a690000293 100644 --- a/mlx/backend/cuda/eval.cpp +++ b/mlx/backend/cuda/eval.cpp @@ -93,6 +93,21 @@ void synchronize(Stream s) { } void clear_streams() { + auto sync = [](auto& encoders) { + for (auto& item : encoders) { + item.second.synchronize(); + } + }; + sync(cu::get_command_encoders()); + if (is_main_thread()) { + sync(cu::get_global_command_encoders()); + } + + // Graph caches reference the cuDNN handle. Destroy both before thread exit. + clear_cudnn_conv_cache(); + clear_cudnn_sdpa_cache(); + clear_cudnn_handles_cache(); + cu::get_command_encoders().clear(); if (is_main_thread()) { cu::get_global_command_encoders().clear(); diff --git a/mlx/backend/cuda/fft.cu b/mlx/backend/cuda/fft.cu index a657bb2dda..5de4f228d0 100644 --- a/mlx/backend/cuda/fft.cu +++ b/mlx/backend/cuda/fft.cu @@ -381,6 +381,7 @@ void FFT::eval_gpu(const std::vector& inputs, array& out) { auto& in = inputs[0]; if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); return; } diff --git a/mlx/backend/cuda/gated_delta_update.cu b/mlx/backend/cuda/gated_delta_update.cu index 0bdd69eb9e..bf392ff707 100644 --- a/mlx/backend/cuda/gated_delta_update.cu +++ b/mlx/backend/cuda/gated_delta_update.cu @@ -204,6 +204,13 @@ void GatedDeltaUpdate::eval_gpu( auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + // With no steps the final state is the initial state + if (outputs[0].size() == 0) { + outputs[0].set_data(cu::malloc_async(0, encoder)); + copy_gpu(inputs[5], outputs[1], CopyType::General, s); + return; + } + auto q = ensure_row_contiguous(inputs[0], encoder, s); auto k = ensure_row_contiguous(inputs[1], encoder, s); auto v = ensure_row_contiguous(inputs[2], encoder, s); diff --git a/mlx/backend/cuda/indexing.cpp b/mlx/backend/cuda/indexing.cpp index cc0ef4f740..9880b69fbd 100644 --- a/mlx/backend/cuda/indexing.cpp +++ b/mlx/backend/cuda/indexing.cpp @@ -588,6 +588,7 @@ void SliceUpdate::eval_gpu(const std::vector& inputs, array& out) { nvtx3::scoped_range r("SliceUpdate::eval_gpu"); assert(inputs.size() == 2); if (out.size() == 0) { + out.set_data(cu::malloc_async(0, cu::get_command_encoder(stream()))); return; } diff --git a/mlx/backend/cuda/layer_norm.cu b/mlx/backend/cuda/layer_norm.cu index 9c8d46fbec..9feba1a833 100644 --- a/mlx/backend/cuda/layer_norm.cu +++ b/mlx/backend/cuda/layer_norm.cu @@ -232,6 +232,11 @@ void LayerNorm::eval_gpu( auto& out = outputs[0]; auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + // Make sure that the last dimension is contiguous. auto set_output = [&s, &out, &encoder](const array& x) { bool no_copy = x.flags().contiguous && x.strides()[x.ndim() - 1] == 1; @@ -298,6 +303,16 @@ void LayerNormVJP::eval_gpu( auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + // Return 0s if the input is empty + if (inputs[0].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + encoder.add_temporary(std::move(zero)); + return; + } + // Ensure row contiguity. We could relax this step by checking that the array // is contiguous (no broadcasts or holes) and that the input strides are the // same as the cotangent strides but for now this is simpler. @@ -365,6 +380,11 @@ void LayerNormVJP::eval_gpu( ReductionPlan plan( ReductionOpType::ContiguousStridedReduce, {n_rows}, {axis_size}); col_reduce(encoder, g, gb, Reduce::ReduceType::Sum, {0}, plan); + } else { + gb.set_data(cu::malloc_async(gb.nbytes(), encoder)); + } + if (!has_w) { + gw.set_data(cu::malloc_async(gw.nbytes(), encoder)); } // Insert dependency if `g` was donated diff --git a/mlx/backend/cuda/load.cpp b/mlx/backend/cuda/load.cpp index 2acc52fd10..3eaf22f6c4 100644 --- a/mlx/backend/cuda/load.cpp +++ b/mlx/backend/cuda/load.cpp @@ -33,6 +33,9 @@ void Load::eval_gpu(const std::vector& inputs, array& out) { auto size = out.size(); auto nbytes = size * out.itemsize(); out.set_data(cu::malloc_async(nbytes, encoder)); + if (nbytes == 0) { + return; + } auto out_ptr = malloc(nbytes); reader_->read(static_cast(out_ptr), nbytes, offset_); if (swap_endianness_) { diff --git a/mlx/backend/cuda/logsumexp.cu b/mlx/backend/cuda/logsumexp.cu index 25d24faf26..afd05d3dc2 100644 --- a/mlx/backend/cuda/logsumexp.cu +++ b/mlx/backend/cuda/logsumexp.cu @@ -102,6 +102,11 @@ void LogSumExp::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + // Make sure that the last dimension is contiguous. auto ensure_contiguous = [&s, &encoder](const array& x) { if (x.flags().contiguous && x.strides()[x.ndim() - 1] == 1) { diff --git a/mlx/backend/cuda/matmul.cpp b/mlx/backend/cuda/matmul.cpp index e430af8f38..2b64813711 100644 --- a/mlx/backend/cuda/matmul.cpp +++ b/mlx/backend/cuda/matmul.cpp @@ -81,7 +81,7 @@ void gemm_and_bias( // Check and collapse batch dimensions auto [batch_shape, a_batch_strides, b_batch_strides] = collapse_batches(a, b); - auto batch_count = out.size() / (M * N); + auto batch_count = out.size() / (int64_t(M) * N); // Collapse batches into M if needed if (batch_count > 1 && !a_transposed && batch_shape.size() == 1 && @@ -257,6 +257,11 @@ void AddMM::eval_gpu(const std::vector& inputs, array& out) { auto& b_pre = inputs[1]; auto c = inputs[2]; + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + ///////////////////////////////////////////////////////////////////////////// // Init checks and prep @@ -316,7 +321,7 @@ void AddMM::eval_gpu(const std::vector& inputs, array& out) { auto [batch_shape, a_batch_strides, b_batch_strides, c_batch_strides] = collapse_batches(a, b, c); - auto batch_count = out.size() / (M * N); + auto batch_count = out.size() / (int64_t(M) * N); // Collapse batches into M if needed if (batch_count > 1 && !a_transposed && batch_shape.size() == 1 && diff --git a/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu b/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu index 4ce2817d34..1d81420611 100644 --- a/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu +++ b/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu @@ -14,8 +14,8 @@ namespace mlx::core { namespace { -inline auto make_cta_tiler(int m, int group_size) { - int tile_m = std::max(16, std::min(64, next_power_of_2(m))); +inline auto make_cta_tiler(int m, int group_size, int tile_m_max) { + int tile_m = std::max(16, std::min(tile_m_max, next_power_of_2(m))); int tile_n = 128; int tile_k = std::max(64, group_size); return cute::make_shape(tile_m, tile_n, tile_k); @@ -25,6 +25,22 @@ inline int get_quantized_batch_count(const array& w) { return w.ndim() > 2 ? w.size() / (w.shape(-1) * w.shape(-2)) : 1; } +bool use_128_row_tiles(int m, int n, int k, int l, cu::Device& device) { + if (m < 512 || k < 1024) { + return false; + } + int sm_count = 0; + CHECK_CUDA_ERROR(cudaDeviceGetAttribute( + &sm_count, cudaDevAttrMultiProcessorCount, device.cuda_device())); + auto waves = [&](int tile_m) { + int64_t ctas = + int64_t(cute::ceil_div(m, tile_m)) * cute::ceil_div(n, 128) * l; + return cute::ceil_div(ctas, int64_t(sm_count)); + }; + int64_t waves_64 = waves(64); + return waves_64 >= 4 && 9 * waves(128) < 5 * waves_64; +} + } // namespace void qmm_sm80( @@ -40,28 +56,38 @@ void qmm_sm80( QuantizationMode mode, cu::CommandEncoder& encoder) { auto [m, n, k, l, broadcast_b] = make_problem_shape(x, w, out); - auto cta_tiler = make_cta_tiler(m, group_size); + bool large_tiles = !lhs_indices && !rhs_indices && + use_128_row_tiles(m, n, k, l, encoder.device()); + auto cta_tiler = make_cta_tiler(m, group_size, large_tiles ? 128 : 64); + int tile_m = cute::size<0>(cta_tiler); + bool grouped_tiles = !lhs_indices && !rhs_indices && tile_m >= 64; std::string module_name = fmt::format( "qmm_sm80_tn_{}_m{}_b{}_g{}_{}", dtype_to_string(x.dtype()), - cute::size<0>(cta_tiler), + grouped_tiles ? "64_128" : std::to_string(tile_m), bits, group_size, quantization_mode_to_string(mode)); auto [ctype_x, ctype_q, ctype_s] = get_qmm_cutlass_types(x, bits, mode); - std::string kernel_name = fmt::format( - "mlx::core::cu::qmm_sm80_kernel<{}, {}, {}, {}, {}>", - group_size, - ctype_x, - ctype_q, - ctype_s, - cta_tiler_to_string(cta_tiler)); + auto make_kernel_name = [&](int tile_m) { + return fmt::format( + "mlx::core::cu::qmm_sm80_kernel<{}, {}, {}, {}, {}>", + group_size, + ctype_x, + ctype_q, + ctype_s, + cta_tiler_to_string(make_cta_tiler(tile_m, group_size, tile_m))); + }; + std::string kernel_name = make_kernel_name(tile_m); cu::JitModule& mod = cu::get_jit_module(encoder.device(), module_name, [&]() { + auto kernel_names = grouped_tiles + ? std::vector{make_kernel_name(64), make_kernel_name(128)} + : std::vector{kernel_name}; return std::make_tuple( - false, jit_source_qmm_sm80, std::vector{kernel_name}); + false, jit_source_qmm_sm80, std::move(kernel_names)); }); encoder.set_input_array(x); @@ -168,7 +194,7 @@ void gather_qmm_rhs_sm80( int n = out.shape(-1); int k = x.shape(-1); int group_count = get_quantized_batch_count(w); - auto cta_tiler = make_cta_tiler(m, group_size); + auto cta_tiler = make_cta_tiler(m, group_size, 64); std::string module_name = fmt::format( "gather_qmm_rhs_sm80_tn_{}_m{}_b{}_g{}_{}", diff --git a/mlx/backend/cuda/quantized/qqmm.cpp b/mlx/backend/cuda/quantized/qqmm.cpp index 5a9fba33d5..388fa3b4f9 100644 --- a/mlx/backend/cuda/quantized/qqmm.cpp +++ b/mlx/backend/cuda/quantized/qqmm.cpp @@ -102,6 +102,9 @@ void QQMatmul::eval_gpu(const std::vector& inputs, array& out) { const array& w_pre = inputs[1]; out.set_data(cu::malloc_async(out.nbytes(), encoder)); + if (out.size() == 0) { + return; + } // - 2 inputs: x, w (non-quantized w) // - 3 inputs: x, w, scales_w (quantized w) @@ -219,6 +222,9 @@ void GatherQQMM::eval_gpu(const std::vector& inputs, array& out) { const array& rhs_indices = ensure_row_contiguous(inputs[3], encoder, s); out.set_data(cu::malloc_async(out.nbytes(), encoder)); + if (out.size() == 0) { + return; + } // - 4 inputs: x, w, lhs_indices, rhs_indices (non-quantized w) // - 5 inputs: x, w, lhs_indices, rhs_indices, scales_w (quantized w) diff --git a/mlx/backend/cuda/quantized/quantized.cpp b/mlx/backend/cuda/quantized/quantized.cpp index a69c49d8f8..3d44d90260 100644 --- a/mlx/backend/cuda/quantized/quantized.cpp +++ b/mlx/backend/cuda/quantized/quantized.cpp @@ -4,6 +4,7 @@ #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/quantized/qmm/qmm.h" #include "mlx/backend/cuda/quantized/quantized_utils.h" +#include "mlx/backend/gpu/copy.h" #include "mlx/dtype_utils.h" #include "mlx/fast_primitives.h" #include "mlx/primitives.h" @@ -17,6 +18,19 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + + // Return 0s if x is empty + if (inputs[0].size() == 0) { + array zero(0, out.dtype()); + encoder.add_temporary(zero); + fill_gpu(zero, out, s); + return; + } + array x = ensure_row_contiguous(inputs[0], encoder, s); const array& w = inputs[1]; const array& scales = inputs[2]; @@ -156,6 +170,19 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + + // Return 0s if x is empty + if (inputs[0].size() == 0) { + array zero(0, out.dtype()); + encoder.add_temporary(zero); + fill_gpu(zero, out, s); + return; + } + array x = ensure_row_contiguous(inputs[0], encoder, s); const array& w = inputs[1]; const array& scales = inputs[2]; @@ -326,6 +353,12 @@ void fast::Quantize::eval_gpu( nvtx3::scoped_range r("Quantize::eval_gpu"); auto& s = stream(); auto& enc = cu::get_command_encoder(s); + if (inputs[0].size() == 0) { + for (auto& out : outputs) { + out.set_data(cu::malloc_async(out.nbytes(), enc)); + } + return; + } if (dequantize_) { auto wq = ensure_row_contiguous(inputs[0], enc, s); auto scales = ensure_row_contiguous(inputs[1], enc, s); diff --git a/mlx/backend/cuda/random.cu b/mlx/backend/cuda/random.cu index 1a485134d9..de68d8674d 100644 --- a/mlx/backend/cuda/random.cu +++ b/mlx/backend/cuda/random.cu @@ -139,10 +139,6 @@ void RandomBits::eval_gpu(const std::vector& inputs, array& out) { // keys has shape (N1, ..., NK, 2) // out has shape (N1, ..., NK, M1, M2, ...) auto& keys = inputs[0]; - size_t num_keys = keys.size() / 2; - - size_t elems_per_key = out.size() / num_keys; - size_t bytes_per_key = out.itemsize() * elems_per_key; auto& s = stream(); auto& encoder = cu::get_command_encoder(s); out.set_data(cu::malloc_async(out.nbytes(), encoder)); @@ -150,6 +146,10 @@ void RandomBits::eval_gpu(const std::vector& inputs, array& out) { return; } + size_t num_keys = keys.size() / 2; + size_t elems_per_key = out.size() / num_keys; + size_t bytes_per_key = out.itemsize() * elems_per_key; + size_t out_per_key = (bytes_per_key + 4 - 1) / 4; size_t half_size = out_per_key / 2; diff --git a/mlx/backend/cuda/reduce/reduce_ops.cuh b/mlx/backend/cuda/reduce/reduce_ops.cuh index 6c6b1827ce..db4f13a4e8 100644 --- a/mlx/backend/cuda/reduce/reduce_ops.cuh +++ b/mlx/backend/cuda/reduce/reduce_ops.cuh @@ -154,6 +154,33 @@ struct ReduceResult { using type = T; }; +// Traits to get the accumulator type of reduce op. Half precision sums and +// products accumulate in float32 to keep precision on long reductions. +template +struct ReduceAccum { + using type = typename ReduceResult::type; +}; + +template <> +struct ReduceAccum { + using type = float; +}; + +template <> +struct ReduceAccum { + using type = float; +}; + +template <> +struct ReduceAccum { + using type = float; +}; + +template <> +struct ReduceAccum { + using type = float; +}; + // Traits to get the init value of reduce op. template struct ReduceInit; diff --git a/mlx/backend/cuda/reduce/row_reduce.cu b/mlx/backend/cuda/reduce/row_reduce.cu index 1dd40d14bd..cb8333bcfd 100644 --- a/mlx/backend/cuda/reduce/row_reduce.cu +++ b/mlx/backend/cuda/reduce/row_reduce.cu @@ -31,6 +31,12 @@ struct RowReduceArgs { // The number of rows we are reducing. Namely prod(reduce_shape). size_t non_row_reductions; + // Split the rows of each output over `splits` blocks of `chunk` rows. Used + // when there are few outputs. + size_t n_out{0}; + int splits{1}; + size_t chunk{0}; + RowReduceArgs( const array& in, const ReductionPlan& plan, @@ -80,18 +86,24 @@ struct RowReduceArgs { } }; -template +template < + typename T, + typename U, + typename A, + typename ReduceOp, + int N = 4, + int M = 1> __global__ void row_reduce_simple(const T* in, U* out, size_t n_rows, int size) { auto grid = cg::this_grid(); auto block = cg::this_thread_block(); auto warp = cg::tiled_partition(block); - const U init = cu::ReduceInit::value(); + const A init = cast_to(cu::ReduceInit::value()); ReduceOp op; AlignedVector vals[M]; - AlignedVector accs; + AlignedVector accs; for (int i = 0; i < M; i++) { accs[i] = init; } @@ -109,7 +121,7 @@ row_reduce_simple(const T* in, U* out, size_t n_rows, int size) { } for (int k = 0; k < M; k++) { for (int j = 0; j < N; j++) { - accs[k] = op(accs[k], cast_to(vals[k][j])); + accs[k] = op(accs[k], cast_to(vals[k][j])); } } @@ -126,43 +138,63 @@ row_reduce_simple(const T* in, U* out, size_t n_rows, int size) { } for (int k = 0; k < M; k++) { for (int j = 0; j < N; j++) { - accs[k] = op(accs[k], cast_to(vals[k][j])); + accs[k] = op(accs[k], cast_to(vals[k][j])); } } } - __shared__ U shared_accumulators[32 * M]; + __shared__ A shared_accumulators[32 * M]; block_reduce(block, warp, accs.val, shared_accumulators, op, init); if (block.thread_rank() == 0) { + AlignedVector results; + for (int i = 0; i < M; i++) { + results[i] = cast_to(accs[i]); + } if (grid.block_rank() * M + M <= n_rows) { - store_vector(out, 0, accs); + store_vector(out, 0, results); } else { short offset = grid.block_rank() * M + M - n_rows; for (int i = offset; i < M; i++) { - out[i] = accs[i]; + out[i] = results[i]; } } } } -template +template < + typename T, + typename U, + typename A, + typename Op, + int NDIM, + int N_READS = 4> __global__ void row_reduce_looped( const T* in, U* out, + A* partials, const __grid_constant__ RowReduceArgs args) { auto grid = cg::this_grid(); auto block = cg::this_thread_block(); auto warp = cg::tiled_partition(block); + // Compute the output index and the rows that this block reduces size_t out_idx = grid.block_rank(); + size_t first = 0; + size_t last = args.non_row_reductions; + if (args.splits > 1) { + out_idx = grid.block_rank() % args.n_out; + first = (grid.block_rank() / args.n_out) * args.chunk; + last = min(first + args.chunk, args.non_row_reductions); + } Op op; - U total[1]; - U init = ReduceInit::value(); + A total[1]; + A init = cast_to(ReduceInit::value()); total[0] = init; LoopedElemToLoc 2)> loop(args.reduce_ndim); + loop.next(first, args.reduce_shape.data(), args.reduce_strides.data()); const size_t full_blocks = args.row_size / (block.size() * N_READS); const size_t final_offset = full_blocks * (block.size() * N_READS); @@ -177,13 +209,13 @@ __global__ void row_reduce_looped( (final_offset + block.thread_rank() * N_READS + i) < args.row_size; } - for (size_t n = 0; n < args.non_row_reductions; n++) { + for (size_t n = first; n < last; n++) { const T* inlocal = in + loop.location(); for (size_t r = 0; r < full_blocks; r++) { auto vals = load_vector(inlocal, 0); for (int i = 0; i < N_READS; i++) { - total[0] = op(total[0], cast_to(vals[i])); + total[0] = op(total[0], cast_to(vals[i])); } inlocal += block.size() * N_READS; } @@ -194,7 +226,7 @@ __global__ void row_reduce_looped( vals[i] = mask[i] ? inlocal[i] : cast_to(init); } for (int i = 0; i < N_READS; i++) { - total[0] = op(total[0], cast_to(vals[i])); + total[0] = op(total[0], cast_to(vals[i])); } } @@ -204,13 +236,13 @@ __global__ void row_reduce_looped( // Aligned case else { - for (size_t n = 0; n < args.non_row_reductions; n++) { + for (size_t n = first; n < last; n++) { const T* inlocal = in + loop.location(); for (size_t r = 0; r < full_blocks; r++) { auto vals = load_vector(inlocal, 0); for (int i = 0; i < N_READS; i++) { - total[0] = op(total[0], cast_to(vals[i])); + total[0] = op(total[0], cast_to(vals[i])); } inlocal += block.size() * N_READS; } @@ -219,16 +251,48 @@ __global__ void row_reduce_looped( } } - __shared__ U shared_accumulators[32]; + __shared__ A shared_accumulators[32]; block_reduce(block, warp, total, shared_accumulators, op, init); if (block.thread_rank() == 0) { - out[out_idx] = total[0]; + if (args.splits > 1) { + partials[grid.block_rank()] = total[0]; + } else { + out[out_idx] = cast_to(total[0]); + } + } +} + +// Second pass of a split row reduce. Each warp reduces the partial results of +// one output. +template +__global__ void +row_reduce_combine(const A* partials, U* out, size_t n_out, int splits) { + auto warp = cg::tiled_partition(cg::this_thread_block()); + size_t i = cg::this_grid().thread_rank() / WARP_SIZE; + if (i >= n_out) { + return; + } + Op op; + A total = cast_to(ReduceInit::value()); + for (int s = warp.thread_rank(); s < splits; s += WARP_SIZE) { + total = op(total, partials[s * n_out + i]); + } + total = cg::reduce(warp, total, op); + if (warp.thread_rank() == 0) { + out[i] = cast_to(total); } } } // namespace cu +// Split the looped row reduce to reach SPLIT_TARGET_THREADS threads, with at +// least SPLIT_MIN_ROWS rows per block. Fewer than SPLIT_MIN_SPLITS blocks per +// output do not pay for the second pass. +constexpr size_t SPLIT_TARGET_THREADS = 1 << 17; +constexpr size_t SPLIT_MIN_ROWS = 16; +constexpr size_t SPLIT_MIN_SPLITS = 4; + void row_reduce_simple( cu::CommandEncoder& encoder, const array& in, @@ -249,6 +313,7 @@ void row_reduce_simple( using OP = MLX_GET_TYPE(reduce_type_tag); using T = cuda_type_t; using U = typename cu::ReduceResult::type; + using A = typename cu::ReduceAccum::type; constexpr int N_READS = 16 / sizeof(T); @@ -262,10 +327,10 @@ void row_reduce_simple( dim3 block(threads, 1, 1); // Pick the kernel - auto kernel = cu::row_reduce_simple; + auto kernel = cu::row_reduce_simple; if (grid.x >= 1024) { grid.x = (grid.x + 1) / 2; - kernel = cu::row_reduce_simple; + kernel = cu::row_reduce_simple; } int size = plan.shape.back(); @@ -300,6 +365,7 @@ void row_reduce_looped( using OP = MLX_GET_TYPE(reduce_type_tag); using T = cuda_type_t; using U = typename cu::ReduceResult::type; + using A = typename cu::ReduceAccum::type; constexpr int N_READS = 16 / sizeof(T); @@ -313,14 +379,63 @@ void row_reduce_looped( int threads = warps * WARP_SIZE; dim3 block(threads, 1, 1); + // Split the rows of each output over more blocks if the grid is small. + // LoopedElemToLoc takes the first row of a split as an int. + args.n_out = out.size(); + size_t total_threads = args.n_out * threads; + size_t splits = std::min( + (SPLIT_TARGET_THREADS + total_threads - 1) / total_threads, + args.non_row_reductions / SPLIT_MIN_ROWS); + if (splits >= SPLIT_MIN_SPLITS && args.non_row_reductions <= INT32_MAX) { + args.chunk = (args.non_row_reductions + splits - 1) / splits; + args.splits = (args.non_row_reductions + args.chunk - 1) / args.chunk; + } + // Pick the kernel - auto kernel = cu::row_reduce_looped; + auto kernel = cu::row_reduce_looped; dispatch_reduce_ndim(args.reduce_ndim, [&](auto reduce_ndim) { - kernel = cu::row_reduce_looped; + kernel = cu::row_reduce_looped; }); + if (args.splits == 1) { + encoder.add_kernel_node( + kernel, + grid, + block, + gpu_ptr(in), + gpu_ptr(out), + static_cast(nullptr), + args); + return; + } + + Dtype partials_type = std::is_same_v ? float32 : out.dtype(); + array partials( + {args.splits, static_cast(args.n_out)}, + partials_type, + nullptr, + {}); + partials.set_data(cu::malloc_async(partials.nbytes(), encoder)); + encoder.add_temporary(partials); + encoder.set_output_array(partials); encoder.add_kernel_node( - kernel, grid, block, gpu_ptr(in), gpu_ptr(out), args); + kernel, + dim3(args.n_out * args.splits), + block, + gpu_ptr(in), + gpu_ptr(out), + gpu_ptr(partials), + args); + encoder.set_input_array(partials); + encoder.set_output_array(out); + encoder.add_kernel_node( + cu::row_reduce_combine, + dim3((args.n_out * WARP_SIZE + 255) / 256), + dim3(256), + gpu_ptr(partials), + gpu_ptr(out), + args.n_out, + args.splits); }); }); } @@ -344,7 +459,9 @@ void row_reduce( // // It is a general row reduction. We are computing 1 output per // threadblock. We read the fastest moving axis vectorized and loop over - // the rest of the axes. + // the rest of the axes. If there are few outputs, we split the rows of + // each output over many threadblocks and reduce the partial results in a + // second pass. // // Notes: We opt to read as much in order as possible and leave // transpositions as they are (contrary to our Metal backend). diff --git a/mlx/backend/cuda/rms_norm.cu b/mlx/backend/cuda/rms_norm.cu index e4c0702a9f..087d3d6fea 100644 --- a/mlx/backend/cuda/rms_norm.cu +++ b/mlx/backend/cuda/rms_norm.cu @@ -544,6 +544,11 @@ void RMSNorm::eval_gpu( auto& out = outputs[0]; auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + // Make sure that the last dimension is contiguous. auto set_output = [&s, &out, &encoder](const array& x) { bool no_copy = x.flags().contiguous && x.strides()[x.ndim() - 1] == 1; @@ -676,6 +681,16 @@ void RMSNormVJP::eval_gpu( auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + // Return 0s if the input is empty + if (inputs[0].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + encoder.add_temporary(std::move(zero)); + return; + } + // Ensure row contiguity. We could relax this step by checking that the array // is contiguous (no broadcasts or holes) and that the input strides are the // same as the cotangent strides but for now this is simpler. @@ -715,6 +730,9 @@ void RMSNormVJP::eval_gpu( if (g_copied && !g_in_gx) { encoder.add_temporary(g); } + if (!has_w) { + gw.set_data(cu::malloc_async(gw.nbytes(), encoder)); + } int32_t axis_size = x.shape().back(); int32_t n_rows = x.data_size() / axis_size; diff --git a/mlx/backend/cuda/rope.cu b/mlx/backend/cuda/rope.cu index cd7e68ceb2..d56dabb5ad 100644 --- a/mlx/backend/cuda/rope.cu +++ b/mlx/backend/cuda/rope.cu @@ -257,6 +257,11 @@ void RoPE::eval_gpu( auto& offset = inputs[1]; auto& out = outputs[0]; + if (in.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + cuda::std::array strides; cuda::std::array out_strides; bool donated = false; diff --git a/mlx/backend/cuda/scaled_dot_product_attention.cpp b/mlx/backend/cuda/scaled_dot_product_attention.cpp index 2257609fb1..5dd2f91897 100644 --- a/mlx/backend/cuda/scaled_dot_product_attention.cpp +++ b/mlx/backend/cuda/scaled_dot_product_attention.cpp @@ -4,6 +4,7 @@ #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/lru_cache.h" #include "mlx/backend/gpu/copy.h" +#include "mlx/backend/gpu/slicing.h" #include "mlx/fast_primitives.h" #include @@ -96,6 +97,9 @@ bool use_cudnn_for_decoding( auto is_slice = [](const array& kv) { // Get pre-sliced sequence length from strides, and check if the buffer // belongs to a contiguous kv cache. + if (kv.strides(2) == 0) { + return false; + } int64_t T_kv = kv.strides(1) / kv.strides(2); if (kv.size() / kv.shape(2) * T_kv != kv.buffer_size() / kv.itemsize()) { return false; @@ -121,6 +125,17 @@ array unslice_kv(const array& kv) { return copy; } +// Get the last n keys or values, i.e. kv[..., -n:, :] +array slice_last_kv(const array& kv, int n, Stream s) { + Shape start(kv.ndim(), 0); + start[2] = kv.shape(2) - n; + Shape shape = kv.shape(); + shape[2] = n; + array out(std::move(shape), kv.dtype(), nullptr, {}); + slice_gpu(kv, out, start, Shape(kv.ndim(), 1), s); + return out; +} + constexpr int QKV_NDIM = 4; struct SDPACacheKey { @@ -133,6 +148,7 @@ struct SDPACacheKey { std::array k_strides; std::array v_strides; bool do_causal; + int window_size; std::array mask_shape; std::array mask_strides; bool has_sinks; @@ -145,6 +161,7 @@ inline BytesKey build_sdpa_cache_key( const array& k, const array& v, bool do_causal, + int window_size, const std::optional& mask_arr, const std::optional& sinks, bool decoding = false, @@ -159,6 +176,7 @@ inline BytesKey build_sdpa_cache_key( cache_key.pod.k_strides = vector_key(k.strides()); cache_key.pod.v_strides = vector_key(v.strides()); cache_key.pod.do_causal = do_causal; + cache_key.pod.window_size = window_size; cache_key.pod.has_sinks = sinks.has_value(); cache_key.pod.output_logsumexp = output_logsumexp; if (mask_arr) { @@ -205,12 +223,30 @@ enum UIDS { D_O, }; +// Keep the keys less than window_size away from the query. If T_q == T_kv we +// align to the top left (the same mask) since cuDNN <= 9.9 on Hopper needs it. +template +void set_window( + Attributes& options, + const array& q, + const array& k, + bool do_causal, + int window_size) { + options + .set_diagonal_alignment( + q.shape(2) == k.shape(2) ? fe::DiagonalAlignment_t::TOP_LEFT + : fe::DiagonalAlignment_t::BOTTOM_RIGHT) + .set_diagonal_band_left_bound(window_size) + .set_diagonal_band_right_bound(do_causal ? 0 : window_size - 1); +} + DnnGraph build_sdpa_graph( cudnnHandle_t handle, const array& q, const array& k, const array& v, bool do_causal, + int window_size, const std::optional& mask_arr, const std::optional& sinks, const std::optional& seq_len_q, @@ -228,7 +264,9 @@ DnnGraph build_sdpa_graph( .set_name("sdpa_cudnn") .set_attn_scale(graph.scalar("Scale", SCALE, float32)) .set_generate_stats(output_logsumexp); - if (do_causal) { + if (window_size > 0) { + set_window(options, q, k, do_causal, window_size); + } else if (do_causal) { options.set_causal_mask_bottom_right(do_causal); } if (mask_arr) { @@ -262,6 +300,7 @@ DnnGraph build_sdpa_backward_graph( const array& k, const array& v, bool do_causal, + int window_size, const std::optional& mask_arr, const std::optional& sinks, const array& o, @@ -282,7 +321,9 @@ DnnGraph build_sdpa_backward_graph( auto options = fe::graph::SDPA_backward_attributes() .set_name("sdpa_backward_cudnn") .set_attn_scale(graph.scalar("Scale", SCALE, float32)); - if (do_causal) { + if (window_size > 0) { + set_window(options, q, k, do_causal, window_size); + } else if (do_causal) { // For pretraining, set_causal_mask (top-left mask) is ~1.8x faster than // the bottom-right mask for a ~4B model (it depends on the model size: for // bigger models the difference is smaller since the FFNs take more FLOPs) @@ -319,12 +360,18 @@ void init_cudnn_sdpa_cache() { sdpa_backward_cache(); } +void clear_cudnn_sdpa_cache() { + sdpa_cache().clear(); + sdpa_backward_cache().clear(); +} + bool supports_sdpa_cudnn( const array& q, const array& k, const array& v, bool has_arr_mask, bool do_causal, + int window_size, Stream s) { bool enabled = config::get("MLX_CUDA_USE_CUDNN_SDPA", 1); @@ -343,6 +390,22 @@ bool supports_sdpa_cudnn( return false; } + if (window_size > 0) { + // Older cuDNN does not support sinks (before 9.13) and gives wrong + // gradients when T_kv % 128 != 0 (before 9.15.1). + if (cudnnGetVersion() < 91501) { + return false; + } + // cuDNN does not support a window with an array mask, or when T_q > T_kv. + if (has_arr_mask || q.shape(2) > k.shape(2)) { + return false; + } + // The vector kernel reads only the keys in the window. + if (q.shape(2) == 1) { + return false; + } + } + // D_qk and D_v must be a multiple of 8 with maximum value 128. if ((q.shape(-1) % 8 != 0) || (q.shape(-1) > 128) || (v.shape(-1) % 8 != 0) || (v.shape(-1) > 128)) { @@ -361,6 +424,7 @@ void sdpa_cudnn( array& o, std::optional& stats, bool do_causal, + int window_size, const std::optional& mask_arr, const std::optional& sinks, bool output_logsumexp, @@ -409,7 +473,16 @@ void sdpa_cudnn( // Search cache. auto cache_key = build_sdpa_cache_key( - encoder, q, k, v, do_causal, mask_arr, sinks, decoding, output_logsumexp); + encoder, + q, + k, + v, + do_causal, + window_size, + mask_arr, + sinks, + decoding, + output_logsumexp); auto it = sdpa_cache().find(cache_key); if (it == sdpa_cache().end()) { auto graph = build_sdpa_graph( @@ -418,6 +491,7 @@ void sdpa_cudnn( k, v, do_causal, + window_size, mask_arr, sinks, seq_len_q, @@ -460,6 +534,7 @@ void sdpa_backward_cudnn( const array& o, const array& stats, bool do_causal, + int window_size, const std::optional& mask_arr, const std::optional& sinks, const array& d_o, @@ -491,8 +566,8 @@ void sdpa_backward_cudnn( } // Search cache. - auto cache_key = - build_sdpa_cache_key(encoder, q, k, v, do_causal, mask_arr, sinks); + auto cache_key = build_sdpa_cache_key( + encoder, q, k, v, do_causal, window_size, mask_arr, sinks); auto it = sdpa_backward_cache().find(cache_key); if (it == sdpa_backward_cache().end()) { auto graph = build_sdpa_backward_graph( @@ -501,6 +576,7 @@ void sdpa_backward_cudnn( k, v, do_causal, + window_size, mask_arr, sinks, o, @@ -555,6 +631,11 @@ namespace fast { namespace { +// Remove the window when it keeps all the keys. +int clip_window(const array& q, const array& k, int window_size) { + return window_size < std::max(q.shape(2), k.shape(2)) ? window_size : -1; +} + std::tuple has_fused_kernel( const array& q, const array& k, @@ -567,15 +648,13 @@ std::tuple has_fused_kernel( if (s.device != Device::gpu) { return {false, "the fused kernels require a GPU stream."}; } - if (window_size > 0) { - return {false, "window attention support for CUDA is NYI"}; - } - if (output_logsumexp && window_size > 0) { - return {false, "window support for backward attention is NYI"}; - } - - if (!supports_sdpa_cudnn(q, k, v, has_arr_mask, do_causal, s) && - !supports_sdpa_vector(q, k, v, has_arr_mask, output_logsumexp)) { + window_size = clip_window(q, k, window_size); + // The vector kernel supports a window only for one query. + bool vector_ok = + supports_sdpa_vector(q, k, v, has_arr_mask, output_logsumexp) && + (window_size <= 0 || q.shape(2) == 1); + if (!supports_sdpa_cudnn(q, k, v, has_arr_mask, do_causal, window_size, s) && + !vector_ok) { std::ostringstream msg; msg << "neither the cuDNN attention nor the vector attention kernel " << "supports this configuration; got query shape " << q.shape() @@ -627,6 +706,14 @@ void ScaledDotProductAttention::eval_gpu( auto& s = stream(); + if (outputs[0].size() == 0) { + auto& encoder = cu::get_command_encoder(s); + for (auto& out : outputs) { + out.set_data(cu::malloc_async(out.nbytes(), encoder)); + } + return; + } + array q = prepare_sdpa_input(inputs[0], s); array k = prepare_sdpa_input(inputs[1], s); array v = prepare_sdpa_input(inputs[2], s); @@ -646,8 +733,9 @@ void ScaledDotProductAttention::eval_gpu( if (output_logsumexp_) { stats = outputs[1]; } + int window_size = clip_window(q, k, window_size_); - if (supports_sdpa_cudnn(q, k, v, has_arr_mask, do_causal_, s)) { + if (supports_sdpa_cudnn(q, k, v, has_arr_mask, do_causal_, window_size, s)) { if (sinks) { sinks = prepare_sdpa_sinks(*sinks, s); } @@ -659,11 +747,17 @@ void ScaledDotProductAttention::eval_gpu( out, stats, do_causal_, + window_size, mask_arr, sinks, output_logsumexp_, s); } else { + // With one query, the window keeps the last window_size keys. + if (window_size > 0) { + k = slice_last_kv(k, window_size, s); + v = slice_last_kv(v, window_size, s); + } sdpa_vector(q, k, v, scale_, out, do_causal_, sinks, s); } } @@ -684,6 +778,16 @@ void ScaledDotProductAttentionVJP::eval_gpu( auto& s = stream(); + // Return 0s if q or k is empty + if (inputs[0].size() == 0 || inputs[1].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + cu::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + assert(inputs.size() >= 6); int primals_size = inputs.size() - 3; bool has_arr_mask = primals_size > 3 + has_sinks_; @@ -701,7 +805,7 @@ void ScaledDotProductAttentionVJP::eval_gpu( } std::optional sinks; if (has_sinks_) { - sinks = prepare_sdpa_sinks(inputs.back(), s); + sinks = prepare_sdpa_sinks(inputs[primals_size - 1], s); } assert(outputs.size() == 3); @@ -717,6 +821,7 @@ void ScaledDotProductAttentionVJP::eval_gpu( o, stats, do_causal_, + clip_window(q, k, window_size_), mask_arr, sinks, d_o, diff --git a/mlx/backend/cuda/softmax.cu b/mlx/backend/cuda/softmax.cu index d34ac11892..1f84a3feb2 100644 --- a/mlx/backend/cuda/softmax.cu +++ b/mlx/backend/cuda/softmax.cu @@ -111,6 +111,11 @@ void Softmax::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(0, encoder)); + return; + } + // Make sure that the last dimension is contiguous. auto set_output = [&s, &out, &encoder](const array& x) { if (x.flags().contiguous && x.strides()[x.ndim() - 1] == 1) { diff --git a/mlx/backend/cuda/wddm.cpp b/mlx/backend/cuda/wddm.cpp index 71027f77c4..4e83b32f01 100644 --- a/mlx/backend/cuda/wddm.cpp +++ b/mlx/backend/cuda/wddm.cpp @@ -100,8 +100,9 @@ class WddmMemoryBudget { } // namespace size_t get_wddm_memory_limit(int device, cudaMemPool_t pool) { - static WddmMemoryBudget budget(gpu::device_count()); - return budget.get_memory_limit(device, pool); + // Avoid releasing DXGI adapters under the loader lock during DLL teardown. + static auto* budget = new WddmMemoryBudget(gpu::device_count()); + return budget->get_memory_limit(device, pool); } } // namespace mlx::core::cu diff --git a/mlx/backend/gpu/primitives.cpp b/mlx/backend/gpu/primitives.cpp index 5470372ad8..eba171932f 100644 --- a/mlx/backend/gpu/primitives.cpp +++ b/mlx/backend/gpu/primitives.cpp @@ -270,15 +270,19 @@ void View::eval_gpu(const std::vector& inputs, array& out) { strides.back() = 1; } auto flags = in.flags(); + auto data_size = in.data_size() * ibytes / obytes; if (ibytes != obytes) { // Last axis size can change contiguity auto [_, row_contiguous, col_contiguous] = check_contiguity(out.shape(), strides); flags.row_contiguous = row_contiguous; flags.col_contiguous = col_contiguous; + if (row_contiguous || col_contiguous) { + flags.contiguous = true; + data_size = out.size(); + } } - out.copy_shared_buffer( - in, strides, flags, in.data_size() * ibytes / obytes); + out.copy_shared_buffer(in, strides, flags, data_size); } else { auto tmp = array(in.shape(), in.dtype(), nullptr, {}); tmp.set_data(allocator::malloc(tmp.nbytes())); diff --git a/mlx/backend/metal/allocator.cpp b/mlx/backend/metal/allocator.cpp index ff12293b79..80a3f72baa 100644 --- a/mlx/backend/metal/allocator.cpp +++ b/mlx/backend/metal/allocator.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace mlx::core { @@ -94,6 +95,7 @@ size_t MetalAllocator::set_memory_limit(size_t limit) { }; size_t MetalAllocator::get_memory_limit() { + std::unique_lock lk(mutex_); return block_limit_; } @@ -129,7 +131,12 @@ Buffer MetalAllocator::malloc(size_t size) { std::unique_lock lk(mutex_); MTL::Buffer* buf = buffer_cache_.reuse_from_cache(size); if (!buf) { - size_t mem_required = get_active_memory() + get_cache_memory() + size; + auto cache_size = buffer_cache_.cache_size(); + assert(active_memory_ <= std::numeric_limits::max() - cache_size); + assert( + size <= + std::numeric_limits::max() - active_memory_ - cache_size); + size_t mem_required = active_memory_ + cache_size + size; // If we have a lot of memory pressure try to reclaim memory from the cache if (mem_required >= gc_limit_ || num_resources_ >= resource_limit_) { @@ -163,13 +170,14 @@ Buffer MetalAllocator::malloc(size_t size) { } } + assert(buf->length() <= std::numeric_limits::max() - active_memory_); active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); // Maintain the cache below the requested limit - if (get_cache_memory() > max_pool_size_) { + if (buffer_cache_.cache_size() > max_pool_size_) { num_resources_ -= buffer_cache_.release_cached_buffers( - get_cache_memory() - max_pool_size_); + buffer_cache_.cache_size() - max_pool_size_); } Buffer buffer(static_cast(buf)); @@ -195,8 +203,9 @@ void MetalAllocator::free(Buffer buffer) { #endif std::unique_lock lk(mutex_); + assert(buf->length() <= active_memory_); active_memory_ -= buf->length(); - if (get_cache_memory() < max_pool_size_) { + if (buffer_cache_.cache_size() < max_pool_size_) { buffer_cache_.recycle_to_cache(buf); } else { num_resources_--; @@ -210,7 +219,10 @@ void MetalAllocator::free(Buffer buffer) { } size_t MetalAllocator::size(Buffer buffer) const { - return static_cast(buffer.ptr())->length(); + if (const auto* p = buffer.ptr(); p) { + return static_cast(p)->length(); + } + return 0; } Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { @@ -218,8 +230,10 @@ Buffer MetalAllocator::make_buffer(void* ptr, size_t size) { if (!buf) { return Buffer{nullptr}; } + // The caller owns this memory, so it is not wired. Wiring a file-backed + // mapping would read the whole file and keep it in memory. std::unique_lock lk(mutex_); - residency_sets_.insert(buf); + assert(buf->length() <= std::numeric_limits::max() - active_memory_); active_memory_ += buf->length(); peak_memory_ = std::max(peak_memory_, active_memory_); num_resources_++; @@ -232,9 +246,9 @@ void MetalAllocator::release(Buffer buffer) { return; } std::unique_lock lk(mutex_); + assert(buf->length() <= active_memory_); active_memory_ -= buf->length(); num_resources_--; - residency_sets_.erase(buf); lk.unlock(); auto pool = metal::new_scoped_memory_pool(); buf->release(); @@ -251,6 +265,14 @@ MetalAllocator& allocator() { } // namespace metal +namespace allocator { + +bool over_memory_limit() { + return metal::allocator().over_memory_limit(); +} + +} // namespace allocator + size_t set_cache_limit(size_t limit) { return metal::allocator().set_cache_limit(limit); } diff --git a/mlx/backend/metal/allocator.h b/mlx/backend/metal/allocator.h index 885951364e..251d67a2ed 100644 --- a/mlx/backend/metal/allocator.h +++ b/mlx/backend/metal/allocator.h @@ -24,9 +24,11 @@ class MetalAllocator : public allocator::Allocator { virtual void release(Buffer buffer) override; size_t get_active_memory() { + std::unique_lock lk(mutex_); return active_memory_; }; size_t get_peak_memory() { + std::unique_lock lk(mutex_); return peak_memory_; }; void reset_peak_memory() { @@ -34,8 +36,13 @@ class MetalAllocator : public allocator::Allocator { peak_memory_ = 0; }; size_t get_cache_memory() { + std::unique_lock lk(mutex_); return buffer_cache_.cache_size(); }; + bool over_memory_limit() { + std::unique_lock lk(mutex_); + return active_memory_ > block_limit_; + } size_t set_cache_limit(size_t limit); size_t set_memory_limit(size_t limit); size_t get_memory_limit(); diff --git a/mlx/backend/metal/compiled.cpp b/mlx/backend/metal/compiled.cpp index e95d7b8d5f..853cfbf840 100644 --- a/mlx/backend/metal/compiled.cpp +++ b/mlx/backend/metal/compiled.cpp @@ -257,6 +257,14 @@ inline void build_kernel( void Compiled::eval_gpu( const std::vector& inputs, std::vector& outputs) { + // All outputs have the same shape + if (outputs[0].size() == 0) { + for (auto& out : outputs) { + out.set_data(allocator::malloc(0)); + } + return; + } + // Get the kernel if someone else built it already auto& s = stream(); auto& d = metal::device(s.device); diff --git a/mlx/backend/metal/conv.cpp b/mlx/backend/metal/conv.cpp index 45b738d645..2bb18933b4 100644 --- a/mlx/backend/metal/conv.cpp +++ b/mlx/backend/metal/conv.cpp @@ -810,8 +810,14 @@ void pad_and_slice_conv_3D_gpu( implicit_gemm_conv_3D_gpu(s, d, in, wt, intermediate, new_params); // Slice out + auto [_, row_contiguous, col_contiguous] = + check_contiguity(out.shape(), intermediate.strides()); + bool contiguous = row_contiguous || col_contiguous; out.copy_shared_buffer( - intermediate, intermediate.strides(), {0}, intermediate.data_size()); + intermediate, + intermediate.strides(), + {contiguous, row_contiguous, col_contiguous}, + contiguous ? out.size() : intermediate.data_size()); } void conv_2D_gpu( @@ -1752,6 +1758,19 @@ void Convolution::eval_gpu(const std::vector& inputs, array& out) { const array& in = inputs[0]; const array& wt = inputs[1]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + + // Return 0s if either input is empty + if (in.size() == 0 || wt.size() == 0) { + array zero = array(0, out.dtype()); + fill_gpu(zero, out, s); + metal::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + // 3D conv if (out.ndim() == 5) { conv_3D_gpu( diff --git a/mlx/backend/metal/copy.cpp b/mlx/backend/metal/copy.cpp index cce820dfdb..ad7cc95b63 100644 --- a/mlx/backend/metal/copy.cpp +++ b/mlx/backend/metal/copy.cpp @@ -180,10 +180,10 @@ void copy_gpu_inplace( } void fill_gpu(const array& val, array& out, const Stream& s) { + out.set_data(allocator::malloc(out.nbytes())); if (out.size() == 0) { return; } - out.set_data(allocator::malloc(out.nbytes())); bool large = out.data_size() > UINT32_MAX; int work_per_thread = get_work_per_thread(out.dtype(), out.data_size()); auto& d = metal::device(s.device); diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index 6c0c92f1fb..100b74ae42 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -907,6 +907,12 @@ MTL::Library* Device::get_library( return it->second.get(); } + if (!config::get("MLX_METAL_RUNTIME_COMPILE", 1)) { + throw std::runtime_error( + "[metal::Device] Library " + name + + " is not loaded and runtime compilation is disabled."); + } + auto mtl_lib = build_library_(builder(), compile_options); library_map_.insert({name, mtl_lib}); return mtl_lib.get(); diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index ad5a1d4c49..c0ff6a3c52 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -11,6 +11,7 @@ #include "mlx/array.h" #include "mlx/backend/common/custom_kernel.h" +#include "mlx/backend/metal/metal.h" #include "mlx/backend/metal/resident.h" #include "mlx/device.h" @@ -269,8 +270,6 @@ std::unordered_map& get_command_encoders(); std::unordered_map& get_global_command_encoders(); NS::SharedPtr new_scoped_memory_pool(); -bool is_nax_available(); - // Number of GPU cores, or 0 when it is not known. int gpu_core_count(); diff --git a/mlx/backend/metal/fft.cpp b/mlx/backend/metal/fft.cpp index 952f829088..100dc4fa62 100644 --- a/mlx/backend/metal/fft.cpp +++ b/mlx/backend/metal/fft.cpp @@ -883,6 +883,11 @@ void FFT::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& in = inputs[0]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + if (axes_.size() > 1) { nd_fft_op(in, out, axes_, inverse_, real_, s); } else { diff --git a/mlx/backend/metal/gated_delta_update.cpp b/mlx/backend/metal/gated_delta_update.cpp index bb9f7b567b..28760637d4 100644 --- a/mlx/backend/metal/gated_delta_update.cpp +++ b/mlx/backend/metal/gated_delta_update.cpp @@ -98,6 +98,16 @@ void GatedDeltaUpdate::eval_gpu( auto& s = stream(); auto& d = metal::device(s.device); + auto& out = outputs[0]; + auto& hf = outputs[1]; + + // With no steps the final state is the initial state + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + copy_gpu(inputs[5], hf, CopyType::General, s); + return; + } + auto q = ensure_row_contiguous(inputs[0], d, s); auto k = ensure_row_contiguous(inputs[1], d, s); auto v = ensure_row_contiguous(inputs[2], d, s); @@ -105,9 +115,6 @@ void GatedDeltaUpdate::eval_gpu( auto beta = ensure_row_contiguous(inputs[4], d, s); auto h0 = ensure_row_contiguous(inputs[5], d, s); - auto& out = outputs[0]; - auto& hf = outputs[1]; - int B = q.shape(0); int T = q.shape(1); int Hk = q.shape(2); @@ -254,6 +261,15 @@ void GatedDeltaUpdateVJP::eval_gpu( auto& s = stream(); auto& d = metal::device(s.device); + // With no steps the initial state gradient is the final state cotangent + if (inputs[0].size() == 0) { + for (int i = 0; i < 5; i++) { + outputs[i].set_data(allocator::malloc(0)); + } + copy_gpu(inputs[7], outputs[5], CopyType::General, s); + return; + } + auto q = ensure_row_contiguous(inputs[0], d, s); auto k = ensure_row_contiguous(inputs[1], d, s); auto v = ensure_row_contiguous(inputs[2], d, s); diff --git a/mlx/backend/metal/indexing.cpp b/mlx/backend/metal/indexing.cpp index 204a43592a..14c5be6106 100644 --- a/mlx/backend/metal/indexing.cpp +++ b/mlx/backend/metal/indexing.cpp @@ -651,7 +651,7 @@ void MaskedScatter::eval_gpu(const std::vector& inputs, array& out) { ? CopyType::Scalar : (dst.flags().row_contiguous ? CopyType::Vector : CopyType::General); copy_gpu(dst, out, ct, s); - if (total == 0) { + if (total == 0 || src.size() == 0) { return; } diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index 9e85944d5c..84cdb68078 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -1391,22 +1391,38 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( bool split_d) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { + // attention_nax_dsplit has no BV template parameter. + std::string template_def; + if (split_d) { + template_def = get_template_definition( + lib_name, + "attention_nax_dsplit", + get_type_string(q.dtype()), + bq, + bk, + bd, + wm, + wn, + get_type_string(m.dtype())); + } else { + template_def = get_template_definition( + lib_name, + "attention_nax", + get_type_string(q.dtype()), + bq, + bk, + bd, + bv, + wm, + wn, + get_type_string(m.dtype())); + } std::string kernel_source; concatenate( kernel_source, metal::utils(), metal::steel_attention_nax(), - get_template_definition( - lib_name, - split_d ? "attention_nax_dsplit" : "attention_nax", - get_type_string(q.dtype()), - bq, - bk, - bd, - bv, - wm, - wn, - get_type_string(m.dtype()))); + template_def); return kernel_source; }); return d.get_kernel(kernel_name, lib, hash_name, func_consts); diff --git a/mlx/backend/metal/kernels/gemv.metal b/mlx/backend/metal/kernels/gemv.metal index 5637ecf732..c38351fe80 100644 --- a/mlx/backend/metal/kernels/gemv.metal +++ b/mlx/backend/metal/kernels/gemv.metal @@ -82,7 +82,9 @@ instantiate_gemv_bs_blocks(complex64, complex64_t); instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 4) \ instantiate_gemv_t(name, itype, 1, 4, 8, 4, 4, 4) \ instantiate_gemv_t(name, itype, 1, 16, 8, 4, 4, 4) \ - instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4) // clang-format on + instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4) \ + instantiate_gemv_t(name, itype, 1, 8, 8, 4, 4, 4) \ + instantiate_gemv_t(name, itype, 4, 2, 8, 4, 4, 4) // clang-format on // clang-format off instantiate_gemv_t_blocks(float32, float); diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index 5357bafbd4..4ff8657a32 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -1932,26 +1932,27 @@ template static_assert(BN % 8 == 0, "BN should be divisible by 8"); static_assert(TM == 1 || TM == 2, "qmv_mma takes at most 16 rows"); static_assert( - (bits == 4 || bits == 8) && + (bits >= 2 && bits <= 8 && bits != 7) && (group_size == 32 || group_size == 64 || group_size == 128), - "qmv_mma reads 4 and 8 bits at group sizes 32, 64 and 128"); + "qmv_mma reads 2 to 8 bits (not 7) at group sizes 32, 64 and 128"); using Frag = mlx::steel::BaseMMAFrag; using frag_t = typename Frag::frag_type; constexpr int BK = 128; constexpr short TN = BN / 8; - constexpr int pack_factor = 8 / bits; - constexpr short loads = bits / 4; + // The lane's 32 values take bits words + constexpr short words = bits; + constexpr uint mask = (1 << bits) - 1; const short2 coord = Frag::get_coord(simd_lid); const short fn = coord.x; const short fm = coord.y; - const int row_bytes = K / pack_factor; + const int row_bytes = K / 8 * bits; const int row_scales = K / group_size; const int y_col = tid.x * BN; auto wl = (const device uint8_t*)w + - (y_col + fm) * static_cast(row_bytes) + 16 * fn / pack_factor; + (y_col + fm) * static_cast(row_bytes) + 2 * fn * bits; const int64_t s_off = (y_col + fm) * static_cast(row_scales) + 16 * fn / group_size; scales += s_off; @@ -1986,16 +1987,34 @@ template } } } - uint4 ws[TN][loads]; + uint ws[TN][words]; float sc[TN]; float bs[TN]; STEEL_PRAGMA_UNROLL for (short t = 0; t < TN; t++) { const device uint8_t* wt = - wl + 8 * t * static_cast(row_bytes) + k / pack_factor; - STEEL_PRAGMA_UNROLL - for (short l = 0; l < loads; l++) { - ws[t][l] = *(const device uint4*)(wt + 16 * l); + wl + 8 * t * static_cast(row_bytes) + k / 8 * bits; + if constexpr (words % 4 == 0) { + STEEL_PRAGMA_UNROLL + for (short l = 0; l < words; l += 4) { + const uint4 v = *(const device uint4*)(wt + 4 * l); + ws[t][l] = v.x; + ws[t][l + 1] = v.y; + ws[t][l + 2] = v.z; + ws[t][l + 3] = v.w; + } + } else if constexpr (words % 2 == 0) { + STEEL_PRAGMA_UNROLL + for (short l = 0; l < words; l += 2) { + const uint2 v = *(const device uint2*)(wt + 4 * l); + ws[t][l] = v.x; + ws[t][l + 1] = v.y; + } + } else { + STEEL_PRAGMA_UNROLL + for (short l = 0; l < words; l++) { + ws[t][l] = ((const device uint*)wt)[l]; + } } const int64_t si = 8 * t * static_cast(row_scales) + k / group_size; @@ -2021,19 +2040,37 @@ template // each half reads as 1024 + q, and taking 1024 off again is exact. uint p[4]; if constexpr (bits == 4) { - const uint lo = ws[t][0][g / 2]; - const uint hi = ws[t][0][2 + g / 2]; + const uint lo = ws[t][g / 2]; + const uint hi = ws[t][2 + g / 2]; const uint q = (g % 2) == 0 ? (lo & 0xffff) | (hi << 16) : (lo >> 16) | (hi & 0xffff0000); STEEL_PRAGMA_UNROLL for (short i = 0; i < 4; i++) { p[i] = (q >> (4 * i)) & 0x000f000f; } + } else if constexpr (bits == 8) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + p[i] = ((ws[t][g] >> (8 * i)) & 0xff) | + (((ws[t][4 + g] >> (8 * i)) & 0xff) << 16); + } } else { + // Values 4g to 4g+3 and 16+4g to 16+4g+3, which can span two words + uint q[2]; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const short bit = (16 * h + 4 * g) * bits; + const short word = bit / 32; + const short shift = bit % 32; + q[h] = ws[t][word] >> shift; + if (shift + 4 * bits > 32) { + q[h] |= ws[t][word + 1] << (32 - shift); + } + } STEEL_PRAGMA_UNROLL for (short i = 0; i < 4; i++) { - p[i] = ((ws[t][0][g] >> (8 * i)) & 0xff) | - (((ws[t][1][g] >> (8 * i)) & 0xff) << 16); + p[i] = ((q[0] >> (bits * i)) & mask) | + (((q[1] >> (bits * i)) & mask) << 16); } } STEEL_PRAGMA_UNROLL diff --git a/mlx/backend/metal/kernels/quantized.metal b/mlx/backend/metal/kernels/quantized.metal index fa945c9b19..d33f3dd29a 100644 --- a/mlx/backend/metal/kernels/quantized.metal +++ b/mlx/backend/metal/kernels/quantized.metal @@ -237,7 +237,11 @@ instantiate_quantized_all(type, group_size, 5) \ instantiate_quantized_all(type, group_size, 6) \ instantiate_quantized_all(type, group_size, 8) \ + instantiate_qmv_mma_all(type, group_size, 2) \ + instantiate_qmv_mma_all(type, group_size, 3) \ instantiate_qmv_mma_all(type, group_size, 4) \ + instantiate_qmv_mma_all(type, group_size, 5) \ + instantiate_qmv_mma_all(type, group_size, 6) \ instantiate_qmv_mma_all(type, group_size, 8) #define instantiate_quantized_all_groups(type) \ diff --git a/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal b/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal index ddd9f4bcda..72cc508aeb 100644 --- a/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal +++ b/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal @@ -47,7 +47,7 @@ struct SDPAVJPTileParams { template [[kernel]] void sdpa_vjp_ds( - const device T* S [[buffer(0)]], // [BH, bq, bk] + const device float* S [[buffer(0)]], // [BH, bq, bk] const device T* dP [[buffer(1)]], // [BH, bq, bk] const device float* lse [[buffer(2)]], // [B, H, qL] const device float* odo [[buffer(3)]], // [B, H, qL] @@ -75,7 +75,7 @@ template if (dead || (p.causal != 0 && (p.j0 + col) > lim)) { pv = 0.0f; } else { - pv = metal::fast::exp(static_cast(S[sbase + col]) * p.scale - l); + pv = metal::fast::exp(S[sbase + col] * p.scale - l); } float dsv = pv * (static_cast(dP[sbase + col]) - dlt) * p.scale; diff --git a/mlx/backend/metal/kernels/sdpa_vector.h b/mlx/backend/metal/kernels/sdpa_vector.h index a2ed821836..921d88a7db 100644 --- a/mlx/backend/metal/kernels/sdpa_vector.h +++ b/mlx/backend/metal/kernels/sdpa_vector.h @@ -240,7 +240,8 @@ template } } -template +// Larger TK spills registers for head dim 512 (up to 3.6x slower on M5 Max). +template 512 ? 2 : 4)> [[kernel]] void sdpa_vector_2pass_1( const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], diff --git a/mlx/backend/metal/kernels/sort.metal b/mlx/backend/metal/kernels/sort.metal index d9bf20476f..a0f5c7ec25 100644 --- a/mlx/backend/metal/kernels/sort.metal +++ b/mlx/backend/metal/kernels/sort.metal @@ -41,6 +41,7 @@ instantiate_block_sort_bn(int32, int32_t) instantiate_block_sort_bn(float16, half) instantiate_block_sort_bn(float32, float) instantiate_block_sort_bn(bfloat16, bfloat16_t) +instantiate_block_sort_bn(bool_, bool) #define instantiate_block_sort_long(itname, itype) \ instantiate_block_sort_tn(itname, itype, 32) \ @@ -73,6 +74,7 @@ instantiate_multi_block_sort_base(int32, int32_t) instantiate_multi_block_sort_base(float16, half) instantiate_multi_block_sort_base(float32, float) instantiate_multi_block_sort_base(bfloat16, bfloat16_t) +instantiate_multi_block_sort_base(bool_, bool) #define instantiate_multi_block_sort_long(vtname, vtype) \ instantiate_multi_block_sort(vtname, vtype, uint32, uint32_t, true, 256, 4) diff --git a/mlx/backend/metal/kernels/steel/utils/integral_constant.h b/mlx/backend/metal/kernels/steel/utils/integral_constant.h index 2f153f482f..3b60ae301d 100644 --- a/mlx/backend/metal/kernels/steel/utils/integral_constant.h +++ b/mlx/backend/metal/kernels/steel/utils/integral_constant.h @@ -47,13 +47,11 @@ using Int = integral_constant; // Binary Operators on Integral constants /////////////////////////////////////////////////////////////////////////////// -#define integral_const_binop(__op__, __operator__) \ - template \ - METAL_FUNC constexpr auto __operator__( \ - integral_constant, integral_constant) { \ - constexpr auto res = tv __op__ uv; \ - using res_t = metal::remove_addrspace_t; \ - return integral_constant{}; \ +#define integral_const_binop(__op__, __operator__) \ + template \ + METAL_FUNC constexpr auto __operator__( \ + integral_constant, integral_constant) { \ + return integral_constant{}; \ } integral_const_binop(+, operator+); diff --git a/mlx/backend/metal/logsumexp.cpp b/mlx/backend/metal/logsumexp.cpp index ff6f07b9bf..63e5bd9506 100644 --- a/mlx/backend/metal/logsumexp.cpp +++ b/mlx/backend/metal/logsumexp.cpp @@ -17,6 +17,10 @@ void LogSumExp::eval_gpu(const std::vector& inputs, array& out) { throw std::runtime_error( "[logsumexp] Does not support non-floating point types."); } + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } auto& s = stream(); auto& d = metal::device(s.device); auto& compute_encoder = metal::get_command_encoder(s); diff --git a/mlx/backend/metal/matmul.cpp b/mlx/backend/metal/matmul.cpp index 3de3ffd7e9..1e80e4c429 100644 --- a/mlx/backend/metal/matmul.cpp +++ b/mlx/backend/metal/matmul.cpp @@ -1241,7 +1241,17 @@ void gemv_axbpy( std::ostringstream kname; if (transpose_mat) { - if (in_vector_len >= 8192 && out_vector_len >= 2048) { + // Specialized kernel for very small outputs + tn = out_vector_len < tn ? 1 : tn; + + // A long K with few outputs launches too few simdgroups to fill the GPU, + // so split K or use smaller threadgroups + bool large_mat = in_vector_len >= 8192 && out_vector_len >= 2048; + size_t n_simdgroups = + batch_size_out * ceildiv(out_vector_len, (large_mat ? 8 : 4) * tn); + bool few_simdgroups = tn == 4 && in_vector_len >= 256 && n_simdgroups < 128; + + if (large_mat && !few_simdgroups) { sm = 4; sn = 8; } else { @@ -1249,7 +1259,12 @@ void gemv_axbpy( sn = 4; } - if (out_vector_len >= 2048) { + if (few_simdgroups && out_vector_len < 1024) { + bm = 4; + bn = 2; + } else if (few_simdgroups && large_mat) { + bn = 8; + } else if (out_vector_len >= 2048) { bn = 16; } else if (out_vector_len >= 512) { bn = 4; @@ -1257,9 +1272,6 @@ void gemv_axbpy( bn = 2; } - // Specialized kernel for very small outputs - tn = out_vector_len < tn ? 1 : tn; - n_out_per_tgp = bn * sn * tn; kname << "gemv_t_" << type_to_name(out); @@ -2943,6 +2955,11 @@ void GatherMM::eval_gpu(const std::vector& inputs, array& out) { auto& lhs_indices = inputs[2]; auto& rhs_indices = inputs[3]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + // Return 0s if either input is empty if (a.size() == 0 || b.size() == 0) { array zero = array(0, a.dtype()); @@ -3167,6 +3184,19 @@ void SegmentedMM::eval_gpu(const std::vector& inputs, array& out) { auto& b = inputs[1]; auto& segments = inputs[2]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + + // Return 0s if either input is empty + if (a.size() == 0 || b.size() == 0) { + array zero = array(0, a.dtype()); + fill_gpu(zero, out, s); + metal::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + out.set_data(allocator::malloc(out.nbytes())); // Extract shapes from inputs. diff --git a/mlx/backend/metal/metal.h b/mlx/backend/metal/metal.h index d686c2971a..cd1d28d4de 100644 --- a/mlx/backend/metal/metal.h +++ b/mlx/backend/metal/metal.h @@ -13,6 +13,9 @@ namespace mlx::core::metal { /* Check if the Metal backend is available. */ MLX_API bool is_available(); +/* Check if MLX kernels can use the GPU neural accelerators (NAX). */ +MLX_API bool is_nax_available(); + /** Capture a GPU trace, saving it to an absolute file `path` */ MLX_API void start_capture(std::string path = ""); MLX_API void stop_capture(); diff --git a/mlx/backend/metal/no_metal.cpp b/mlx/backend/metal/no_metal.cpp index 3b72ad005a..f5d0eed7d1 100644 --- a/mlx/backend/metal/no_metal.cpp +++ b/mlx/backend/metal/no_metal.cpp @@ -12,6 +12,10 @@ bool is_available() { return false; } +bool is_nax_available() { + return false; +} + void start_capture(std::string) {} void stop_capture() {} diff --git a/mlx/backend/metal/normalization.cpp b/mlx/backend/metal/normalization.cpp index 1420b83270..821edf806b 100644 --- a/mlx/backend/metal/normalization.cpp +++ b/mlx/backend/metal/normalization.cpp @@ -21,6 +21,11 @@ void RMSNorm::eval_gpu( auto& d = metal::device(s.device); auto& out = outputs[0]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + // Make sure that the last dimension is contiguous auto set_output = [&s, &out](const array& x) { bool no_copy = x.flags().contiguous && x.strides()[x.ndim() - 1] == 1; @@ -96,6 +101,16 @@ void RMSNormVJP::eval_gpu( auto& d = metal::device(s.device); auto& compute_encoder = metal::get_command_encoder(s); + // Return 0s if the input is empty + if (inputs[0].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + compute_encoder.add_temporary(std::move(zero)); + return; + } + // Ensure row contiguity. We could relax this step by checking that the array // is contiguous (no broadcasts or holes) and that the input strides are the // same as the cotangent strides but for now this is simpler. @@ -224,6 +239,11 @@ void LayerNorm::eval_gpu( auto& d = metal::device(s.device); auto& out = outputs[0]; + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + // Make sure that the last dimension is contiguous auto set_output = [&s, &out](const array& x) { bool no_copy = x.flags().contiguous && x.strides()[x.ndim() - 1] == 1; @@ -310,6 +330,16 @@ void LayerNormVJP::eval_gpu( auto& d = metal::device(s.device); auto& compute_encoder = metal::get_command_encoder(s); + // Return 0s if the input is empty + if (inputs[0].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + compute_encoder.add_temporary(std::move(zero)); + return; + } + // Ensure row contiguity. We could relax this step by checking that the array // is contiguous (no broadcasts or holes) and that the input strides are the // same as the cotangent strides but for now this is simpler. diff --git a/mlx/backend/metal/primitives.cpp b/mlx/backend/metal/primitives.cpp index 45929e27dd..6e90d002d0 100644 --- a/mlx/backend/metal/primitives.cpp +++ b/mlx/backend/metal/primitives.cpp @@ -63,6 +63,9 @@ void ArgReduce::eval_gpu(const std::vector& inputs, array& out) { assert(inputs.size() == 1); auto& in = inputs[0]; out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } auto& s = stream(); auto& d = metal::device(s.device); std::string op_name; @@ -137,15 +140,15 @@ void RandomBits::eval_gpu(const std::vector& inputs, array& out) { // keys has shape (N1, ..., NK, 2) // out has shape (N1, ..., NK, M1, M2, ...) auto& keys = inputs[0]; - size_t num_keys = keys.size() / 2; - - size_t elems_per_key = out.size() / num_keys; - size_t bytes_per_key = out.itemsize() * elems_per_key; out.set_data(allocator::malloc(out.nbytes())); if (out.size() == 0) { return; } + size_t num_keys = keys.size() / 2; + size_t elems_per_key = out.size() / num_keys; + size_t bytes_per_key = out.itemsize() * elems_per_key; + size_t out_per_key = (bytes_per_key + 4 - 1) / 4; size_t half_size = out_per_key / 2; bool odd = out_per_key % 2; diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index f41c2fd129..561eafca11 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -242,7 +242,9 @@ void quantize_impl( Stream s) { auto& w_pre = inputs[0]; auto& out = outputs[0]; - out.set_data(allocator::malloc(out.nbytes())); + if (w_pre.size() == 0) { + return; + } auto& d = metal::device(s.device); auto& compute_encoder = metal::get_command_encoder(s); @@ -264,10 +266,8 @@ void quantize_impl( compute_encoder.set_output_array(out, 3); } else { auto& scales = outputs[1]; - scales.set_data(allocator::malloc(scales.nbytes())); if (has_biases) { auto& biases = outputs[2]; - biases.set_data(allocator::malloc(biases.nbytes())); compute_encoder.set_output_array(biases, 3); } else if (has_global_scale) { compute_encoder.set_input_array(inputs[1], 3); @@ -328,8 +328,10 @@ auto quantize_input( array(wq_shape, uint32, nullptr, {}), array(scales_shape, uint8, nullptr, {})}; auto& compute_encoder = metal::get_command_encoder(s); - compute_encoder.add_temporary(outputs[0]); - compute_encoder.add_temporary(outputs[1]); + for (auto& out : outputs) { + out.set_data(allocator::malloc(out.nbytes())); + compute_encoder.add_temporary(out); + } quantize_impl(inputs, outputs, mode, group_size, bits, false, s); return std::make_tuple(outputs[0], outputs[1]); } @@ -643,11 +645,15 @@ inline bool use_qmv_mma( metal::Device& d) { bool nax = metal::is_nax_available(); bool affine = mode == QuantizationMode::Affine; - // affine_qmv_mma beats qmv from 3 rows below gen 15 and qmv_wide from 4 - // rows above; the other paths from 6. + // affine_qmv_mma beats qmv from 3 rows on gen 13 and 14 GPUs (4 on their + // Ultras) and qmv_wide from 4 rows on gen 15 and above. 4-bit + // affine_qmv_nax from 4 rows; the other paths from 6. + bool ultra = d.get_architecture().back() == 'd'; int min_rows = 6; if (affine && !nax) { - min_rows = d.get_architecture_gen() >= 15 ? 4 : 3; + min_rows = (ultra || d.get_architecture_gen() >= 15) ? 4 : 3; + } else if (affine && bits == 4) { + min_rows = 4; } if ((M < min_rows) || (K % 128 != 0)) { return false; @@ -665,14 +671,19 @@ inline bool use_qmv_mma( (x.dtype() == float16 || x.dtype() == bfloat16) && (N >= 512) && (K >= 1024) && (N % 32 == 0); } else { // non-nax - // Ultra keeps the vector kernels. - if (d.get_architecture().back() == 'd') { + // qmv_mma reads 2 to 8 bits (not 7). + if (bits < 2 || bits == 7) { return false; } - // Only 4 and 8 bits are instantiated; affine pays off from a smaller N * - // K than fp. - return (bits == 4 || bits == 8) && (N >= 512) && (K >= 512) && - (int64_t(N) * K >= (int64_t(1) << 21)) && (N % 16 == 0); + // On M3 Ultra and newer, as for fp, only for large layers. + if (ultra && d.get_architecture_gen() >= 15) { + return (N >= 4096) && (K >= 4096) && (N % 16 == 0); + } + // Affine pays off from a smaller N * K than fp, and from 2^20 on gen 15+ + // (M4). + int nk_log2 = d.get_architecture_gen() >= 15 ? 20 : 21; + return (N >= 512) && (K >= 512) && + (int64_t(N) * K >= (int64_t(1) << nk_log2)) && (N % 16 == 0); } } else { // fp quantization if (nax) { @@ -2274,7 +2285,18 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& d = metal::device(s.device); + // Return 0s if x is empty + if (inputs[0].size() == 0) { + array zero = array(0, out.dtype()); + fill_gpu(zero, out, s); + metal::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } // Make sure the last two dims of x and w, s, b are contiguous. This should // be relaxed for x. @@ -2362,7 +2384,18 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& d = metal::device(s.device); + // Return 0s if x is empty + if (inputs[0].size() == 0) { + array zero = array(0, out.dtype()); + fill_gpu(zero, out, s); + metal::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } array x = ensure_row_contiguous_matrix(inputs[0], d, s); array w = ensure_row_contiguous_matrix(inputs[1], d, s); @@ -2483,6 +2516,9 @@ void QQMatmul::eval_gpu(const std::vector& inputs, array& out) { auto mode = quantization_mode_to_string(mode_); out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } // - 2 inputs: x, w (non-quantized w) // - 3 inputs: x, w, scales_w (quantized w) @@ -2583,6 +2619,9 @@ void GatherQQMM::eval_gpu(const std::vector& inputs, array& out) { auto mode = quantization_mode_to_string(mode_); out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } // - 4 inputs: x, w (non-quantized w) // - 5 inputs: x, w, scales_w (quantized w) @@ -2698,6 +2737,9 @@ void GatherQQMM::eval_gpu(const std::vector& inputs, array& out) { void fast::Quantize::eval_gpu( const std::vector& inputs, std::vector& outputs) { + for (auto& out : outputs) { + out.set_data(allocator::malloc(out.nbytes())); + } quantize_impl( inputs, outputs, mode_, group_size_, bits_, dequantize_, stream()); } diff --git a/mlx/backend/metal/reduce.cpp b/mlx/backend/metal/reduce.cpp index aa1b07fcd4..8a2ea95b32 100644 --- a/mlx/backend/metal/reduce.cpp +++ b/mlx/backend/metal/reduce.cpp @@ -568,8 +568,8 @@ void row_reduce_general_dispatch( // Prepare the arguments for the kernel RowReduceArgs args(in, plan, axes); - // Case 1: The row is small - if (args.row_size <= 64) { + // Case 1: The row is small and the kernel's 32-bit counter cannot wrap + if (args.row_size <= 64 && args.non_row_reductions <= UINT32_MAX - 31) { return row_reduce_small(in, out, op_name, args, compute_encoder, d, s); } diff --git a/mlx/backend/metal/rope.cpp b/mlx/backend/metal/rope.cpp index 1147361baf..7fe625a07f 100644 --- a/mlx/backend/metal/rope.cpp +++ b/mlx/backend/metal/rope.cpp @@ -18,6 +18,11 @@ void RoPE::eval_gpu( auto& in = inputs[0]; auto& out = outputs[0]; + if (in.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + auto& s = out.primitive().stream(); auto& d = metal::device(s.device); diff --git a/mlx/backend/metal/scaled_dot_product_attention.cpp b/mlx/backend/metal/scaled_dot_product_attention.cpp index 78aaa0aa55..15a2ca96e8 100644 --- a/mlx/backend/metal/scaled_dot_product_attention.cpp +++ b/mlx/backend/metal/scaled_dot_product_attention.cpp @@ -1,5 +1,6 @@ // Copyright © 2024-26 Apple Inc. #include +#include #include #include "mlx/backend/common/compiled.h" @@ -1507,11 +1508,20 @@ void sdpa_vjp_blocked( auto red_add = d.get_kernel("sdpa_vjp_reduce_add_" + tname); auto red_set = d.get_kernel("sdpa_vjp_reduce_set_" + tname); - // Temporary tiles - array s_buf = vjp_alloc({BH, BQ, BK}, ctype, s); + // Temporary tiles. The scores S stay in float32 to keep precision. + array s_buf = vjp_alloc({BH, BQ, BK}, float32, s); array dp_buf = vjp_alloc({BH, BQ, BK}, ctype, s); array p_buf = vjp_alloc({BH, BQ, BK}, ctype, s); + // For half precision inputs Q and K operands stay in float32 too. + const bool upcast = (ctype != float32); + std::optional q32_buf; + std::optional k32_buf; + if (upcast) { + q32_buf = vjp_alloc({B, H, BQ, D}, float32, s); + k32_buf = vjp_alloc({B, Hk, BK, D}, float32, s); + } + // Output of the gemms array dq_tile = vjp_alloc({BH, BQ, D}, ctype, s); array dk_tile = vjp_alloc({BH, BK, D}, ctype, s); @@ -1565,6 +1575,15 @@ void sdpa_vjp_blocked( array k_sl = vjp_row_slice(k, j0, bk_len); array v_sl = vjp_row_slice(v, j0, bk_len); + // The K operand of S = Q @ K.T + array k_op = k_sl; + Strides k_op_bs = k_bs; + if (upcast) { + k_op = vjp_view(*k32_buf, {B, Hk, bk_len, D}); + copy_gpu_inplace(k_sl, k_op, CopyType::General, s); + k_op_bs = {Hk * int64_t(bk_len) * D, int64_t(bk_len) * D, 0}; + } + bool kv_accum = false; for (int ii = 0; ii < n_i; ++ii) { @@ -1578,13 +1597,25 @@ void sdpa_vjp_blocked( array q_sl = vjp_row_slice(q, i0, bq_len); array o_sl = vjp_row_slice(cot_o, i0, bq_len); + // The Q operand of S = Q @ K.T + array q_op = q_sl; + Strides q_op_bs = q_bs; + if (upcast) { + q_op = vjp_view(*q32_buf, {B, H, bq_len, D}); + copy_gpu_inplace(q_sl, q_op, CopyType::General, s); + q_op_bs = { + H * int64_t(bq_len) * D, + G * int64_t(bq_len) * D, + int64_t(bq_len) * D}; + } + array s_v = vjp_view(s_buf, {BH, bq_len, bk_len}); // S = Q @ K.T steel_matmul( s, d, - q_sl, - k_sl, + q_op, + k_op, s_v, bq_len, bk_len, @@ -1596,8 +1627,8 @@ void sdpa_vjp_blocked( true, copies, bshape, - q_bs, - k_bs); + q_op_bs, + k_op_bs); array dp_v = vjp_view(dp_buf, {BH, bq_len, bk_len}); // dP = dO @ V.T @@ -1620,7 +1651,8 @@ void sdpa_vjp_blocked( o_bs, v_bs); - array ds_v = vjp_view(s_buf, {BH, bq_len, bk_len}); + // dS overwrites dP; each element is read once and written once + array ds_v = vjp_view(dp_buf, {BH, bq_len, bk_len}); array p_v = vjp_view(p_buf, {BH, bq_len, bk_len}); SDPAVJPTileParams params{ @@ -1632,7 +1664,7 @@ void sdpa_vjp_blocked( compute_encoder.set_input_array(dp_v, 1); compute_encoder.set_input_array(lse, 2); compute_encoder.set_input_array(odo, 3); - compute_encoder.set_output_array(s_v, 4); + compute_encoder.set_output_array(ds_v, 4); compute_encoder.set_output_array(p_v, 5); compute_encoder.set_bytes(params, 6); compute_encoder.dispatch_threads( @@ -1775,32 +1807,35 @@ bool ScaledDotProductAttention::use_fallback( return false; } + const bool nax = metal::is_nax_available(); const int query_sequence_length = q.shape(2); const int query_head_dim = q.shape(-1); const int value_head_dim = v.shape(-1); - if (query_head_dim == 512 && query_sequence_length > 8) { - constexpr int64_t min_query_blocks = 1024; - const int64_t query_blocks = int64_t(q.shape(0)) * q.shape(1) * - int64_t(ceildiv(query_sequence_length, 32)); - // The D512 kernel needs this many query blocks to match fallback speed. - const bool eligible = metal::is_nax_available() && - (env::enable_tf32() || q.dtype() != float32) && - query_sequence_length >= 1024 && do_causal && !has_arr_mask && - query_blocks >= min_query_blocks; - return !eligible; - } - // Use headdim-split kernel when NAX is enabled and there are enough query // blocks to fill the machine. - if (metal::is_nax_available() && - (env::enable_tf32() || q.dtype() != float32) && - query_sequence_length >= 1024 && query_head_dim == 256 && + if (nax && (env::enable_tf32() || q.dtype() != float32) && + (query_head_dim == 256 || query_head_dim == 512) && (do_causal || has_arr_mask)) { - return false; + if (query_head_dim == 256 && query_sequence_length >= 1024) { + return false; + } + + if (query_head_dim == 256 && + (q.dtype() == float16 || q.dtype() == bfloat16) && + query_sequence_length >= 512 && int64_t(q.shape(0)) * q.shape(1) >= 8) { + return false; + } + + int64_t query_blocks = + int64_t(q.shape(0)) * q.shape(1) * ceildiv(query_sequence_length, 32); + if (query_head_dim == 512 && query_sequence_length >= 1024 && + query_blocks >= 1024) { + return false; + } } - if (!metal::is_nax_available() && q.dtype() != float32 && do_causal && + if (!nax && (q.dtype() == float16 || q.dtype() == bfloat16) && do_causal && query_head_dim == 256 && query_sequence_length >= 2048 && query_sequence_length == k.shape(2)) { return false; @@ -1809,7 +1844,8 @@ bool ScaledDotProductAttention::use_fallback( // Unfused path is faster for following shapes. // Full attention: if (query_sequence_length > 8) { - return query_head_dim == 192 || query_head_dim == 256; + return query_head_dim == 192 || query_head_dim == 256 || + query_head_dim == 512; } // Split attention: const int rows = query_sequence_length * (q.shape(1) / k.shape(1)); @@ -1835,6 +1871,13 @@ void ScaledDotProductAttention::eval_gpu( auto& v_pre = inputs[2]; auto& o = outputs[0]; + if (o.size() == 0) { + for (auto& out : outputs) { + out.set_data(allocator::malloc(out.nbytes())); + } + return; + } + std::vector copies; // Define some copy functions to ensure the layout of the inputs is as // expected. @@ -2130,6 +2173,16 @@ void ScaledDotProductAttentionVJP::eval_gpu( "[ScaledDotProductAttentionVJP] NYI: attention sinks"); } + // Return 0s if q or k is empty + if (inputs[0].size() == 0 || inputs[1].size() == 0) { + array zero(0, outputs[0].dtype()); + for (auto& out : outputs) { + fill_gpu(zero, out, s); + } + metal::get_command_encoder(s).add_temporary(std::move(zero)); + return; + } + auto q = ensure_row_contiguous(inputs[0], d, s); auto k = ensure_row_contiguous(inputs[1], d, s); auto v = ensure_row_contiguous(inputs[2], d, s); diff --git a/mlx/backend/metal/softmax.cpp b/mlx/backend/metal/softmax.cpp index 1abdaec420..a924ec5e34 100644 --- a/mlx/backend/metal/softmax.cpp +++ b/mlx/backend/metal/softmax.cpp @@ -18,6 +18,10 @@ void Softmax::eval_gpu(const std::vector& inputs, array& out) { throw std::runtime_error( "[softmax] Does not support non-floating point types."); } + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } auto& s = stream(); auto& d = metal::device(s.device); diff --git a/mlx/backend/no_gpu/allocator.cpp b/mlx/backend/no_gpu/allocator.cpp index a800e381a7..b89e2bf635 100644 --- a/mlx/backend/no_gpu/allocator.cpp +++ b/mlx/backend/no_gpu/allocator.cpp @@ -42,9 +42,11 @@ class CommonAllocator : public Allocator { virtual size_t size(Buffer buffer) const override; size_t get_active_memory() const { + std::unique_lock lk(mutex_); return active_memory_; }; size_t get_peak_memory() const { + std::unique_lock lk(mutex_); return peak_memory_; }; void reset_peak_memory() { @@ -52,8 +54,13 @@ class CommonAllocator : public Allocator { peak_memory_ = 0; }; size_t get_memory_limit() { + std::unique_lock lk(mutex_); return memory_limit_; } + bool over_memory_limit() const { + std::unique_lock lk(mutex_); + return active_memory_ > memory_limit_; + } size_t set_memory_limit(size_t limit) { std::unique_lock lk(mutex_); std::swap(memory_limit_, limit); @@ -171,6 +178,10 @@ Allocator& allocator() { return common_allocator(); } +bool over_memory_limit() { + return common_allocator().over_memory_limit(); +} + void* Buffer::raw_ptr() { if (!ptr_) { return nullptr; diff --git a/mlx/compile.cpp b/mlx/compile.cpp index e6bb2953b5..462a772797 100644 --- a/mlx/compile.cpp +++ b/mlx/compile.cpp @@ -694,6 +694,12 @@ void compile_simplify( tape_order.insert({tape[i].id(), i}); } + // Outputs were rewritten above, so output_map keys are no longer their ids. + std::unordered_set output_set; + for (auto& o : outputs) { + output_set.insert(o.id()); + } + // Multi-pass merge only keeping non-orphaned arrays in the tape for (int pass = 0; pass < passes; ++pass) { for (auto& arr : tape) { @@ -713,7 +719,7 @@ void compile_simplify( auto& src = parents->second[src_idx].first; auto& dst = parents->second[dst_idx].first; if (src.id() != dst.id() && array_equivalent(src, dst) && - output_map.find(src.id()) == output_map.end()) { + output_set.find(src.id()) == output_set.end()) { merge(dst, src, parents_map); mask[src_idx] = true; } @@ -779,7 +785,7 @@ void compile_simplify( } return false; } else { - return output_map.find(a.id()) == output_map.end(); + return output_set.find(a.id()) == output_set.end(); } }; bool discard = maybe_merge_parents(arr); diff --git a/mlx/distributed/ring/ring.cpp b/mlx/distributed/ring/ring.cpp index d2c55c5576..f82ac785a4 100644 --- a/mlx/distributed/ring/ring.cpp +++ b/mlx/distributed/ring/ring.cpp @@ -1,6 +1,7 @@ // Copyright © 2024 Apple Inc. #include +#include #include #include #include diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 3b886b7cf6..edf1533239 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -1094,14 +1094,18 @@ static array scaled_dot_product_attention_impl( stream)) { if (has_bool_mask && !skip_left_padding && !ScaledDotProductAttention::supports_bool_mask()) { - // Convert bool mask to additive mask. + // Convert bool mask to additive mask before the broadcast, so it is not + // copied for each head. The fused kernel needs a contiguous last axis. float inf = std::numeric_limits::infinity(); - array& mask = inputs[3]; - mask = where( - mask, - full_like(mask, 0, final_type, stream), - full_like(mask, -inf, final_type, stream), + auto shape = mask_arr->ndim() > 0 ? mask_arr->shape() : Shape{1}; + shape.back() = keys.shape(-2); + auto mask = where( + broadcast_to(*mask_arr, shape, stream), + array(0.0f, final_type), + array(-inf, final_type), stream); + mask = contiguous(mask, false, stream); + inputs[3] = broadcast_to(mask, inputs[3].shape(), stream); } Shape out_shape{q.shape(0), q.shape(1), q.shape(2), v.shape(-1)}; auto primitive = std::make_shared( @@ -1223,14 +1227,18 @@ std::vector ScaledDotProductAttention::vjp( return Custom::vjp(primals, cotangents, argnums, outputs); } - if (outputs.size() != 2) { + // The fused backward computes only the gradients of q, k and v. + bool other_grads = std::any_of( + argnums.begin(), argnums.end(), [](int arg) { return arg >= 3; }); + if (outputs.size() != 2 || other_grads) { return Custom::vjp(primals, cotangents, argnums, outputs); } + // The inputs are the primals, the output, the logsumexp and the cotangent. auto fallback = [sdpa = fallback_, s](const std::vector& inputs) { - std::vector primals(inputs.begin(), std::prev(inputs.end())); + std::vector primals(inputs.begin(), inputs.end() - 3); auto [_, vjps] = mlx::core::vjp(sdpa, primals, {inputs.back()}); - return vjps; + return std::vector(vjps.begin(), vjps.begin() + 3); }; std::vector shapes; @@ -1240,7 +1248,7 @@ std::vector ScaledDotProductAttention::vjp( dtypes.push_back(primals[i].dtype()); } auto primitive = std::make_shared( - s, fallback, scale_, do_causal_, has_sinks_); + s, fallback, scale_, do_causal_, has_sinks_, window_size_); std::vector inputs = primals; inputs.push_back(outputs[0]); inputs.push_back(outputs[1]); @@ -1249,11 +1257,6 @@ std::vector ScaledDotProductAttention::vjp( std::vector returned_vjps; for (int arg : argnums) { - if (arg >= 3) { - throw std::invalid_argument( - "[scale_dot_product_attention] Does not support VJP with respect " - " to mask or attention sinks."); - } returned_vjps.push_back(std::move(vjps[arg])); } return returned_vjps; @@ -1275,7 +1278,7 @@ bool ScaledDotProductAttentionVJP::is_equivalent(const Primitive& other) const { const ScaledDotProductAttentionVJP& a_other = static_cast(other); return scale_ == a_other.scale_ && do_causal_ == a_other.do_causal_ && - has_sinks_ == a_other.has_sinks_; + has_sinks_ == a_other.has_sinks_ && window_size_ == a_other.window_size_; } std::vector gated_delta_update( diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 91a33c296a..cc59fd9df0 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -351,11 +351,13 @@ class ScaledDotProductAttentionVJP : public Custom { std::function(std::vector)> fallback, float scale, bool do_causal, - bool has_sinks) + bool has_sinks, + int window_size) : Custom(stream, std::move(fallback)), scale_(scale), do_causal_(do_causal), - has_sinks_(has_sinks) {} + has_sinks_(has_sinks), + window_size_(window_size) {} static bool use_fallback(const array& q, Stream s); @@ -370,13 +372,15 @@ class ScaledDotProductAttentionVJP : public Custom { DEFINE_NAME(ScaledDotProductAttentionVJP); bool is_equivalent(const Primitive& other) const override; auto state() const { - return std::make_tuple(nullptr, scale_, do_causal_, has_sinks_); + return std::make_tuple( + nullptr, scale_, do_causal_, has_sinks_, window_size_); } private: float scale_; bool do_causal_; bool has_sinks_; + int window_size_; }; class ConvertFP8 : public Primitive { diff --git a/mlx/io/gguf.cpp b/mlx/io/gguf.cpp index dd27385dfd..4b73ba69f9 100644 --- a/mlx/io/gguf.cpp +++ b/mlx/io/gguf.cpp @@ -1,11 +1,15 @@ // Copyright © 2023-2024 Apple Inc. +#include #include #include #include #include #include +#include +#include +#include "mlx/allocator.h" #include "mlx/io/gguf.h" #include "mlx/io/load.h" #include "mlx/ops.h" @@ -15,6 +19,49 @@ namespace mlx::core { // https://github.com/antirez/gguf-tools/blob/af7d88d808a7608a33723fba067036202910acb3/gguflib.h#L102-L108 constexpr int gguf_array_header_size = 12; +namespace { + +template + requires std::is_trivially_copyable_v +T load_unaligned(const void* src) { + T value; + std::memcpy(&value, src, sizeof(T)); + return value; +} + +template + requires std::is_trivially_copyable_v +void store_unaligned(void* dst, const T& value) { + std::memcpy(dst, &value, sizeof(T)); +} + +template + requires std::is_trivially_copyable_v && + std::is_trivially_copyable_v +array load_unaligned_array(const char* data, int size, Dtype dtype) { + auto storage = allocator::malloc(sizeof(To) * size); + auto* out = static_cast(storage.buffer().raw_ptr()); + if constexpr (std::is_same_v) { + if (size > 0) { + std::memcpy(out, data, sizeof(To) * size); + } + } else { + std::generate_n(out, size, [src = data]() mutable { + auto value = load_unaligned(src); + src += sizeof(From); + return static_cast(value); + }); + } + return array(std::move(storage), {size}, dtype); +} + +void store_array_header(char* dst, uint32_t type, uint64_t len) { + store_unaligned(dst, type); + store_unaligned(dst + sizeof(type), len); +} + +} // namespace + std::optional dtype_to_gguf_tensor_type(const Dtype& dtype) { switch (dtype) { case float32: @@ -117,95 +164,98 @@ void set_mx_value_from_gguf( uint32_t type, gguf_value* val, GGUFMetaData& value) { + const auto* p = reinterpret_cast(val); switch (type) { case GGUF_VALUE_TYPE_UINT8: - value = array(val->uint8, uint8); + value = array(load_unaligned(p), uint8); break; case GGUF_VALUE_TYPE_INT8: - value = array(val->int8, int8); + value = array(load_unaligned(p), int8); break; case GGUF_VALUE_TYPE_UINT16: - value = array(val->uint16, uint16); + value = array(load_unaligned(p), uint16); break; case GGUF_VALUE_TYPE_INT16: - value = array(val->int16, int16); + value = array(load_unaligned(p), int16); break; case GGUF_VALUE_TYPE_UINT32: - value = array(val->uint32, uint32); + value = array(load_unaligned(p), uint32); break; case GGUF_VALUE_TYPE_INT32: - value = array(val->int32, int32); + value = array(load_unaligned(p), int32); break; case GGUF_VALUE_TYPE_UINT64: - value = array(val->uint64, uint64); + value = array(load_unaligned(p), uint64); break; case GGUF_VALUE_TYPE_INT64: - value = array(val->int64, int64); + value = array(load_unaligned(p), int64); break; case GGUF_VALUE_TYPE_FLOAT32: - value = array(val->float32, float32); + value = array(load_unaligned(p), float32); break; case GGUF_VALUE_TYPE_BOOL: - value = array(val->boolval, bool_); + value = array(load_unaligned(p) != 0, bool_); break; case GGUF_VALUE_TYPE_STRING: - value = std::string(val->string.string, val->string.len); + value = std::string(p + sizeof(uint64_t), load_unaligned(p)); break; case GGUF_VALUE_TYPE_FLOAT64: - value = array(val->float64, float32); + value = array(load_unaligned(p), float32); break; case GGUF_VALUE_TYPE_ARRAY: { ctx->off += gguf_array_header_size; // Skip header - char* data = reinterpret_cast(val) + gguf_array_header_size; - auto size = static_cast(val->array.len); - if (val->array.type == GGUF_VALUE_TYPE_ARRAY) { + const auto* data = p + gguf_array_header_size; + auto array_type = load_unaligned(p); + auto size = + static_cast(load_unaligned(p + sizeof(uint32_t))); + if (array_type == GGUF_VALUE_TYPE_ARRAY) { throw std::invalid_argument( "[load_gguf] Only supports loading 1-layer of nested arrays."); } - switch (val->array.type) { + switch (array_type) { case GGUF_VALUE_TYPE_UINT8: - value = array(reinterpret_cast(data), {size}, uint8); + value = load_unaligned_array(data, size, uint8); break; case GGUF_VALUE_TYPE_INT8: - value = array(reinterpret_cast(data), {size}, int8); + value = load_unaligned_array(data, size, int8); break; case GGUF_VALUE_TYPE_UINT16: - value = array(reinterpret_cast(data), {size}, uint16); + value = load_unaligned_array(data, size, uint16); break; case GGUF_VALUE_TYPE_INT16: - value = array(reinterpret_cast(data), {size}, int16); + value = load_unaligned_array(data, size, int16); break; case GGUF_VALUE_TYPE_UINT32: - value = array(reinterpret_cast(data), {size}, uint32); + value = load_unaligned_array(data, size, uint32); break; case GGUF_VALUE_TYPE_INT32: - value = array(reinterpret_cast(data), {size}, int32); + value = load_unaligned_array(data, size, int32); break; case GGUF_VALUE_TYPE_UINT64: - value = array(reinterpret_cast(data), {size}, uint64); + value = load_unaligned_array(data, size, uint64); break; case GGUF_VALUE_TYPE_INT64: - value = array(reinterpret_cast(data), {size}, int64); + value = load_unaligned_array(data, size, int64); break; case GGUF_VALUE_TYPE_FLOAT32: - value = array(reinterpret_cast(data), {size}, float32); + value = load_unaligned_array(data, size, float32); break; case GGUF_VALUE_TYPE_BOOL: - value = array(reinterpret_cast(data), {size}, bool_); + value = load_unaligned_array(data, size, bool_); break; case GGUF_VALUE_TYPE_STRING: { std::vector strs(size); for (auto& str : strs) { - auto str_val = reinterpret_cast(data); - data += (str_val->len + sizeof(gguf_string)); - str = std::string(str_val->string, str_val->len); - ctx->off += (str_val->len + sizeof(gguf_string)); + auto len = load_unaligned(data); + str = std::string(data + sizeof(uint64_t), len); + data += sizeof(uint64_t) + len; + ctx->off += sizeof(uint64_t) + len; } value = std::move(strs); break; } case GGUF_VALUE_TYPE_FLOAT64: - value = array(reinterpret_cast(data), {size}, float32); + value = load_unaligned_array(data, size, float32); break; default: throw std::runtime_error( @@ -273,7 +323,7 @@ void check_metadata_value_in_file( } auto check_string = [&](const uint8_t* p) -> const uint8_t* { - uint64_t len = reinterpret_cast(p)->len; + auto len = load_unaligned(p); if (sizeof(uint64_t) + len > avail(p)) { fail("String metadata value extends past the end of the file."); } @@ -293,16 +343,18 @@ void check_metadata_value_in_file( fail("Metadata value extends past the end of the file."); } const uint8_t* elt = base + gguf_array_header_size; - size_t elt_size = gguf_value_type_size(val->array.type); + auto array_type = load_unaligned(base); + auto array_len = load_unaligned(base + sizeof(uint32_t)); + size_t elt_size = gguf_value_type_size(array_type); if (elt_size) { - if (val->array.len > avail(elt) / elt_size) { + if (array_len > avail(elt) / elt_size) { fail("Array metadata value extends past the end of the file."); } return; } - if (val->array.type == GGUF_VALUE_TYPE_STRING) { + if (array_type == GGUF_VALUE_TYPE_STRING) { const uint8_t* p = elt; - for (uint64_t i = 0; i < val->array.len; i++) { + for (uint64_t i = 0; i < array_len; i++) { if (sizeof(uint64_t) > avail(p)) { fail("Array metadata value extends past the end of the file."); } @@ -395,9 +447,7 @@ void append_kv_array( if (val.ndim() == 1) { size_t gguf_size = val.nbytes() + gguf_array_header_size; std::vector val_vec(gguf_size); - gguf_value* gguf_val = reinterpret_cast(val_vec.data()); - gguf_val->array.type = gguf_type; - gguf_val->array.len = val.size(); + store_array_header(val_vec.data(), gguf_type, val.size()); memcpy( val_vec.data() + gguf_array_header_size, val.data(), @@ -433,9 +483,8 @@ void write_gguf( } auto string_to_gguf = [](char* dst, const std::string& src) { - gguf_string* val = reinterpret_cast(dst); - val->len = src.length(); - memcpy(val->string, src.c_str(), src.length()); + store_unaligned(dst, static_cast(src.length())); + memcpy(dst + sizeof(uint64_t), src.data(), src.length()); }; // Save any meta data @@ -460,9 +509,8 @@ void write_gguf( }); mem_size += str_vec.size() * sizeof(gguf_string) + gguf_array_header_size; std::vector val_vec(mem_size); - gguf_value* val = reinterpret_cast(val_vec.data()); - val->array.type = GGUF_VALUE_TYPE_STRING; - val->array.len = str_vec.size(); + store_array_header( + val_vec.data(), GGUF_VALUE_TYPE_STRING, str_vec.size()); auto str_ptr = val_vec.data() + gguf_array_header_size; for (auto& str : str_vec) { string_to_gguf(str_ptr, str); @@ -473,7 +521,7 @@ void write_gguf( key.c_str(), key.length(), GGUF_VALUE_TYPE_ARRAY, - static_cast(val), + val_vec.data(), mem_size); } else if (auto pv = std::get_if(&value); pv) { array v = *pv; diff --git a/mlx/linalg.cpp b/mlx/linalg.cpp index 2aa0230dcf..aea5f95a23 100644 --- a/mlx/linalg.cpp +++ b/mlx/linalg.cpp @@ -59,7 +59,7 @@ inline array l2_norm( bool keepdims, StreamOrDevice s) { if (issubdtype(a.dtype(), complexfloating)) { - return sqrt(sum(abs(a, s) * abs(a, s), axis, keepdims, s), s); + return sqrt(sum(multiply(abs(a, s), abs(a, s), s), axis, keepdims, s), s); } else { return sqrt(sum(square(a, s), axis, keepdims, s), s); } diff --git a/mlx/ops.cpp b/mlx/ops.cpp index 97ff8ae881..e0bc716704 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -2683,7 +2683,7 @@ std::tuple minmax( array argmin(const array& a, bool keepdims, StreamOrDevice s /* = {} */) { auto result = argmin(flatten(a, s), 0, true, s); - if (keepdims) { + if (keepdims && a.ndim() > 0) { std::vector axes(a.ndim() - 1); std::iota(axes.begin(), axes.end(), 0); result = expand_dims(result, axes, s); @@ -2720,7 +2720,7 @@ array argmin( array argmax(const array& a, bool keepdims, StreamOrDevice s /* = {} */) { auto result = argmax(flatten(a, s), 0, true, s); - if (keepdims) { + if (keepdims && a.ndim() > 0) { std::vector axes(a.ndim() - 1); std::iota(axes.begin(), axes.end(), 0); result = expand_dims(result, axes, s); @@ -5006,6 +5006,16 @@ array quantized_matmul( std::move(inputs)); } +void validate_qqmm_mode(std::string_view tag, QuantizationMode qmode) { + // Affine mode needs biases, and qqmm does not take them. + if (qmode == QuantizationMode::Affine) { + std::ostringstream msg; + msg << "[" << tag << "] Only 'nvfp4', 'mxfp4' and 'mxfp8' quantization " + << "modes are supported but received 'affine'."; + throw std::invalid_argument(msg.str()); + } +} + void validate_qqmm_inputs( const array& x, const array& w, @@ -5108,6 +5118,7 @@ array qqmm( StreamOrDevice s /* = {} */) { auto stream = to_stream(s); auto qmode = string_to_quantization_mode(mode, "qqmm"); + validate_qqmm_mode("qqmm", qmode); // we need to check 2 cases: // 1. w is quantized, scales is provided // 2. w is not quantized, scales is not provided @@ -5315,8 +5326,10 @@ std::vector fp_quantize( auto new_shape = w.shape(); new_shape.back() = -1; auto wq = reshape(w, {-1, group_size}, s); - auto scales = - divide(max(abs(wq, s), -1, true, s), array(maxval, w.dtype()), s); + // Skip NaN in the group max, as the GPU kernels do + auto w_abs = abs(wq, s); + w_abs = where(isnan(w_abs, s), array(0, w.dtype()), w_abs, s); + auto scales = divide(max(w_abs, -1, true, s), array(maxval, w.dtype()), s); if (group_size == 16) { // convert to e4m3 auto scale_encode = inputs.size() > 1 @@ -5324,8 +5337,11 @@ std::vector fp_quantize( : array(1.0f, float32); scales = multiply(scales, scale_encode, s); scales = to_fp8(scales, s); - wq = multiply( - divide(wq, from_fp8(scales, w.dtype(), s), s), scale_encode, s); + auto dec = from_fp8(scales, w.dtype(), s); + auto zero = array(0, dec.dtype()); + wq = where( + not_equal(dec, zero, s), divide(wq, dec, s), zeros_like(wq, s), s); + wq = multiply(wq, scale_encode, s); } else { // convert to e8m0 auto z = array(0, scales.dtype()); @@ -5339,33 +5355,26 @@ std::vector fp_quantize( add(exponent, array(1, int32), s), exponent, s); - scales = where(equal(scales, z, s), z, exponent, s); + auto zero_max = equal(scales, z, s); + scales = where(zero_max, z, exponent, s); wq = divide(wq, power(array(2.0f, w.dtype()), scales, s), s); scales = astype(add(scales, array(127, int32), s), uint8, s); + scales = where(zero_max, array(0, uint8), scales, s); } if (bits == 4) { - auto lut = array({ - +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, - }); - lut = astype(lut, w.dtype(), s); - wq = argmin( - abs(subtract(expand_dims(wq, -1, s), lut, s), s), -1, false, s); + // Midpoints between the e2m1 magnitudes, ties go to the even code + auto mid = array({0.25f, 0.75f, 1.25f, 1.75f, 2.5f, 3.5f, 5.0f}); + mid = astype(mid, w.dtype(), s); + auto wa = abs(wq, s); + auto lo = searchsorted(mid, wa, "left", s); + auto hi = searchsorted(mid, wa, "right", s); + auto odd = astype(bitwise_and(lo, array(1, uint32), s), bool_, s); + auto sign_bit = multiply( + astype(less(wq, array(0, wq.dtype()), s), uint32, s), + array(8, uint32), + s); + wq = add(where(odd, hi, lo, s), sign_bit, s); auto shifts = power(array(2, uint32), arange(0, 32, 4, uint32, s), s); wq = reshape(wq, {-1, 4, 8}, s); wq = sum(multiply(wq, shifts, s), -1, false, s); @@ -5863,6 +5872,7 @@ array gather_qqmm( StreamOrDevice s) { auto stream = to_stream(s); auto qmode = string_to_quantization_mode(mode, "gather_qqmm"); + validate_qqmm_mode("gather_qqmm", qmode); auto [group_size, bits] = quantization_params_from_mode(qmode, group_size_, bits_); diff --git a/mlx/primitives.cpp b/mlx/primitives.cpp index 415db4e3fa..3670564d3e 100644 --- a/mlx/primitives.cpp +++ b/mlx/primitives.cpp @@ -1577,6 +1577,11 @@ std::vector Convolution::vjp( } // Grads for weight else if (a == 1) { + if (in.shape(0) == 0) { + grads.push_back(zeros_like(wt, stream())); + continue; + } + bool no_dilation = true; for (int i = 0; i < input_dilation_.size(); i++) { @@ -1819,6 +1824,11 @@ std::vector CustomTransforms::vjp( vjps.push_back(all_vjps[arg]); } + // Finish all requested vjps before any of them can start an earlier + // checkpoint. + if (synchronize_vjps_ && vjps.size() > 1) { + return depends(vjps, vjps); + } return vjps; } @@ -1886,10 +1896,16 @@ std::vector DivMod::vjp( const std::vector& primals, const std::vector& cotangents, const std::vector& argnums, - const std::vector&) { + const std::vector& outputs) { + // The quotient is floored so it has zero gradient std::vector vjps; for (auto arg : argnums) { - vjps.push_back(zeros_like(primals[arg], stream())); + if (arg == 0) { + vjps.push_back(cotangents[1]); + } else { + vjps.push_back( + negative(multiply(outputs[0], cotangents[1], stream()), stream())); + } } return vjps; } @@ -1898,16 +1914,25 @@ std::vector DivMod::jvp( const std::vector& primals, const std::vector& tangents, const std::vector& argnums) { - // One tangent per output; inputs are pre-broadcast and pre-promoted - auto zero = zeros_like(primals[0], stream()); - return {zero, zero}; + auto jvp_fun = [&](int i) { + if (argnums[i] == 0) { + return tangents[i]; + } + auto x_over_y = floor(divide(primals[0], primals[1], stream()), stream()); + return negative(multiply(x_over_y, tangents[i], stream()), stream()); + }; + auto rem = jvp_fun(0); + if (argnums.size() > 1) { + rem = add(rem, jvp_fun(1), stream()); + } + return {zeros_like(primals[0], stream()), rem}; } std::pair, std::vector> DivMod::vmap( const std::vector& inputs, const std::vector& axes) { auto [a, b, to_ax] = vmap_binary_op(inputs, axes, stream()); - return {divmod(a, b, stream()), {to_ax}}; + return {divmod(a, b, stream()), {to_ax, to_ax}}; } std::vector Divide::jvp( @@ -4686,8 +4711,10 @@ std::vector Scatter::vjp( gather(cotangents[0], indices, axes_, slice_sizes, stream()); auto gathered_result = gather(result, indices, axes_, slice_sizes, stream()); - vjps.push_back( - multiply(gathered_cotan, gathered_result == updates, stream())); + vjps.push_back(multiply( + gathered_cotan, + equal(gathered_result, updates, stream()), + stream())); break; } default: { diff --git a/mlx/primitives.h b/mlx/primitives.h index 68995b7503..908f33257f 100644 --- a/mlx/primitives.h +++ b/mlx/primitives.h @@ -847,9 +847,11 @@ class CustomTransforms : public Primitive { const std::vector&)> jvp, std::function, std::vector>( const std::vector&, - const std::vector&)> vmap) + const std::vector&)> vmap, + bool synchronize_vjps = false) : Primitive(stream), num_outputs_(num_outputs), + synchronize_vjps_(synchronize_vjps), vjp_fun_(std::move(vjp)), jvp_fun_(std::move(jvp)), vmap_fun_(std::move(vmap)) {} @@ -867,6 +869,7 @@ class CustomTransforms : public Primitive { void eval(const std::vector& inputs, std::vector& outputs); int num_outputs_; + bool synchronize_vjps_; std::function( const std::vector&, diff --git a/mlx/random.cpp b/mlx/random.cpp index 739ad25021..8f7d0f7b0b 100644 --- a/mlx/random.cpp +++ b/mlx/random.cpp @@ -1,6 +1,8 @@ // Copyright © 2023-2024 Apple Inc. #include +#include +#include #include #include @@ -14,6 +16,15 @@ namespace mlx::core::random { KeySequence::KeySequence(uint64_t seed) : key_(key(seed)) {} +uint64_t KeySequence::default_seed() { + static const uint64_t time_seed = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + static std::atomic count{0}; + return time_seed + count++; +} + void KeySequence::seed(uint64_t seed) { key_ = key((seed)); } diff --git a/mlx/random.h b/mlx/random.h index c09d12ebe5..ff5d3cfd88 100644 --- a/mlx/random.h +++ b/mlx/random.h @@ -2,7 +2,6 @@ #pragma once -#include #include #include "mlx/api.h" @@ -21,16 +20,13 @@ class MLX_API KeySequence { // Each thread has its own random key to avoid race condition. static KeySequence& default_() { - static auto time_seed = []() { - auto now = std::chrono::system_clock::now(); - return std::chrono::duration_cast( - now.time_since_epoch()) - .count(); - }(); - static thread_local KeySequence ks(time_seed); + static thread_local KeySequence ks(default_seed()); return ks; } + // Seed for a new default key. Each call returns a different seed. + static uint64_t default_seed(); + private: array key_; }; diff --git a/mlx/scheduler.cpp b/mlx/scheduler.cpp index 572e236bbe..ee7e740645 100644 --- a/mlx/scheduler.cpp +++ b/mlx/scheduler.cpp @@ -3,6 +3,7 @@ #include #include +#include "mlx/allocator.h" #include "mlx/backend/cpu/eval.h" #include "mlx/backend/gpu/eval.h" #include "mlx/compile_impl.h" @@ -11,6 +12,8 @@ namespace mlx::core { +static constexpr int MAX_ACTIVE_TASKS = 10; + void synchronize(Stream s) { if (s.device == mlx::core::Device::cpu) { auto p = std::make_shared>(); @@ -91,6 +94,27 @@ struct StreamThread { } }; +void Scheduler::wait_for_capacity(const std::set& open_streams) { + int n = n_active_tasks_.load(); + if (n <= MAX_ACTIVE_TASKS && !(n > 0 && allocator::over_memory_limit())) { + return; + } + // Commit any open streams + for (auto& s : open_streams) { + if (s.device == Device::gpu) { + gpu::finalize(s); + } + } + // Wait for one task to finish, repeat while memory is above the limit + do { + int n_old = n = n_active_tasks_.load(); + while (n_old > 1 && n >= n_old) { + n_active_tasks_.wait(n); + n = n_active_tasks_.load(); + } + } while (n > 0 && allocator::over_memory_limit()); +} + Scheduler::Scheduler() { is_main_thread(); gpu::init(); diff --git a/mlx/scheduler.h b/mlx/scheduler.h index 7bce5a9fe6..5c1a71b02a 100644 --- a/mlx/scheduler.h +++ b/mlx/scheduler.h @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -34,45 +35,26 @@ class MLX_API Scheduler { void check_error(Stream s); void notify_new_task(const Stream& stream) { - { - std::lock_guard lk(mtx); - n_active_tasks_++; - } - completion_cv.notify_all(); + n_active_tasks_.fetch_add(1); } void notify_task_completion(const Stream& stream) { - { - std::lock_guard lk(mtx); - n_active_tasks_--; - } - completion_cv.notify_all(); + n_active_tasks_.fetch_sub(1); + n_active_tasks_.notify_all(); } - int n_active_tasks() const { - return n_active_tasks_; - } - - void wait_for_one() { - std::unique_lock lk(mtx); - int n_tasks_old = n_active_tasks(); - if (n_tasks_old > 1) { - completion_cv.wait(lk, [this, n_tasks_old] { - return this->n_active_tasks() < n_tasks_old; - }); - } - } + // Block the caller when too many tasks or too much memory is in flight. + // Commits the GPU streams in open_streams first so that tasks can finish. + void wait_for_capacity(const std::set& open_streams); private: friend Stream mlx::core::new_stream(Device d); StreamThread& get_thread(Stream s); - int n_active_tasks_{0}; + std::atomic n_active_tasks_{0}; std::unordered_map> threads_; std::shared_mutex threads_mtx_; - std::condition_variable completion_cv; - std::mutex mtx; }; MLX_API Scheduler& scheduler(); @@ -98,10 +80,6 @@ inline void check_error(Stream s) { scheduler().check_error(s); } -inline int n_active_tasks() { - return scheduler().n_active_tasks(); -} - inline void notify_new_task(const Stream& stream) { scheduler().notify_new_task(stream); } @@ -110,8 +88,8 @@ inline void notify_task_completion(const Stream& stream) { scheduler().notify_task_completion(stream); } -inline void wait_for_one() { - scheduler().wait_for_one(); +inline void wait_for_capacity(const std::set& open_streams) { + scheduler().wait_for_capacity(open_streams); } } // namespace mlx::core::scheduler diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 24c91f3483..d5d1ef5fb6 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -24,10 +24,22 @@ namespace mlx::core { -static constexpr int MAX_ACTIVE_TASKS = 10; - namespace { +#ifndef NDEBUG +// Throw if a primitive did not set the data of each output. +void check_outputs_have_data(const array& arr) { + for (auto& out : arr.outputs()) { + if (!out.data_shared_ptr()) { + std::ostringstream msg; + msg << "[" << arr.primitive().name() << "] Output with shape " + << out.shape() << " has no data after eval."; + throw std::runtime_error(msg.str()); + } + } +} +#endif + // Get the stream of the first array that has a primitive, else the default. StreamOrDevice find_stream(const std::vector& arrays) { for (auto& a : arrays) { @@ -320,21 +332,14 @@ array eval_impl(std::vector outputs, bool async) { cpu::eval(arr); } - if (scheduler::n_active_tasks() > MAX_ACTIVE_TASKS || - (get_active_memory() > get_memory_limit() && - scheduler::n_active_tasks() > 0)) { - // Commit any open streams - for (auto& s : open_streams) { - if (s.device == Device::gpu) { - gpu::finalize(s); - } - } - scheduler::wait_for_one(); - while (get_active_memory() > get_memory_limit() && - scheduler::n_active_tasks() > 0) { - scheduler::wait_for_one(); - } +#ifndef NDEBUG + // The synchronizer has no output data. + if (arr.id() != synchronizer.id()) { + check_outputs_have_data(arr); } +#endif + + scheduler::wait_for_capacity(open_streams); auto maybe_update_fence = [&fences, &needs_fence, stream](const array& a) { @@ -1052,19 +1057,23 @@ std::function vmap( return [vfun](const array& a) { return vfun({a})[0]; }; } -std::function(const std::vector&)> custom_function( +namespace { + +std::function(const std::vector&)> +custom_function_impl( std::function(const std::vector&)> fun, std::optional( const std::vector&, const std::vector&, - const std::vector&)>> fun_vjp /* = std::nullopt */, + const std::vector&)>> fun_vjp, std::optional( const std::vector&, const std::vector&, - const std::vector&)>> fun_jvp /* = std::nullopt */, + const std::vector&)>> fun_jvp, std::optional, std::vector>( const std::vector&, - const std::vector&)>> fun_vmap /* = std::nullopt */) { + const std::vector&)>> fun_vmap, + bool synchronize_vjps) { if (!fun_vjp.has_value() && !fun_jvp.has_value() && !fun_vmap.has_value()) { return fun; } @@ -1072,7 +1081,8 @@ std::function(const std::vector&)> custom_function( return [fun = std::move(fun), fun_vjp = std::move(fun_vjp), fun_jvp = std::move(fun_jvp), - fun_vmap = std::move(fun_vmap)](const std::vector& args) { + fun_vmap = std::move(fun_vmap), + synchronize_vjps](const std::vector& args) { // Compute the outputs auto outputs = fun(args); @@ -1142,11 +1152,35 @@ std::function(const std::vector&)> custom_function( -> std::pair, std::vector> { std::vector out_axes(out_size, 0); return {vmap(fun, in_axes, out_axes)(inputs), out_axes}; - })), + }), + synchronize_vjps), inputs); }; } +} // namespace + +std::function(const std::vector&)> custom_function( + std::function(const std::vector&)> fun, + std::optional( + const std::vector&, + const std::vector&, + const std::vector&)>> fun_vjp /* = std::nullopt */, + std::optional( + const std::vector&, + const std::vector&, + const std::vector&)>> fun_jvp /* = std::nullopt */, + std::optional, std::vector>( + const std::vector&, + const std::vector&)>> fun_vmap /* = std::nullopt */) { + return custom_function_impl( + std::move(fun), + std::move(fun_vjp), + std::move(fun_jvp), + std::move(fun_vmap), + false); +} + std::function(const std::vector&)> custom_vjp( std::function(const std::vector&)> fun, std::function( @@ -1162,11 +1196,16 @@ std::function(const std::vector&)> checkpoint( const std::vector& primals, const std::vector& cotangents, const std::vector& outputs) -> std::vector { - auto [__, vjps] = vjp(fun, depends(primals, outputs), cotangents); + // Do not recompute before the outputs and the cotangents are available. + auto dependencies = outputs; + dependencies.insert( + dependencies.end(), cotangents.begin(), cotangents.end()); + auto [__, vjps] = vjp(fun, depends(primals, dependencies), cotangents); return vjps; }; - return custom_vjp(fun, vjp_fun); + return custom_function_impl( + std::move(fun), std::move(vjp_fun), std::nullopt, std::nullopt, true); } } // namespace mlx::core diff --git a/mlx/utils.cpp b/mlx/utils.cpp index 3030df91e3..62470e556e 100644 --- a/mlx/utils.cpp +++ b/mlx/utils.cpp @@ -4,9 +4,17 @@ #include #include #include -#include #include +#if defined(__APPLE__) +#include +#elif defined(__linux__) +#include +#include +#else +#include +#endif + #include "mlx/dtype_utils.h" #include "mlx/types/limits.h" #include "mlx/utils.h" @@ -126,8 +134,14 @@ void set_printoptions(PrintOptions options) { } bool is_main_thread() { +#if defined(__APPLE__) + return pthread_main_np() != 0; +#elif defined(__linux__) + return syscall(SYS_gettid) == getpid(); +#else static auto main_thread_id = std::this_thread::get_id(); return main_thread_id == std::this_thread::get_id(); +#endif } Dtype result_type(const std::vector& arrays) { @@ -324,14 +338,15 @@ finfo::finfo(Dtype dtype) : dtype(dtype) { } template -void set_iinfo_limits(int64_t& min, uint64_t& max) { +void set_iinfo_limits(int& bits, int64_t& min, uint64_t& max) { + bits = 8 * sizeof(T); min = std::numeric_limits::min(); max = std::numeric_limits::max(); } iinfo::iinfo(Dtype dtype) : dtype(dtype) { dispatch_int_types(dtype, "[iinfo]", [&](auto type_tag) { - set_iinfo_limits(min, max); + set_iinfo_limits(bits, min, max); }); } diff --git a/mlx/utils.h b/mlx/utils.h index 1f207a087a..bcbc5d16e7 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -85,7 +85,8 @@ MLX_API void set_printoptions(PrintOptions options); MLX_API PrintFormatter& get_global_formatter(); -/** Return whether current thread is the first one that called this function. */ +/** Check for the process main thread on Apple platforms and Linux. + * Elsewhere, compare with the thread ID from the first call. */ bool is_main_thread(); /** Holds information about floating-point types. */ @@ -103,6 +104,7 @@ struct MLX_API finfo { struct MLX_API iinfo { explicit iinfo(Dtype dtype); Dtype dtype; + int bits; int64_t min; uint64_t max; }; diff --git a/python/mlx/nn/layers/activations.py b/python/mlx/nn/layers/activations.py index 1511c129e0..a3c83eb2c4 100644 --- a/python/mlx/nn/layers/activations.py +++ b/python/mlx/nn/layers/activations.py @@ -184,7 +184,12 @@ def gelu_approx(x): x^3\right)\right)\right) """ - return 0.5 * x * (1 + mx.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3))) + # The clip does not change the output (tanh is +-1 for |x| >= 10). Taking the + # tanh gradient through t keeps float16 gradients free of inf * 0. + t = mx.clip(x, -10, 10) + u = 1 + mx.tanh(math.sqrt(2 / math.pi) * (t + 0.044715 * t**3)) + v = mx.stop_gradient(u) + return 0.5 * x * v + 0.5 * t * (u - v) @partial(mx.compile, shapeless=True) diff --git a/python/mlx/nn/utils.py b/python/mlx/nn/utils.py index 2f057235b9..2c89b9e93a 100644 --- a/python/mlx/nn/utils.py +++ b/python/mlx/nn/utils.py @@ -186,7 +186,8 @@ def clip_grad_norm_sharded( :func:`mlx.optimizers.clip_grad_norm`. Each member of the group holds only a shard of the gradients, so the global norm is computed by summing the local squared norms across the group before rescaling. It is useful for - clipping the gradients of a module wrapped with :func:`mlx.nn.fully_shard`. + clipping the gradients of a module wrapped with + :func:`mlx.nn.layers.distributed.fully_shard`. Args: gradients (Any): A Python tree containing the local shard of the @@ -200,11 +201,24 @@ def clip_grad_norm_sharded( (Any, mlx.core.array): The possibly rescaled local shard of the gradients and the global gradient norm. """ + + def squared_norm(g): + # Sum float16 squares in float32 so they do not overflow + if g.dtype == mx.float16: + g = g.astype(mx.float32) + return g.square().sum() + + def scale(g): + # Cast after scaling so small normalizers do not underflow in float16 + if mx.issubdtype(g.dtype, mx.floating): + return (g * normalizer).astype(g.dtype) + return g * normalizer + local_norm_squared = tree_reduce( - lambda acc, g: acc + g.square().sum(), gradients, 0.0 + lambda acc, g: acc + squared_norm(g), gradients, 0.0 ) global_norm_squared = mx.distributed.all_sum(local_norm_squared, group=group) grad_norm = mx.sqrt(global_norm_squared) normalizer = mx.minimum(max_norm / (grad_norm + 1e-6), 1.0) - clipped_gradients = tree_map(lambda g: g * normalizer, gradients) + clipped_gradients = tree_map(scale, gradients) return clipped_gradients, grad_norm diff --git a/python/src/array.cpp b/python/src/array.cpp index e634bf31b7..b68452d65b 100644 --- a/python/src/array.cpp +++ b/python/src/array.cpp @@ -206,6 +206,11 @@ void init_array(nb::module_& m) { Get information on floating-point types. )pbdoc") .def(nb::init()) + .def( + "__init__", + [](mx::finfo* self, const mx::array& a) { + new (self) mx::finfo(a.dtype()); + }) .def_ro( "bits", &mx::finfo::bits, @@ -248,6 +253,15 @@ void init_array(nb::module_& m) { Get information on integer types. )pbdoc") .def(nb::init()) + .def( + "__init__", + [](mx::iinfo* self, const mx::array& a) { + new (self) mx::iinfo(a.dtype()); + }) + .def_ro( + "bits", + &mx::iinfo::bits, + R"pbdoc(The number of bits occupied by the type.)pbdoc") .def_ro( "min", &mx::iinfo::min, diff --git a/python/src/fast.cpp b/python/src/fast.cpp index 8a211b71f1..63a34d58a3 100644 --- a/python/src/fast.cpp +++ b/python/src/fast.cpp @@ -455,18 +455,27 @@ void init_fast(nb::module_& parent_module) { "mask"_a = nb::none(), // optional, defaults to None "stream"_a = nb::none(), // optional, defaults to None R"( - Chunked gated delta network forward pass. + Gated delta network forward pass. + + The number of value heads ``Hv`` must be a multiple of the number + of query and key heads ``Hk``. Args: - q: Queries [B, T, Hk, Dk] - k: Keys [B, T, Hk, Dk] - v: Values [B, T, Hv, Dv] - gamma: Decay rate in linear space [B, T, Hv] - beta: Delta update rates [B, T, Hv] - initial_state: Optional initial hidden state [B, T, Hk, Dv] - mask: Optional + q (array): Queries with shape ``[B, T, Hk, Dk]``. + k (array): Keys with shape ``[B, T, Hk, Dk]``. + v (array): Values with shape ``[B, T, Hv, Dv]``. + gamma (array): Decay rates in linear space with shape + ``[B, T, Hv]`` or ``[B, T, Hv, Dk]``. + beta (array): Delta update rates with shape ``[B, T, Hv]``. + initial_state (array, optional): Initial state with shape + ``[B, Hv, Dv, Dk]``. Default: zeros. + mask (array, optional): Boolean mask with shape ``[B, T]``. + False entries leave the state unchanged and produce zero + output. Default: ``None``. + Returns: - Tuple of (output [B, T, Hv, Dv], final_state [B, T, Hk, Dv]) + list(array): The output with shape ``[B, T, Hv, Dv]`` and the + final state with shape ``[B, Hv, Dv, Dk]`` and dtype ``float32``. )"); m.def( diff --git a/python/src/memory.cpp b/python/src/memory.cpp index 5719449535..cefe8054e7 100644 --- a/python/src/memory.cpp +++ b/python/src/memory.cpp @@ -127,7 +127,8 @@ void init_memory(nb::module_& m) { memory size. The wired limit is the total size in bytes of memory that will be kept - resident. The default value is ``0``. + resident. The default value is ``0``. It applies to memory MLX allocates; + arrays that wrap caller-owned memory without a copy are not wired. Setting a wired limit larger than system wired limit is an error. You can increase the system wired limit with: diff --git a/python/src/metal.cpp b/python/src/metal.cpp index 8d0d4242e2..596a1b8738 100644 --- a/python/src/metal.cpp +++ b/python/src/metal.cpp @@ -33,6 +33,12 @@ void init_metal(nb::module_& m) { R"pbdoc( Check if the Metal back-end is available. )pbdoc"); + metal.def( + "is_nax_available", + &mx::metal::is_nax_available, + R"pbdoc( + Check if MLX kernels can use the GPU neural accelerators (NAX). + )pbdoc"); metal.def("get_active_memory", []() { DEPRECATE("mx.metal.get_active_memory", "mx.get_active_memory"); return mx::get_active_memory(); diff --git a/python/src/mlx.cpp b/python/src/mlx.cpp index 677de7b787..f61fb5485c 100644 --- a/python/src/mlx.cpp +++ b/python/src/mlx.cpp @@ -35,6 +35,7 @@ NB_MODULE(core, m) { auto array_namespace_info = nb::module_::import_("mlx.__array_api_info"); m.attr("__array_namespace_info__") = array_namespace_info.attr("__array_namespace_info__"); + m.attr("__array_api_version__") = "2025.12"; init_mlx_func(m); init_config(m); diff --git a/python/src/ops.cpp b/python/src/ops.cpp index 347cc24ab8..2f9d472b68 100644 --- a/python/src/ops.cpp +++ b/python/src/ops.cpp @@ -257,7 +257,7 @@ void init_ops(nb::module_& m) { Args: a (array): Input array. - axes (int or tuple(int)): The index of the inserted dimensions. + axis (int or tuple(int)): The index of the inserted dimensions. Returns: array: The array with inserted dimensions. @@ -1514,7 +1514,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def arange(start : int | float, stop : None | int | float, step : None | int | float, dtype: Dtype | None = None, *, stream: StreamOrDevice = None) -> array"), + "def arange(start : int | float, stop : None | int | float, step : None | int | float = None, dtype: Dtype | None = None, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Generates ranges of numbers. @@ -2642,7 +2642,7 @@ void init_ops(nb::module_& m) { "keepdims"_a = false, "stream"_a = nb::none(), nb::sig( - "def count_nonzero(a: array, /, *, axis: None | int | Sequence[int] = None, keepdims: bool = False, stream: StreamOrDevice = None) -> array"), + "def count_nonzero(a: array, /, axis: None | int | Sequence[int] = None, *, keepdims: bool = False, stream: StreamOrDevice = None) -> array"), R"pbdoc( Count the number of non-zero elements along the given axis. @@ -2923,7 +2923,7 @@ void init_ops(nb::module_& m) { "correction"_a = nb::none(), "stream"_a = nb::none(), nb::sig( - "def var(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, stream: StreamOrDevice = None) -> array"), + "def var(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, correction: int | None = None, stream: StreamOrDevice = None) -> array"), R"pbdoc( Compute the variance(s) over the given axes. @@ -2936,6 +2936,8 @@ void init_ops(nb::module_& m) { singleton dimensions, defaults to `False`. ddof (int, optional): The divisor to compute the variance is ``N - ddof``, defaults to 0. + correction (int, optional): If set, overrides ``ddof``. + Default: ``None``. Returns: array: The output array of variances. @@ -2959,7 +2961,7 @@ void init_ops(nb::module_& m) { "correction"_a = nb::none(), "stream"_a = nb::none(), nb::sig( - "def std(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, stream: StreamOrDevice = None) -> array"), + "def std(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, correction: int | None = None, stream: StreamOrDevice = None) -> array"), R"pbdoc( Compute the standard deviation(s) over the given axes. @@ -2972,6 +2974,8 @@ void init_ops(nb::module_& m) { singleton dimensions, defaults to `False`. ddof (int, optional): The divisor to compute the variance is ``N - ddof``, defaults to 0. + correction (int, optional): If set, overrides ``ddof``. + Default: ``None``. Returns: array: The output array of standard deviations. @@ -3778,7 +3782,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def astype(a: array, dtype: Dtype, /, *, stream: StreamOrDevice = None) -> array"), + "def astype(a: array, /, dtype: Dtype, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Cast the array to a specified type. @@ -4674,7 +4678,7 @@ void init_ops(nb::module_& m) { "arrays"_a, "metadata"_a = nb::none(), nb::sig( - "def save_gguf(file: file | str | pathlib.Path, arrays: dict[str, array], metadata: dict[str, array | str | list[str]])"), + "def save_gguf(file: file | str | pathlib.Path, arrays: dict[str, array], metadata: dict[str, array | str | list[str]] | None = None)"), R"pbdoc( Save array(s) to a binary file in ``.gguf`` format. @@ -4686,9 +4690,10 @@ void init_ops(nb::module_& m) { file (file, str, pathlib.Path): File in which the array is saved. arrays (dict(str, array)): The dictionary of names to arrays to be saved. - metadata (dict(str, Union[array, str, list(str)])): The dictionary + metadata (dict(str, Union[array, str, list(str)]), optional): The dictionary of metadata to be saved. The values can be a scalar or 1D obj:`array`, a :obj:`str`, or a :obj:`list` of :obj:`str`. + Defaults to ``None``. )pbdoc"); m.def( "where", @@ -5071,7 +5076,7 @@ void init_ops(nb::module_& m) { ``x`` and ``w``. See supported values and defaults in the :ref:`table of quantization modes `. Default: ``None``. mode (str, optional): The quantization mode. Default: ``"nvfp4"``. - Supported modes are ``nvfp4`` and ``mxfp8``. See the + Supported modes are ``nvfp4``, ``mxfp4`` and ``mxfp8``. See the :ref:`table of quantization modes ` for details. global_scale_x (array, optional): The per-input float32 scale used for x with ``"nvfp4"`` quantization. Default: ``None``. @@ -5082,7 +5087,6 @@ void init_ops(nb::module_& m) { Returns: array: The result of the multiplication of quantized ``x`` with quantized ``w``. - needed). )pbdoc"); m.def( "segmented_mm", @@ -5173,7 +5177,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def vecdot(a: array, b: array, /, *, axis: int = -1, stream: StreamOrDevice = None) -> array"), + "def vecdot(a: array, b: array, /, axis: int = -1, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Compute the vector dot product of two arrays along an axis. @@ -6006,7 +6010,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def roll(a: array, shift: int | tuple[int], axis: None | int | tuple[int] = None, /, *, stream: StreamOrDevice = None) -> array"), + "def roll(a: array, /, shift: int | tuple[int], axis: None | int | tuple[int] = None, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Roll array elements along a given axis. @@ -6270,7 +6274,7 @@ void init_ops(nb::module_& m) { If ``w`` is expected to receive gradients, it must be provided in non-quantized form. - If ``x`` and `w`` are not quantized, their data types must be ``float32``, + If ``x`` and ``w`` are not quantized, their data types must be ``float32``, ``float16``, or ``bfloat16``. If ``w`` is quantized, it must be packed in unsigned integers. ``global_scale_x`` and ``global_scale_w`` are only used for ``nvfp4`` quantization. @@ -6287,15 +6291,14 @@ void init_ops(nb::module_& m) { ``x`` and ``w``. See supported values and defaults in the :ref:`table of quantization modes `. Default: ``None``. mode (str, optional): The quantization mode. Default: ``"nvfp4"``. - Supported modes are ``nvfp4`` and ``mxfp8``. See the + Supported modes are ``nvfp4``, ``mxfp4`` and ``mxfp8``. See the :ref:`table of quantization modes ` for details. - global_scale (array, optional): The per-input float32 scale used for x + global_scale_x (array, optional): The per-input float32 scale used for x with ``"nvfp4"`` quantization. Default: ``None``. global_scale_w (array, optional): The per-input float32 scale used for w with ``"nvfp4"`` quantization. Default: ``None``. Returns: array: The result of the multiplication of quantized ``x`` with quantized ``w``. - needed). )pbdoc"); m.def( "from_fp8", diff --git a/python/src/random.cpp b/python/src/random.cpp index 68eb6eaf9f..8e4e9c3e48 100644 --- a/python/src/random.cpp +++ b/python/src/random.cpp @@ -5,8 +5,6 @@ #include #include -#include - #include "mlx/ops.h" #include "mlx/random.h" #include "python/src/random.h" @@ -42,14 +40,8 @@ class PyKeySequence { nb::list& state() { if (!state_) { - static auto time_seed = []() { - auto now = std::chrono::system_clock::now(); - return std::chrono::duration_cast( - now.time_since_epoch()) - .count(); - }(); state_ = nb::list(); - state_->append(mx::random::key(time_seed)); + state_->append(mx::random::key(mx::random::KeySequence::default_seed())); } return *state_; } diff --git a/python/tests/mlx_distributed_tests.py b/python/tests/mlx_distributed_tests.py index fc6d81a043..aa16a79f85 100644 --- a/python/tests/mlx_distributed_tests.py +++ b/python/tests/mlx_distributed_tests.py @@ -424,6 +424,29 @@ def test_clip_grad_norm_sharded(self): ) ) + def test_clip_grad_norm_sharded_float16(self): + world = mx.distributed.init() + N = world.size() + + # 300^2 overflows float16 + grads_slice = {"a": mx.full((4,), 300.0, dtype=mx.float16)} + expected_norm = math.sqrt(N * 4) * 300.0 + + for max_norm in (1.0, 1e-5): + clipped, grad_norm = clip_grad_norm_sharded( + grads_slice, max_norm=max_norm, group=world + ) + mx.eval(clipped, grad_norm) + self.assertEqual(grad_norm.dtype, mx.float32) + self.assertTrue( + mx.allclose(grad_norm, mx.array(expected_norm), rtol=self.rtol) + ) + self.assertEqual(clipped["a"].dtype, mx.float16) + expected = 300.0 * max_norm / expected_norm + self.assertTrue( + mx.allclose(clipped["a"], mx.array(expected), rtol=1e-3, atol=1e-7) + ) + def test_jaccl_all_gather_factory_validation(self): # A custom side-channel factory is only valid with the jaccl backend. with self.assertRaises(ValueError): diff --git a/python/tests/test_array.py b/python/tests/test_array.py index 425a592687..e7ad090b5e 100644 --- a/python/tests/test_array.py +++ b/python/tests/test_array.py @@ -176,6 +176,7 @@ def test_finfo(self): float(np.finfo(np.float32).smallest_normal), ) self.assertEqual(mx.finfo(mx.float32).dtype, mx.float32) + self.assertEqual(mx.finfo(mx.array(1.0, dtype=mx.float16)).dtype, mx.float16) self.assertEqual(mx.finfo(mx.float16).min, np.finfo(np.float16).min) self.assertEqual(mx.finfo(mx.float16).max, np.finfo(np.float16).max) @@ -209,6 +210,10 @@ def test_iinfo(self): self.assertEqual(mx.iinfo(mx.uint32).max, np.iinfo(np.uint32).max) self.assertEqual(mx.iinfo(mx.int8).dtype, mx.int8) + for t in [mx.int8, mx.uint16, mx.int32, mx.uint64]: + self.assertEqual(mx.iinfo(t).bits, t.size * 8) + self.assertEqual(mx.iinfo(mx.array(1, dtype=mx.int16)).dtype, mx.int16) + def test_result_type(self): self.assertEqual(mx.result_type(mx.int8, mx.int16), mx.int16) self.assertEqual(mx.result_type(mx.float32, mx.float64), mx.float64) diff --git a/python/tests/test_autograd.py b/python/tests/test_autograd.py index bb933d405c..9a8b09500d 100644 --- a/python/tests/test_autograd.py +++ b/python/tests/test_autograd.py @@ -253,7 +253,7 @@ def fun(x): _, (dq, dr) = mx.jvp(fun, [mx.array(7.0)], [mx.array(1.0)]) self.assertEqual(dq.item(), 0.0) - self.assertEqual(dr.item(), 0.0) + self.assertEqual(dr.item(), -1.0) # slice_update with dynamic start indices and a subset of traced # inputs (issue #3634) @@ -279,6 +279,58 @@ def fun(s, u): _, (j,) = mx.jvp(fun, [src, upd], [mx.ones(4), mx.full(2, 2.0)]) self.assertEqual(j.tolist(), [1.0, 2.0, 2.0, 1.0]) + def test_divmod_grads(self): + x = mx.array([5.5, -3.25, 7.0, -7.5, 0.5]) + y = mx.array([2.0, 1.5, -2.5, -2.0, 4.0]) + q, _ = mx.divmod(x, y) + self.assertTrue(mx.array_equal(q, mx.floor_divide(x, y))) + + def rem(x, y): + return mx.divmod(x, y)[1] + + def quo(x, y): + return mx.divmod(x, y)[0] + + wq = mx.array([1.0, -2.0, 3.0, 0.5, 4.0]) + wr = mx.array([0.5, 2.0, -1.0, 3.0, 1.5]) + + # vjp + gx, gy = mx.vjp(lambda x, y: mx.divmod(x, y), [x, y], [wq, wr])[1] + self.assertTrue(mx.allclose(gx, wr)) + self.assertTrue(mx.allclose(gy, -q * wr)) + + gx, gy = mx.vjp(lambda x, y: mx.divmod(x, y), [x, y], [wq, mx.zeros_like(wr)])[ + 1 + ] + self.assertTrue(mx.array_equal(gx, mx.zeros_like(x))) + self.assertTrue(mx.array_equal(gy, mx.zeros_like(y))) + + # Same gradients as remainder + gx, gy = mx.grad(lambda x, y: rem(x, y).sum(), argnums=(0, 1))(x, y) + ex, ey = mx.grad(lambda x, y: mx.remainder(x, y).sum(), argnums=(0, 1))(x, y) + self.assertTrue(mx.allclose(gx, ex)) + self.assertTrue(mx.allclose(gy, ey)) + self.assertTrue(mx.allclose(gx, mx.ones_like(x))) + gx, gy = mx.grad(lambda x, y: quo(x, y).sum(), argnums=(0, 1))(x, y) + self.assertTrue(mx.array_equal(gx, mx.zeros_like(x))) + self.assertTrue(mx.array_equal(gy, mx.zeros_like(y))) + + # jvp + tx = mx.array([1.0, 2.0, -1.0, 0.5, 3.0]) + ty = mx.array([0.5, -1.0, 2.0, 1.0, -0.5]) + + _, (dq, dr) = mx.jvp(lambda x, y: mx.divmod(x, y), [x, y], [tx, ty]) + self.assertTrue(mx.array_equal(dq, mx.zeros_like(x))) + self.assertTrue(mx.allclose(dr, tx - q * ty)) + + _, (dq, dr) = mx.jvp(lambda x: mx.divmod(x, y), [x], [tx]) + self.assertTrue(mx.array_equal(dq, mx.zeros_like(x))) + self.assertTrue(mx.allclose(dr, tx)) + + _, (dq, dr) = mx.jvp(lambda y: mx.divmod(x, y), [y], [ty]) + self.assertTrue(mx.array_equal(dq, mx.zeros_like(x))) + self.assertTrue(mx.allclose(dr, -q * ty)) + def test_grad(self): def fun(x): return x * x @@ -1452,6 +1504,51 @@ def f(x): mem_post = mx.get_active_memory() self.assertEqual(mem_pre, mem_post) + def test_checkpoint_recurrence_memory(self): + # Chunked recurrence with gradients for the per-step inputs (#4837) + H, D, C = 4, 128, 32 + + def step(s, q, k, v): + ys = [] + for t in range(q.shape[0]): + s = s * 0.95 + delta = v[t] - (s * k[t][:, None, :]).sum(-1) + s = s + delta[:, :, None] * k[t][:, None, :] + ys.append((s * q[t][:, None, :]).sum(-1)) + return s, mx.stack(ys) + + def loss(x0, chunks): + s, total = x0, mx.array(0.0) + for q, k, v in chunks: + s, y = mx.checkpoint(step)(s, q, k, v) + total = total + y.sum() + return total + + def peak_memory(num_chunks): + mx.random.seed(0) + chunks = [ + ( + mx.random.normal((C, H, D)), + 0.05 * mx.random.normal((C, H, D)), + mx.random.normal((C, H, D)), + ) + for _ in range(num_chunks) + ] + x0 = mx.zeros((H, D, D)) + mx.eval(chunks, x0) + mx.synchronize() + gc.collect() + mx.reset_peak_memory() + base = mx.get_active_memory() + out = mx.value_and_grad(loss, argnums=(0, 1))(x0, chunks) + mx.eval(out) + return mx.get_peak_memory() - base + + # Without bounded recomputation, about one state per step stays alive + state_size = H * D * D * 4 + growth = peak_memory(16) - peak_memory(4) + self.assertLess(growth / (12 * C * state_size), 0.25) + def test_grad_with_copies(self): a = mx.array(2.0) arrays = [a, a, a] diff --git a/python/tests/test_blas.py b/python/tests/test_blas.py index 5a2068b182..8fd7912c96 100644 --- a/python/tests/test_blas.py +++ b/python/tests/test_blas.py @@ -329,6 +329,7 @@ def test_matrix_vector(self): (2, 2), (32, 32), (64, 64), + (300, 40), (2048, 2048), ): for mi in (-1, 0, 1): @@ -369,6 +370,8 @@ def test_matrix_vector_batched(self): ((32, 1, 128), (128, 64)), ((1, 128), (32, 128, 64)), ((1, 8, 4, 1, 128), (1, 8, 1, 128, 6)), + ((3, 1, 300), (3, 300, 40)), + ((2, 1, 1, 300), (1, 3, 300, 40)), ): self.__gemv_test( shape_mat, shape_vec, mat_first=False, np_dtype=np_dtype @@ -814,6 +817,21 @@ def test_addmm(self): self.assertListEqual(list(d_npy.shape), list(d_mlx.shape)) self.assertTrue(np.allclose(d_mlx, d_npy, atol=1e-5)) + # Matmul with vector and a long K, on a local generator to keep + # the global numpy state for later tests + rng = np.random.default_rng(0) + for k, n, batch in ((512, 128, (4,)), (8192, 2048, ())): + a_npy = rng.normal(0.0, 1.0 / 128, (k,)).astype(np.float32) + b_npy = rng.normal(0.0, 1.0 / 128, batch + (k, n)).astype(np.float32) + + for c_shape in ((1,), (n,), batch + (n,)): + c_npy = np.ones(c_shape).astype(np.float32) + d_npy = alpha * (a_npy @ b_npy) + beta * c_npy + d_mlx = mx.addmm( + mx.array(c_npy), mx.array(a_npy), mx.array(b_npy), alpha, beta + ) + self.assertTrue(np.allclose(d_mlx, d_npy, atol=1e-5)) + # Matmul with vector a_npy = np.random.normal(0.0, 1.0 / 128, (32, 128, 16)).astype(np.float32) b_npy = np.random.normal(0.0, 1.0 / 128, (16,)).astype(np.float32) @@ -952,6 +970,19 @@ def test_thin_matmul(self): ref_c = 0.5 * ref + 2.0 * c_r self.assertTrue(np.allclose(out, ref_c, 1e-2, 0.125 * scale)) + def test_matmul_large_output(self): + if not mx.cuda.is_available() or mx.default_device() == mx.cpu: + self.skipTest("CUDA only") + + # M * N = 2**32 does not fit in int32 + a = mx.ones((16384, 64), mx.float16) + b = mx.ones((64, 262144), mx.float16) + c = mx.ones((262144,), mx.float16) + out = a @ b + self.assertEqual(out[-1, -1].item(), 64.0) + out = mx.addmm(c, a, b, 1.0, 2.0) + self.assertEqual(out[-1, -1].item(), 66.0) + def test_addmm_grad(self): def make_ref_addmm(alpha, beta): return lambda c, a, b: alpha * (a @ b) + beta * c diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 7436e58cd2..6209805f69 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -1728,6 +1728,16 @@ 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_output_through_noop_is_kept(self): + def fun(x): + a = x.astype(mx.float32) * 2 + b = mx.stop_gradient(x.astype(mx.float32)) + return a, b + + a, b = mx.compile(fun)(mx.array([1, 2, 3])) + self.assertTrue(mx.array_equal(a, mx.array([2.0, 4.0, 6.0]))) + self.assertTrue(mx.array_equal(b, mx.array([1.0, 2.0, 3.0]))) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_conv.py b/python/tests/test_conv.py index 7c8fee4975..c4a5d1176d 100644 --- a/python/tests/test_conv.py +++ b/python/tests/test_conv.py @@ -600,6 +600,16 @@ def run_conv3D( N, C, OC, idim, kdim, stride, padding, dilation=(2, 2, 2), dtype=dtype ) + def test_conv_3D_output_reshape_transpose(self): + # A dense output with no contiguity flags must stay correct after a + # reshape and transpose. + x = mx.random.normal((2, 12, 15, 18, 2)) + w = mx.random.normal((240, 4, 5, 6, 2)) + y = mx.conv_general(x, w, stride=(4, 5, 6)) + out = y.reshape(-1, 240).T.reshape(-1) + expected = np.array(y).reshape(-1, 240).T.reshape(-1) + self.assertTrue(np.array_equal(out, expected)) + @unittest.skipIf(not has_torch, "requires Torch") def test_torch_conv_3D_grad(self): def run_conv3D_grad( diff --git a/python/tests/test_device.py b/python/tests/test_device.py index 86f7fbebd1..ef7ac99a8c 100644 --- a/python/tests/test_device.py +++ b/python/tests/test_device.py @@ -194,6 +194,12 @@ def test_cuda_get_arch_list(self): else: self.assertEqual(arch_list, []) + def test_metal_is_nax_available(self): + nax = mx.metal.is_nax_available() + self.assertIsInstance(nax, bool) + if not mx.metal.is_available(): + self.assertFalse(nax) + def test_device_info_default(self): info = mx.device_info() self.assertIsInstance(info, dict) diff --git a/python/tests/test_eval.py b/python/tests/test_eval.py index 9801f82c7a..1ea63208df 100644 --- a/python/tests/test_eval.py +++ b/python/tests/test_eval.py @@ -255,6 +255,111 @@ def test_eval_exception_after_cross_stream_wait(self): self.assertTrue(mx.all(x == 6.0).item()) self.assertEqual((mx.ones((4,), stream=mx.cpu) + 1).sum().item(), 8.0) + def test_empty_outputs(self): + # Read each output on the CPU, so an output with no data fails + def check(outs): + outs = outs if isinstance(outs, (list, tuple)) else [outs] + mx.eval(outs) + for o in outs: + self.assertTrue(mx.array_equal(o, o, stream=mx.cpu).item()) + + z = mx.zeros + + def q(w): + return mx.quantize(w, 64, 4) + + for s in [mx.cpu, mx.gpu]: + if not mx.is_available(s): + continue + with self.subTest(stream=s), mx.stream(s): + check(mx.matmul(z((0, 32)), z((32, 16)), stream=s)) + check(mx.matmul(z((0, 32)), z((32,)), stream=s)) + check(mx.addmm(z((0, 16)), z((0, 32)), z((32, 16)), stream=s)) + check(mx.block_masked_mm(z((0, 64)), z((64, 64)), 32, stream=s)) + idx = mx.array([], dtype=mx.uint32) + check(mx.gather_mm(z((2, 4, 8)), z((2, 8, 5)), idx, idx, stream=s)) + check(mx.pad(z((0, 4)), [(0, 0), (1, 1)], stream=s)) + check(mx.quantize(z((0, 64)), 64, 4, stream=s)) + if s == mx.gpu: + check(mx.dequantize(*q(z((0, 64))), 64, 4, stream=s)) + check(mx.quantized_matmul(z((0, 64)), *q(z((32, 64))), stream=s)) + check(mx.conv2d(z((0, 8, 8, 4)), z((2, 3, 3, 4)), stream=s)) + check(mx.conv2d(z((2, 8, 8, 4)), z((0, 3, 3, 4)), stream=s)) + check(mx.fft.rfft(z((0, 8)), stream=s)) + check(mx.softmax(z((4, 0)), axis=-1, stream=s)) + check(mx.fast.rms_norm(z((0, 4)), z((4,)), 1e-5, stream=s)) + check( + mx.fast.rope( + z((0, 4, 8)), + 8, + traditional=False, + base=1e4, + scale=1.0, + offset=0, + stream=s, + ) + ) + qkv = z((0, 2, 4, 64)) + check( + mx.fast.scaled_dot_product_attention( + qkv, qkv, qkv, scale=1.0, stream=s + ) + ) + keys = z((0, 2), mx.uint32) + check(mx.vmap(lambda k: mx.random.uniform(shape=(3,), key=k))(keys)) + idx = mx.array([0, 1]) + check(z((4, 0)).at[idx].add(z((2, 0)))) + a = z((4, 4)) + a[a > 1] = z((0,)) + check(a) + + # Compiled kernel with empty output + f = mx.compile(lambda a, b: mx.exp(a) * b) + check(f(z((17, 0)), z((0,)))) + + # Empty input with non-empty output must give zeros + out = mx.conv2d(z((2, 8, 8, 0)), z((2, 3, 3, 0)), stream=s) + self.assertTrue(mx.array_equal(out, z((2, 6, 6, 2)))) + out = mx.segmented_mm( + z((4, 0)), z((0, 5)), mx.array([[0, 0]], dtype=mx.uint32) + ) + self.assertTrue(mx.array_equal(out, z((1, 4, 5)))) + o = mx.ones + out = mx.quantized_matmul(o((4, 0)), *q(o((32, 0))), stream=s) + self.assertTrue(mx.array_equal(out, z((4, 32)))) + + # Gradient of a weight with an empty input is zero + w = mx.ones((4,)) + g = mx.grad(lambda w: mx.fast.rms_norm(z((0, 4)), w, 1e-5).sum())(w) + self.assertTrue(mx.array_equal(g, z((4,)))) + + def test_empty_lu(self): + p, lower, upper = mx.linalg.lu(mx.zeros((2, 3, 0)), stream=mx.cpu) + self.assertTrue(mx.array_equal(p, mx.array([[0, 1, 2], [0, 1, 2]]))) + self.assertEqual(lower.shape, (2, 3, 0)) + self.assertEqual(upper.shape, (2, 0, 0)) + + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_custom_kernel_empty_and_nonempty_outputs(self): + kernel = mx.fast.metal_kernel( + name="empty_and_nonempty", + input_names=["a"], + output_names=["out0", "out1"], + source="uint e = thread_position_in_grid.x; out1[e] = a[e];", + ) + a = mx.ones((4,)) + out0, out1 = kernel( + inputs=[a], + grid=(4, 1, 1), + threadgroup=(4, 1, 1), + output_shapes=[(0,), (4,)], + output_dtypes=[mx.float32, mx.float32], + init_value=0, + ) + mx.eval(out0, out1) + self.assertTrue(mx.array_equal(out0, out0, stream=mx.cpu)) + self.assertTrue(mx.array_equal(out1, a)) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index db45a15479..453757d1a5 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -426,29 +426,13 @@ def test_sdpa_full_head_dim_256(self): def test_sdpa_full_head_dim_512_nax(self): if mx.default_device() != mx.gpu: self.skipTest("requires GPU") + if not mx.metal.is_nax_available(): + self.skipTest("D512 full attention requires NAX") D = 512 scale = D**-0.5 mx.random.seed(0) - q_probe = mx.random.normal(shape=(1, 2, 9, D)).astype(mx.bfloat16) - k_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16) - v_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16) - try: - mx.eval( - mx.fast.scaled_dot_product_attention( - q_probe, - k_probe, - v_probe, - scale=scale, - force_fused=True, - ) - ) - except ValueError as e: - if "plus head dim 512 on NAX GPUs" not in str(e): - raise - self.skipTest("D512 full attention requires NAX") - cases = [ # Multiple query tiles with GQA. (1, 8, 2, 257, 513, None, True), @@ -1764,6 +1748,63 @@ def loss_fast(q, k, v): test_grad(loss_slow, loss_fast, [q, k, v]) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_grad_large_scores(self): + # The fused backward rebuilds P = exp(scale * S - lse) from the scores + # S = Q @ K.T and the float32 lse of the forward. If S is rounded to + # half precision, large scores put the rounding error into the exponent + # (and float16 S overflows), and the gradients blow up. + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + mx.random.seed(0) + B, H, Hk, qL, kL, D = 2, 4, 2, 200, 232, 64 + scale = D**-0.5 + + def rel_err(x, expected): + x = x.astype(mx.float32) + return (mx.linalg.norm(x - expected) / mx.linalg.norm(expected)).item() + + for dtype, mask in product((mx.bfloat16, mx.float16), (None, "causal")): + q = 32 * mx.random.normal((B, H, qL, D)) + k = 32 * mx.random.normal((B, Hk, kL, D)) + # One key per kv head equal to a query, so the largest |q.k| is + # about 6.5e4: past the float16 max, while scale * q.k still fits. + k[:, :, 0] = q[:, :: H // Hk, -1] + v = mx.random.normal((B, Hk, kL, D)) + cotan = mx.random.normal((B, H, qL, D)) + q, k, v, cotan = (x.astype(dtype) for x in (q, k, v, cotan)) + + def fast(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + + def ref(q, k, v): + return mlx_ref_attn(q, k, v, scale=scale, mask=mask) + + # The fused backward, with small tiles so it runs several ragged + # tiles per axis. + with mx.config.scoped_update( + MLX_SDPA_VJP_FALLBACK=0, MLX_SDPA_VJP_BQ=64, MLX_SDPA_VJP_BK=48 + ): + _, grads = mx.vjp(fast, [q, k, v], [cotan]) + mx.eval(grads) + + # The same values in float32 + primals = [x.astype(mx.float32) for x in (q, k, v)] + _, expected = mx.vjp(ref, primals, [cotan.astype(mx.float32)]) + + # dq and dk carry the half precision rounding of dS and dP; dv only + # that of P. + if dtype == mx.bfloat16: + tols = (0.3, 0.3, 1e-2) + else: + tols = (5e-2, 5e-2, 2e-3) + for name, g, e, tol in zip(("dq", "dk", "dv"), grads, expected, tols): + with self.subTest(dtype=dtype, mask=mask, grad=name): + self.assertTrue(mx.all(mx.isfinite(g)).item()) + self.assertLess(rel_err(g, e), tol) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") def test_sdpa_force_fused_metal(self): if mx.default_device() != mx.gpu: @@ -2033,6 +2074,184 @@ def test_sdpa_window_large(self): out = mx.where(valid, out, 0) self.assertTrue(mx.allclose(ref, out, atol=1e-5, rtol=1e-5)) + @unittest.skipIf(not mx.cuda.is_available(), "CUDA kernel path only") + def test_sdpa_window_cuda(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + + # The cuDNN attention requires compute capability 8.0 or later. + has_cudnn = mx.device_info()["compute_capability_major"] >= 8 + D = 128 + scale = D**-0.5 + + def make_qkv(qL, kL, dtype=mx.float16): + q = mx.random.normal((1, 8, qL, D), dtype) + k = mx.random.normal((1, 2, kL, D), dtype) + v = mx.random.normal((1, 2, kL, D), dtype) + return q, k, v + + def ref_attn(q, k, v, mask, sinks=None): + # GPU float32 GEMM may use TF32; keep the reference exact. + with mx.stream(mx.cpu): + return mlx_ref_attn( + q.astype(mx.float32), + k.astype(mx.float32), + v.astype(mx.float32), + scale=scale, + mask=mask, + sinks=None if sinks is None else sinks.astype(mx.float32), + ) + + for qL, kL, window, causal, dtype in product( + (1, 3, 128, 256), + (256, 2048), + (1, 64, 1000), + (False, True), + (mx.float16, mx.bfloat16), + ): + # With a window, the vector kernel takes only one query. + if qL > 1 and not has_cudnn: + continue + with self.subTest(qL=qL, kL=kL, window=window, causal=causal, dtype=dtype): + q, k, v = make_qkv(qL, kL, dtype) + mask = make_window_mask(qL, kL, window) + if causal: + mask = mask & make_causal_mask(qL, kL) + ref = ref_attn(q, k, v, mask) + out = mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + window_size=window, + mask="causal" if causal else None, + force_fused=True, + ) + tol = 1e-3 if dtype == mx.float16 else 1e-2 + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + + # Decoding from a fixed-size cache, with a window shorter and longer + # than the keys. + for window in (64, 1000): + with self.subTest(cache_window=window): + q, k, v = make_qkv(1, 512) + k = k[..., :300, :] + v = v[..., :300, :] + ref = ref_attn(q, k, v, make_window_mask(1, 300, window)) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, window_size=window, force_fused=True + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) + + # The backward needs the cuDNN attention. + if not has_cudnn: + return + for kL, causal, sinks, dtype in product( + (128, 256), (False, True), (False, True), (mx.float16, mx.bfloat16) + ): + with self.subTest( + grad_kL=kL, grad_causal=causal, grad_sinks=sinks, grad_dtype=dtype + ): + q, k, v = make_qkv(128, kL, dtype) + s = mx.random.normal((8,), dtype) if sinks else None + cotan = mx.random.normal(q.shape, dtype) + mask = make_window_mask(128, kL, 32) + if causal: + mask = mask & make_causal_mask(128, kL) + + def sdpa_ref(q, k, v): + return ref_attn(q, k, v, mask, s) + + def sdpa_fused(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + window_size=32, + mask="causal" if causal else None, + sinks=s, + force_fused=True, + ) + + _, ref = mx.vjp(sdpa_ref, [q, k, v], [cotan]) + _, out = mx.vjp(sdpa_fused, [q, k, v], [cotan]) + tol = 1e-2 if dtype == mx.float16 else 5e-2 + for r, o in zip(ref, out): + self.assertTrue(mx.allclose(r, o, atol=tol, rtol=tol)) + + def test_sdpa_grad_sinks_and_nested(self): + D = 64 + scale = D**-0.5 + q = mx.random.normal((1, 4, 128, D), mx.float16) + k = mx.random.normal((1, 2, 128, D), mx.float16) + v = mx.random.normal((1, 2, 128, D), mx.float16) + sinks = mx.random.normal((4,), mx.float16) + + def ref_attn(q, k, v, sinks, window): + mask = make_causal_mask(128, 128) + if window > 0: + mask = mask & make_window_mask(128, 128, window) + if sinks is not None: + sinks = sinks.astype(mx.float32) + with mx.stream(mx.cpu): + return mlx_ref_attn( + q.astype(mx.float32), + k.astype(mx.float32), + v.astype(mx.float32), + scale=scale, + mask=mask, + sinks=sinks, + ) + + def fast_attn(q, k, v, sinks, window): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, window_size=window, mask="causal", sinks=sinks + ) + + for window in (-1, 32): + # Gradients of the sinks + with self.subTest(sinks_window=window): + cotan = mx.random.normal(q.shape, mx.float16) + _, ref = mx.vjp( + lambda *x: ref_attn(*x, window), [q, k, v, sinks], [cotan] + ) + _, out = mx.vjp( + lambda *x: fast_attn(*x, window), [q, k, v, sinks], [cotan] + ) + for r, o in zip(ref, out): + self.assertTrue(mx.allclose(r, o, atol=1e-2, rtol=1e-2)) + + # Gradients of gradients + with self.subTest(nested_window=window): + + def nested(attn): + def loss(q): + out = attn(q, k, v, None, window).astype(mx.float32) + return (out**2).sum() + + grad = mx.grad(loss) + return mx.grad(lambda q: grad(q).astype(mx.float32).sum())(q) + + ref = nested(ref_attn) + out = nested(fast_attn) + self.assertTrue(mx.allclose(ref, out, atol=5e-2, rtol=5e-2)) + + def test_sdpa_vector_broadcast_kv(self): + D = 64 + q = mx.random.normal((1, 8, 1, D), mx.float16) + k = mx.broadcast_to(mx.random.normal((1, 2, 1, D), mx.float16), (1, 2, 256, D)) + v = mx.broadcast_to(mx.random.normal((1, 2, 1, D), mx.float16), (1, 2, 256, D)) + mx.eval(q, k, v) + for window in (-1, 32): + with self.subTest(window=window): + mask = make_window_mask(1, 256, window) if window > 0 else None + ref = mlx_ref_attn(q, k, v, scale=D**-0.5, mask=mask) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=D**-0.5, window_size=window + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) + def test_sdpa_window_size_errors(self): q = mx.random.normal((1, 2, 4, 32)) for window in (0, -2): diff --git a/python/tests/test_nn.py b/python/tests/test_nn.py index 0519bcb4ad..2664ce2a54 100644 --- a/python/tests/test_nn.py +++ b/python/tests/test_nn.py @@ -1104,6 +1104,15 @@ def test_gelu(self): self.assertLess(mx.abs(y - y_hat1).max(), 0.0005) self.assertLess(mx.abs(y - y_hat2).max(), 0.025) + # The float16 gradient stays finite where x**3 overflows + x = mx.array([-60000.0, -150.0, -9.0, 0.5, 9.0, 150.0], dtype=mx.float16) + dx = mx.grad(lambda x: nn.gelu_approx(x).astype(mx.float32).sum())(x) + expected = mx.grad(lambda x: nn.gelu_approx(x).sum())(x.astype(mx.float32)) + self.assertTrue(mx.allclose(dx, expected, atol=1e-3)) + cotan = mx.full(x.shape, 4000.0, dtype=mx.float16) + _, (dx,) = mx.vjp(nn.gelu_approx, [x], [cotan]) + self.assertTrue(mx.allclose(dx, cotan * expected, rtol=1e-2)) + def test_sin_pe(self): m = nn.SinusoidalPositionalEncoding(16, min_freq=0.01) x = mx.arange(10) diff --git a/python/tests/test_ops.py b/python/tests/test_ops.py index 27a863df31..2b4f5f31b8 100644 --- a/python/tests/test_ops.py +++ b/python/tests/test_ops.py @@ -953,6 +953,15 @@ def test_argmin_argmax(self): b = getattr(np, op)(data) self.assertEqual(a.item(), b) + # A 0-d input keeps no axes + x = mx.array(3.0) + for op in ["argmin", "argmax"]: + for kd in [True, False]: + a = getattr(mx, op)(x, keepdims=kd) + b = getattr(np, op)(np.array(3.0), keepdims=kd) + self.assertEqual(a.shape, b.shape) + self.assertEqual(a.item(), b) + def test_broadcast(self): a_npy = np.reshape(np.arange(200), (10, 20)) a_mlx = mx.array(a_npy) @@ -2980,6 +2989,20 @@ def test_cummax_cummin_nan(self): msg=f"{op} reverse={reverse} inclusive={inclusive} " f"arr={arr}\ngot={got}\nexp={expected}", ) + for dtype in (mx.float16, mx.bfloat16): + got = getattr(mx, op)( + a_mx.astype(dtype), reverse=reverse, inclusive=inclusive + ) + self.assertEqual(got.dtype, dtype) + self.assertTrue( + np.array_equal( + np.array(got.astype(mx.float32)), + expected, + equal_nan=True, + ), + msg=f"{op} {dtype} reverse={reverse} " + f"inclusive={inclusive} arr={arr}", + ) def test_diff(self): a = mx.array([1, 2, 4, 7, 0]) @@ -4941,6 +4964,18 @@ def test_argsort_nan(self): sorted_x = mx.take(x, mx.argsort(x)) self.assertTrue(mx.array_equal(sorted_x, expected, equal_nan=True)) + def test_sort_bool(self): + np.random.seed(0) + # Small sizes use the single block sort, large sizes the multi-block sort + for size in [10, 5000, 50000]: + with self.subTest(size=size): + a_np = np.random.uniform(size=size) < 0.5 + a_mx = mx.array(a_np) + self.assertTrue(np.array_equal(mx.sort(a_mx), np.sort(a_np))) + self.assertEqual(mx.sort(a_mx).dtype, mx.bool_) + idx = mx.argsort(a_mx) + self.assertTrue(np.array_equal(mx.take(a_mx, idx), np.sort(a_np))) + def test_to_from_fp8(self): vals = mx.array( [448, 256, 192, 128, 96, 64, 48, 32, 24, 16, 12, 8, 6, 4, 3, 2, 0.015625] @@ -4978,6 +5013,39 @@ def test_to_from_fp8(self): ) ) + def test_to_from_fp8_float64(self): + # float64 is only supported on the CPU. + with mx.stream(mx.cpu): + vals = [448, 256, 192, 128, 96, 64, 48, 32, 24, 16, 12, 8, 6, 4, 3, 2] + vals += [0.015625, 0.001953125] + x64 = mx.array(vals, dtype=mx.float64) + x32 = mx.array(vals, dtype=mx.float32) + self.assertTrue(mx.array_equal(mx.to_fp8(x64), mx.to_fp8(x32))) + self.assertTrue(mx.array_equal(mx.to_fp8(-x64), mx.to_fp8(-x32))) + + codes = mx.array(list(range(256)), dtype=mx.uint8) + d64 = mx.from_fp8(codes, dtype=mx.float64) + d32 = mx.from_fp8(codes, dtype=mx.float32) + self.assertEqual(d64.dtype, mx.float64) + self.assertTrue(mx.array_equal(d64, d32.astype(mx.float64), equal_nan=True)) + + # 1.0625 is the midpoint between 1.0 (0x38) and 1.125 (0x39). + # Rounding to float32 first would move 1.0625 + eps onto the tie, + # which then rounds to even (0x38) instead of up. + eps = 2.0**-30 + x = mx.array( + [1.0625 - eps, 1.0625, 1.0625 + eps, -(1.0625 + eps)], + dtype=mx.float64, + ) + self.assertEqual(mx.to_fp8(x).tolist(), [0x38, 0x38, 0x39, 0xB9]) + + # Saturation and NaN behave as for the other float types. + special = mx.array( + [float("inf"), -float("inf"), 1e300, float("nan")], dtype=mx.float64 + ) + self.assertEqual(mx.to_fp8(special).tolist()[:3], [0x7E, 0xFE, 0x7E]) + self.assertIn(mx.to_fp8(special)[3].item(), [0x7F, 0xFF]) + def test_zeros_ones_empty_like_dtype(self): x = mx.array([1, 2, 3], dtype=mx.int32) diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 476c39fe57..2073dd3ced 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -131,6 +131,26 @@ def test_mxfp4_quantize_dequantize(self): w_hat = mx.dequantize(w_q, scales, mode="mxfp4") self.assertTrue(mx.all(w_hat == 0)) + def test_fp4_quantize_ties_to_even(self): + ties = mx.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0]) + expected = mx.array([0.0, 1.0, 1.0, 2.0, 2.0, 4.0, 4.0]) + w = mx.zeros((3, 32)) + w[0, :7] = ties + w[1, :7] = -ties + w[:2, 7] = 6.0 + # A NaN should not change the group scale + w[0, 8] = float("nan") + for mode in ["mxfp4", "nvfp4"]: + w_q, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(w_q, scales, mode=mode) + self.assertTrue(mx.array_equal(w_hat[0, :7], expected)) + self.assertTrue(mx.array_equal(w_hat[1, :7], -expected)) + self.assertEqual(w_q[0, 1].item(), 7) + # FIXME: The zero group checks fail in the CUDA backend. + if not mx.cuda.is_available(): + self.assertTrue(mx.all(w_q[:, 2:] == 0)) + self.assertTrue(mx.all(scales[2] == 0)) + def test_mxfp8_quantize_dequantize(self): w = 2 * mx.random.uniform(shape=(512, 32)) - 1 w = w.astype(mx.bfloat16) @@ -393,11 +413,30 @@ def test_qqmv(self): self.assertEqual(y_q.shape, y_hat.shape) self.assertLess((y_q - y_hat).abs().max(), 1e-3) - def test_qqmm(self): - if mx.default_device() == mx.cpu: - self.skipTest("Not implemented for CPU") - return + def test_qqmm_nvfp4_global_scale_float16_cpu(self): + with mx.stream(mx.cpu): + x = mx.full((1, 128), 1024, dtype=mx.float16) + global_scale_x = mx.max(mx.abs(x)).astype(mx.float32) + for sign in (1, -1): + with self.subTest(sign=sign): + # Encode in float32 to isolate the half-precision matmul. + w = mx.full((1, 128), sign * 2**-23, dtype=mx.float32) + global_scale_w = mx.max(mx.abs(w)).astype(mx.float32) + w_q, scales = mx.quantize( + w, mode="nvfp4", global_scale=global_scale_w + ) + result = mx.qqmm( + x, + w_q, + scales, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + self.assertEqual(result.dtype, mx.float16) + self.assertEqual(result.item(), sign * 0.015625) + def test_qqmm(self): tol = 5e-2 if mx.cuda.is_available() else 1e-3 key = mx.random.key(0) k1, k2 = mx.random.split(key) @@ -443,9 +482,29 @@ def test_qqmm(self): self.assertEqual(y_q.shape, y_hat.shape) self.assertLess((y_q - y_hat).abs().max(), tol) - @unittest.skipIf( - not mx.metal.is_available(), "Global scale is only supported on Metal backend" - ) + def test_qqmm_unquantized_w(self): + if mx.default_device() == mx.cpu: + self.skipTest("Not implemented for CPU") + + key = mx.random.key(0) + k1, k2, k3 = mx.random.split(key, 3) + x = mx.random.normal((33, 512), key=k1) + ws = [ + ("contiguous", mx.random.normal((256, 512), key=k2)), + ("transposed", mx.random.normal((512, 256), key=k3).T), + ] + for mode in ["mxfp8", "nvfp4"]: + for layout, w in ws: + with self.subTest(mode=mode, layout=layout): + gx = mx.max(mx.abs(x)) if mode == "nvfp4" else None + gw = mx.max(mx.abs(w)) if mode == "nvfp4" else None + y = mx.qqmm(x, w, mode=mode, global_scale_x=gx, global_scale_w=gw) + w_q, scales = mx.quantize(w, mode=mode, global_scale=gw) + y_q = mx.qqmm( + x, w_q, scales, mode=mode, global_scale_x=gx, global_scale_w=gw + ) + self.assertTrue(mx.array_equal(y, y_q)) + def test_qqmm_global_scale_matrix_kernels(self): mx.random.seed(0) dtype = mx.bfloat16 @@ -487,13 +546,10 @@ def test_qqmm_global_scale_matrix_kernels(self): relative_error = delta.max() / mx.maximum( mx.abs(expected.astype(mx.float32)).max(), 1e-20 ) - self.assertLess(relative_error, 3e-2) + tol = 3e-2 if mx.default_device() != mx.cpu else 1e-1 + self.assertLess(relative_error, tol) def test_qqmm_matrix_kernels(self): - if mx.default_device() == mx.cpu: - self.skipTest("Not implemented for CPU") - return - mx.random.seed(0) dtype = mx.bfloat16 for M, N, K, mode in product( @@ -515,7 +571,16 @@ def test_qqmm_matrix_kernels(self): actual = mx.qqmm(x, w_q, scales, mode=mode) delta = mx.abs(actual.astype(mx.float32) - expected) relative_error = delta.max() / mx.abs(expected).max() - self.assertLess(relative_error, 3e-2) + tol = 3e-2 if mx.default_device() == mx.gpu else 4e-2 + self.assertLess(relative_error, tol) + + def test_qqmm_unsupported_mode(self): + x = mx.zeros((32, 128)) + w = mx.zeros((64, 128)) + with self.assertRaises(ValueError): + mx.qqmm(x, w, mode="affine") + with self.assertRaises(ValueError): + mx.gather_qqmm(x, w, mode="affine") def test_qmm(self): key = mx.random.key(0) @@ -926,9 +991,10 @@ def rel_err(got, expected): [ (4224, 4128), (512, 4096), # smallest K: one K step per simdgroup + (1024, 1024), # smallest N * K on gen 15+ ], [3, 8, 9], - [4, 8], + [2, 3, 4, 5, 6, 8], [32, 64, 128], [mx.bfloat16, mx.float16, mx.float32], ): @@ -1126,6 +1192,41 @@ def test_qmm_accumulation_precision(self): ) self.assertTrue(mx.array_equal(y, y_ref.astype(dtype)).item()) + def test_fp_qmm_accumulation_precision(self): + # Same construction as test_qmm_accumulation_precision for the + # floating point modes. Every weight is exact after quantization and + # every partial sum is exact in float32. + N, K = 128, 256 + for dtype, transpose, mode in product( + [mx.bfloat16, mx.float16], + [True, False], + ["mxfp4", "nvfp4", "mxfp8"], + ): + with self.subTest(dtype=dtype, transpose=transpose, mode=mode): + eps = 1 / 256 if dtype == mx.bfloat16 else 1 / 2048 + x = mx.tile(mx.array([1, eps, -1, 0], dtype), K // 4) + x = mx.stack([x, -x]) + if transpose: + v = mx.arange(N)[:, None] + 3 * (mx.arange(K)[None] // 4) + else: + v = mx.arange(K)[:, None] // 4 + 3 * mx.arange(N)[None] + w = (v % 4 + 1).astype(dtype) + q, scales = mx.quantize(w, mode=mode) + w = mx.dequantize(q, scales, mode=mode, dtype=mx.float32) + y_ref = x.astype(mx.float32) @ (w.T if transpose else w) + y_ref = y_ref.astype(dtype) + y = mx.quantized_matmul(x, q, scales, transpose=transpose, mode=mode) + self.assertTrue(mx.array_equal(y, y_ref).item()) + y = mx.gather_qmm( + x, + q[None], + scales[None], + rhs_indices=mx.array([0], mx.uint32), + transpose=transpose, + mode=mode, + ) + self.assertTrue(mx.array_equal(y, y_ref[None]).item()) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_qmv_fast_unaligned_n(self): # Output sizes that are not a multiple of 8 with an aligned input size. @@ -1196,6 +1297,9 @@ def test_fp_qmv_fast_unaligned_n(self): @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_fp_qmv_fast_unaligned_n_global_scale(self): + if mx.default_device() == mx.cpu: + self.skipTest("Not implemented for CPU") + for n, k, m, dtype in product( [1, 3, 5, 7, 8, 9, 12, 17], [512, 544, 1024], @@ -2808,10 +2912,10 @@ def gmm(s, x, wq): _ds = mx.grad(gmm)(s, x, wq) - @unittest.skipIf( - not mx.is_available(mx.gpu), "Global scale is only supported on the GPU" - ) def test_gather_qmm_global_scale(self): + if mx.default_device() == mx.cpu: + self.skipTest("Not implemented for CPU") + mx.random.seed(0) N, K = 128, 256 diff --git a/python/tests/test_reduce.py b/python/tests/test_reduce.py index 2926f76a0f..a1446a2549 100644 --- a/python/tests/test_reduce.py +++ b/python/tests/test_reduce.py @@ -1,6 +1,7 @@ # Copyright © 2023 Apple Inc. import math +import os import unittest from itertools import combinations, permutations @@ -217,6 +218,10 @@ def test_zero_size(self): mx.eval(out) self.assertEqual(out.shape, (0,)) + # An empty array with large dimensions + a = mx.zeros((1, 2**16, 2**16, 0)) + self.assertEqual(mx.sum(a, axis=(1, 2, 3)).item(), 0) + def test_sum_bool(self): x = np.random.uniform(0, 1, size=(10, 10, 10)) > 0.5 y = mx.array(x) @@ -385,6 +390,11 @@ def test_large_offsets(self): self.assertTrue(x.any().item()) self.assertFalse(x.all().item()) + # Reducing two axes that together hold 2**31 + 2**16 elements + if not (mx.cuda.is_available() and "CI" in os.environ): + self.assertEqual(x[None].max(axis=(1, 2)).item(), 250) + self.assertEqual(x.T[None].max(axis=(1, 2)).item(), 250) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_init_reduce_large_output(self): out = mx.all(mx.zeros((0, 4, 2**30), dtype=mx.bool_), axis=0) @@ -406,6 +416,47 @@ def test_minmax(self): self.assertEqual(actual.shape, expected.shape) self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf( + mx.metal.is_available(), + "Metal accumulates half precision row reductions in half precision", + ) + def test_half_precision_row_reduce(self): + # Sums and products of many values into few outputs, like the gradient + # of a per channel scale. A half precision accumulator loses precision + # on long reductions. + dtypes = [(mx.bfloat16, 5e-3)] + if mx.default_device() == mx.gpu: + # The CPU accumulates float16 in float16 + dtypes.append((mx.float16, 2e-3)) + + # Small values so that the float16 sums do not overflow + for shape, axes in [ + ((2, 1 << 22), (1,)), + ((1, 4096, 8, 1024), (0, 1, 3)), + ((2, 512, 4, 256), (0, 1, 3)), + ((64, 8, 4096), (0, 2)), + ((65, 3, 17), (0, 2)), + ((8, 300, 6), (0, 2)), + ]: + for dtype, rtol in dtypes: + with self.subTest(op="sum", shape=shape, axes=axes, dtype=dtype): + x = (mx.random.normal(shape) * 0.01 + 0.005).astype(dtype) + x_np = np.array(x.astype(mx.float32)) + expected = x_np.sum(axis=axes, dtype=np.float64) + out = np.array(x.sum(axis=axes).astype(mx.float32)) + self.assertTrue(np.allclose(out, expected, rtol=rtol)) + + # 1 + 2**-7 times 1 - 2**-7 is 1 - 2**-14, which rounds to 1 in half + # precision. Each output is the product of 1 << 16 such pairs. + expected = (1 - 2**-14) ** (1 << 16) + for shape, axes in [((2, 1 << 17), (1,)), ((64, 4, 2048), (0, 2))]: + reps = (*shape[:-1], shape[-1] // 2) + for dtype, rtol in dtypes: + with self.subTest(op="prod", shape=shape, axes=axes, dtype=dtype): + x = mx.tile(mx.array([1 + 2**-7, 1 - 2**-7], dtype), reps) + out = np.array(x.prod(axis=axes).astype(mx.float32)) + self.assertTrue(np.allclose(out, expected, rtol=rtol)) + if __name__ == "__main__": mlx_tests.MLXTestRunner(failfast=True) diff --git a/python/tests/test_threads.py b/python/tests/test_threads.py index 3d2aa65191..aae9135e86 100644 --- a/python/tests/test_threads.py +++ b/python/tests/test_threads.py @@ -106,6 +106,26 @@ def vmap_worker(): t.join() self.assertEqual(errors, []) + def test_default_random_key_per_thread(self): + # Threads that do not call seed() must not get the same numbers. + n_threads = 4 + results = [None] * n_threads + + def draw(i): + results[i] = mx.random.uniform(shape=(8,)).tolist() + + threads = [threading.Thread(target=draw, args=(i,)) for i in range(n_threads)] + for t in threads: + t.start() + for t in threads: + t.join() + + main_result = mx.random.uniform(shape=(8,)).tolist() + all_results = results + [main_result] + for i in range(len(all_results)): + for j in range(i + 1, len(all_results)): + self.assertNotEqual(all_results[i], all_results[j]) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_vmap.py b/python/tests/test_vmap.py index be4c1a242b..ed6b362dd3 100644 --- a/python/tests/test_vmap.py +++ b/python/tests/test_vmap.py @@ -447,6 +447,29 @@ def static(s, u): expected = mx.stack([static(src[i], u[i]) for i in range(3)]) self.assertTrue(mx.array_equal(out, expected)) + def test_vmap_divmod(self): + x = mx.array([[5.5, -3.25, 7.0], [-7.5, 0.5, 2.0]]) + y = mx.array([[2.0, 1.5, -2.5], [-2.0, 4.0, 3.0]]) + + out = mx.vmap(mx.divmod)(x, y) + self.assertEqual(len(out), 2) + for i in range(2): + self.assertEqual(out[i].shape, (2, 3)) + self.assertTrue(mx.array_equal(out[i], mx.divmod(x, y)[i])) + + out = mx.vmap(mx.divmod, in_axes=(1, None))(x, y[:, 0]) + expected = mx.divmod(x.T, y[:, 0]) + for o, e in zip(out, expected): + self.assertTrue(mx.array_equal(o, e)) + + out = mx.vmap(mx.divmod, in_axes=(None, 1), out_axes=[1, 0])(x[:, 0], y) + expected = mx.divmod(x[:, 0], y.T) + self.assertTrue(mx.array_equal(out[0], expected[0].T)) + self.assertTrue(mx.array_equal(out[1], expected[1])) + + out = mx.vmap(lambda a, b: mx.divmod(a, b)[1])(x, y) + self.assertTrue(mx.array_equal(out, mx.remainder(x, y))) + def test_vmap_svd(self): a = mx.random.uniform(shape=(3, 4, 2)) diff --git a/python/tests/xp-tests/xfail.txt b/python/tests/xp-tests/xfail.txt index 2e55d1c442..cdac9e29d3 100644 --- a/python/tests/xp-tests/xfail.txt +++ b/python/tests/xp-tests/xfail.txt @@ -206,10 +206,6 @@ array_api_tests/test_operators_and_elementwise_functions.py::test_binary_with_sc ### Missing argument `device` array_api_tests/test_inspection_functions.py::test_array_namespace_info_dtypes -## Other failures -### Missing attribute '__array_api_version__' -array_api_tests/test_inspection_functions.py::TestInspection::test_capabilities - # test_statistical_functions.py ## Missing arguments ### Missing argument `correction` @@ -242,26 +238,6 @@ array_api_tests/test_manipulation_functions.py::test_moveaxis array_api_tests/test_data_type_functions.py::test_astype ### array_api_tests/test_data_type_functions.py::test_can_cast -### -array_api_tests/test_data_type_functions.py::test_finfo[dtype0] -### -array_api_tests/test_data_type_functions.py::test_finfo[dtype1] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype0] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype1] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype2] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype3] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype4] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype5] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype6] -### Missing attribute `bits` -array_api_tests/test_data_type_functions.py::test_iinfo[dtype7] ## Other failures ### MLX result_type() does not accept Python scalar values alongside dtypes diff --git a/tests/allocator_tests.cpp b/tests/allocator_tests.cpp index 1fff8d8cc9..e11f2ab62d 100644 --- a/tests/allocator_tests.cpp +++ b/tests/allocator_tests.cpp @@ -1,7 +1,10 @@ // Copyright © 2023-2026 Apple Inc. +#include +#include #include #include +#include #include #include #include @@ -42,6 +45,68 @@ TEST_CASE("test simple allocations") { } } +TEST_CASE("test size of a zero-sized allocation") { + auto buffer = allocator::allocator().malloc(0); + CHECK_EQ(allocator::allocator().size(buffer), 0); + allocator::allocator().free(buffer); + + auto x = zeros({0}); + auto y = remainder(x, array(2.0f)); + eval(y); + CHECK_EQ(y.size(), 0); +} + +TEST_CASE("test peak memory is the largest active memory") { + clear_cache(); + reset_peak_memory(); + size_t size = 1 << 20; + size_t active_with_buffer = 0; + for (int i = 0; i < 10; ++i) { + auto buffer = allocator::allocator().malloc(size); + active_with_buffer = std::max(active_with_buffer, get_active_memory()); + allocator::allocator().free(buffer); + } + CHECK_GE(get_peak_memory(), active_with_buffer); + CHECK_GE(get_peak_memory(), size); + CHECK_LT(get_peak_memory(), 5 * size); + clear_cache(); +} + +TEST_CASE("test memory stats are readable while another thread allocates") { + std::atomic done{false}; + std::thread allocating([&done] { + for (int i = 0; i < 1000; ++i) { + auto buffer = allocator::allocator().malloc(4096); + allocator::allocator().free(buffer); + } + done = true; + }); + bool peak_never_decreased = true; + auto last_peak = get_peak_memory(); + do { + get_active_memory(); + get_cache_memory(); + get_memory_limit(); + allocator::over_memory_limit(); + auto peak = get_peak_memory(); + peak_never_decreased = peak_never_decreased && peak >= last_peak; + last_peak = peak; + } while (!done); + allocating.join(); + CHECK(peak_never_decreased); + CHECK_GE(get_peak_memory(), 4096); +} + +TEST_CASE("test over memory limit follows the memory limit") { + auto buffer = allocator::allocator().malloc(1 << 20); + auto old_limit = set_memory_limit(1); + CHECK(allocator::over_memory_limit()); + set_memory_limit(std::numeric_limits::max()); + CHECK_FALSE(allocator::over_memory_limit()); + set_memory_limit(old_limit); + allocator::allocator().free(buffer); +} + TEST_CASE("test large allocations") { size_t size = 1 << 30; for (int i = 0; i < 100; ++i) { diff --git a/tests/array_tests.cpp b/tests/array_tests.cpp index f126ce3276..cb25bbdac5 100644 --- a/tests/array_tests.cpp +++ b/tests/array_tests.cpp @@ -1,8 +1,12 @@ // Copyright © 2023 Apple Inc. +#include #include +#include #include #include +#include #include +#include #include #include "doctest/doctest.h" @@ -627,11 +631,11 @@ TEST_CASE("test make array from user buffer") { int size = 4096; std::vector buffer(size, 0); - int count = 0; - auto deleter = [&count, data = buffer.data()](void* ptr) { + auto count = std::make_shared>(0); + auto deleter = [count, data = buffer.data()](void* ptr) { // make sure pointer is correct if (ptr == data) { - count++; + ++*count; } }; @@ -645,8 +649,11 @@ TEST_CASE("test make array from user buffer") { auto expected = ones({4096}); CHECK(array_equal(b, expected).item()); } - // deleter should always get called - CHECK_EQ(count, 1); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (*count == 0 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + CHECK_EQ(*count, 1); } TEST_CASE("test user buffer is not donated") { diff --git a/tests/blas_tests.cpp b/tests/blas_tests.cpp index 37653ba040..00078ec646 100644 --- a/tests/blas_tests.cpp +++ b/tests/blas_tests.cpp @@ -108,3 +108,42 @@ 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 segmented_mm float16 and bfloat16") { + auto a_f32 = reshape(arange(0, 4 * 12, float32), {4, 12}) * 0.1f; + auto b_f32 = reshape(arange(0, 12 * 6, float32), {12, 6}) * 0.1f; + auto segments = array({0u, 3u, 3u, 8u, 8u, 12u}, {3, 2}, uint32); + + for (auto dt : {float16, bfloat16}) { + auto a = astype(a_f32, dt); + auto b = astype(b_f32, dt); + auto a_ref = astype(a, float32); + auto b_ref = astype(b, float32); + + // Non-transposed + auto expected = astype(segmented_mm(a_ref, b_ref, segments), float32); + auto actual = astype(segmented_mm(a, b, segments), float32); + CHECK(allclose(actual, expected, 1e-2, 1e-2).item()); + + // Transposed a + auto a_t = transpose( + astype(reshape(arange(0, 12 * 4, float32), {12, 4}) * 0.1f, dt)); + auto a_t_ref = astype(a_t, float32); + expected = astype(segmented_mm(a_t_ref, b_ref, segments), float32); + actual = astype(segmented_mm(a_t, b, segments), float32); + CHECK(allclose(actual, expected, 1e-2, 1e-2).item()); + + // Transposed b + auto b_t = transpose( + astype(reshape(arange(0, 6 * 12, float32), {6, 12}) * 0.1f, dt)); + auto b_t_ref = astype(b_t, float32); + expected = astype(segmented_mm(a_ref, b_t_ref, segments), float32); + actual = astype(segmented_mm(a, b_t, segments), float32); + CHECK(allclose(actual, expected, 1e-2, 1e-2).item()); + + // Both transposed + expected = astype(segmented_mm(a_t_ref, b_t_ref, segments), float32); + actual = astype(segmented_mm(a_t, b_t, segments), float32); + CHECK(allclose(actual, expected, 1e-2, 1e-2).item()); + } +} diff --git a/tests/load_tests.cpp b/tests/load_tests.cpp index 4ba5084b80..634a175afc 100644 --- a/tests/load_tests.cpp +++ b/tests/load_tests.cpp @@ -480,6 +480,41 @@ TEST_CASE("test gguf metadata value validation") { } } +TEST_CASE("test gguf metadata at unaligned offsets") { + std::string file_path = get_temp_file("test_unaligned_metadata.gguf"); + std::unordered_map weights = {{"w", array({1.0f, 2.0f})}}; + std::unordered_map metadata = { + {"a", std::string("xyz")}, + {"bcd", std::vector{"e", "fgh", "ij"}}, + {"efghi", array(7)}, + {"jkl", array({1, -2, 3})}, + {"m", array({1.5f, -2.5f})}, + {"nopqr", astype(array({1, 2, 3}), uint64)}, + {"stu", astype(array({-4, 5}), int16)}, + {"v", astype(array({6, 7, 8}), uint8)}, + {"wxyzw", array({true, false, true})}}; + save_gguf(file_path, weights, metadata); + + auto [loaded_weights, loaded_metadata] = load_gguf(file_path); + CHECK_EQ(loaded_metadata.size(), metadata.size()); + CHECK_EQ(std::get(loaded_metadata.at("a")), "xyz"); + const std::vector expected_bcd = {"e", "fgh", "ij"}; + const auto& bcd = + std::get>(loaded_metadata.at("bcd")); + REQUIRE_EQ(bcd.size(), expected_bcd.size()); + for (size_t i = 0; i < bcd.size(); ++i) { + CHECK_EQ(bcd[i], expected_bcd[i]); + } + CHECK_EQ(std::get(loaded_metadata.at("efghi")).item(), 7); + for (auto key : {"jkl", "m", "nopqr", "stu", "v", "wxyzw"}) { + CAPTURE(key); + const auto& expected = std::get(metadata.at(key)); + const auto& loaded = std::get(loaded_metadata.at(key)); + CHECK_EQ(loaded.dtype(), expected.dtype()); + CHECK(array_equal(loaded, expected).item()); + } +} + TEST_CASE("test gguf metadata") { std::string file_path = get_temp_file("test_arr.gguf"); using dict = std::unordered_map; diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 60e11f6cf9..db512943b5 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -137,6 +137,21 @@ TEST_CASE("test reshape") { eval(y); CHECK(!y.flags().row_contiguous); CHECK(y.flags().col_contiguous); + + // Dense data with no contiguity flags becomes contiguous after reshape + x = arange(32, float32); + eval(x); + auto dense = array({1, 1, 20}, float32, nullptr, {}); + dense.copy_shared_buffer(x, {32, 32, 1}, {false, false, false}, 32); + dense.set_status(array::Status::available); + y = reshape(dense, {4, 5}); + eval(y); + CHECK(y.flags().contiguous); + CHECK(y.flags().row_contiguous); + CHECK_EQ(y.data_size(), 20); + CHECK( + array_equal(transpose(y), transpose(reshape(arange(20, float32), {4, 5}))) + .item()); } TEST_CASE("test flatten") { @@ -1453,6 +1468,32 @@ TEST_CASE("test irregular binary ops") { } } +TEST_CASE("test exp of inf, nan and large values on cpu") { + auto inf = std::numeric_limits::infinity(); + auto nan = std::numeric_limits::quiet_NaN(); + for (auto dt : {float32, float16, bfloat16}) { + auto x = array({-inf, -60000.0f, 0.0f, 1.0f, 60000.0f, inf, nan}, {7}); + auto y = astype(exp(astype(x, dt), Device::cpu), float32); + eval(y); + auto* p = y.data(); + CHECK_EQ(p[0], 0.0f); + CHECK_EQ(p[1], 0.0f); + CHECK_EQ(p[2], 1.0f); + CHECK_LT(std::abs(p[3] / std::exp(1.0f) - 1.0f), 1e-2f); + CHECK_EQ(p[4], inf); + CHECK_EQ(p[5], inf); + CHECK(std::isnan(p[6])); + } + auto x = array({-1e30f, -88.0f, 88.0f, 1e30f}, {4}); + auto y = exp(x, Device::cpu); + eval(y); + auto* p = y.data(); + CHECK_EQ(p[0], 0.0f); + CHECK_LE(p[1], 1e-37f); + CHECK_LT(std::abs(p[2] / std::exp(88.0f) - 1.0f), 1e-4f); + CHECK_EQ(p[3], inf); +} + TEST_CASE("test arithmetic unary ops") { // Test negative { @@ -4463,6 +4504,36 @@ TEST_CASE("test conv2d") { } } +TEST_CASE("test conv empty batch weight gradients") { + SUBCASE("conv1d") { + for (int groups : {1, 2}) { + auto in = zeros({0, 5, 2}); + auto wt = ones({4, 3, 2 / groups}); + auto conv_w = [&](const std::vector& primals) { + return std::vector{conv1d(in, primals[0], 1, 0, 1, groups)}; + }; + auto cotan = ones_like(conv_w({wt})[0]); + auto grad = vjp(conv_w, {wt}, {cotan}).second[0]; + CHECK_EQ(grad.shape(), wt.shape()); + CHECK_EQ(grad.dtype(), wt.dtype()); + CHECK(array_equal(grad, zeros_like(wt)).item()); + } + } + + SUBCASE("conv2d") { + auto in = zeros({0, 5, 5, 2}, float16); + auto wt = ones({4, 3, 3, 2}, float16); + auto conv_w = [&](const std::vector& primals) { + return std::vector{conv2d(in, primals[0])}; + }; + auto cotan = ones_like(conv_w({wt})[0]); + auto grad = vjp(conv_w, {wt}, {cotan}).second[0]; + CHECK_EQ(grad.shape(), wt.shape()); + CHECK_EQ(grad.dtype(), wt.dtype()); + CHECK(array_equal(grad, zeros_like(wt)).item()); + } +} + TEST_CASE("test trace") { auto in = eye(3); auto out = trace(in).item(); @@ -4490,6 +4561,19 @@ TEST_CASE("test view") { in = array({1, 2, 3, 4}, int64); auto out = view(in, int32); CHECK(array_equal(out, array({1, 0, 2, 0, 3, 0, 4, 0})).item()); + + // Dense data with no contiguity flags becomes contiguous after a view + auto x = arange(8, int64); + eval(x); + in = array({2, 4}, int64, nullptr, {}); + in.copy_shared_buffer(x, {4, 1}, {false, false, false}, 8); + in.set_status(array::Status::available); + out = view(in, int32); + eval(out); + CHECK(out.flags().contiguous); + CHECK(out.flags().row_contiguous); + CHECK(array_equal(transpose(out), transpose(view(reshape(x, {2, 4}), int32))) + .item()); } TEST_CASE("test roll") { @@ -4808,6 +4892,28 @@ TEST_CASE("test fp8 conversion") { CHECK(array_equal(out, expected, true).item()); } +TEST_CASE("test fp8 to float64 all encodings on cpu") { + auto codes = arange(0, 256, uint8, Device::cpu); + auto result = from_fp8(codes, float64, Device::cpu); + result.eval(); + auto values = result.data(); + for (int code = 0; code < 256; ++code) { + CAPTURE(code); + int exponent = (code >> 3) & 15; + int mantissa = code & 7; + if (exponent == 15 && mantissa == 7) { + CHECK(std::isnan(values[code])); + continue; + } + double magnitude = exponent == 0 + ? std::ldexp(static_cast(mantissa), -9) + : std::ldexp(1.0 + mantissa / 8.0, exponent - 7); + CHECK_EQ(values[code], (code & 128) ? -magnitude : magnitude); + } + CHECK_FALSE(std::signbit(values[0])); + CHECK(std::signbit(values[128])); +} + TEST_CASE("test max min with nan") { // Test maximum and minimum with NaN values auto x = array({0.0f, 1.0f, NAN, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}); diff --git a/tests/random_tests.cpp b/tests/random_tests.cpp index 9dfe98a5d8..7db86e78c8 100644 --- a/tests/random_tests.cpp +++ b/tests/random_tests.cpp @@ -1,6 +1,7 @@ // Copyright © 2023 Apple Inc. #include +#include #include "doctest/doctest.h" @@ -36,6 +37,27 @@ TEST_CASE("test global rng") { CHECK_EQ(y.item(), b.item()); } +TEST_CASE("test default key per thread") { + // Threads that do not call seed() must not get the same bits. + constexpr int n_threads = 4; + std::vector results(n_threads); + std::vector threads; + for (int i = 0; i < n_threads; ++i) { + threads.emplace_back([&results, i]() { + results[i] = + random::bits({}, 4, std::nullopt, Device::cpu).item(); + }); + } + for (auto& t : threads) { + t.join(); + } + for (int i = 0; i < n_threads; ++i) { + for (int j = i + 1; j < n_threads; ++j) { + CHECK_NE(results[i], results[j]); + } + } +} + TEST_CASE("test random split") { auto [key, subkey] = random::split(random::key(0)); CHECK(array_equal(key, array({4146024105u, 967050713u})).item()); @@ -53,6 +75,22 @@ TEST_CASE("test random split") { CHECK(array_equal(keys, expected).item()); } +TEST_CASE("test random bits with keys at unaligned offsets") { + auto keys = random::split(random::key(0), 4); + for (int width : {1, 2}) { + CAPTURE(width); + auto fn = [width](array k) { + return random::bits({3}, width, k, Device::cpu); + }; + auto out = vmap(fn)(keys); + for (int i = 0; i < keys.shape(0); ++i) { + CAPTURE(i); + auto expected = random::bits({3}, width, take(keys, i, 0), Device::cpu); + CHECK(array_equal(take(out, i, 0), expected).item()); + } + } +} + TEST_CASE("test random bits") { // Test shapes, types, and sizes { diff --git a/tests/residency_tests.cpp b/tests/residency_tests.cpp index 0edac9b6dc..78cd304373 100644 --- a/tests/residency_tests.cpp +++ b/tests/residency_tests.cpp @@ -1,5 +1,9 @@ // Copyright © 2026 Apple Inc. +#include +#include +#include +#include #include #include "doctest/doctest.h" @@ -294,3 +298,39 @@ TEST_CASE("test the wired limit is used up to its boundary") { allocator::allocator().free(second); CHECK_EQ(residency().wired_size(), baseline); } + +TEST_CASE("test a user buffer is not wired") { + if (!residency().enabled()) { + return; + } + LimitGuard guard(0, 0); + set_wired_limit(256 * MB); + const size_t baseline = residency().wired_size(); + + // Page-aligned, so Metal can wrap it without a copy. + const size_t page = static_cast(getpagesize()); + constexpr int size = 4 * MB / sizeof(float); + std::unique_ptr data( + static_cast(std::aligned_alloc(page, size * sizeof(float))), + &std::free); + REQUIRE(data != nullptr); + std::fill_n(data.get(), size, 1.0f); + { + auto a = array(data.get(), Shape{size}, float32, [](void*) {}); + REQUIRE_EQ(a.data(), data.get()); + CHECK_EQ(residency().wired_size(), baseline); + + // Raising the limit wires MLX's own allocations, but not this buffer. + auto own = allocator::allocator().malloc(4 * MB); + set_wired_limit(512 * MB); + CHECK_EQ(residency().wired_size(), baseline + 4 * MB); + + auto b = sum(a); + eval(b); + CHECK_EQ(b.item(), static_cast(size)); + synchronize(); + allocator::allocator().free(own); + } + // Releasing the buffer must not touch the residency accounting. + CHECK_EQ(residency().wired_size(), baseline); +} diff --git a/tests/scheduler_tests.cpp b/tests/scheduler_tests.cpp index 2cc9325a0c..72de6df20b 100644 --- a/tests/scheduler_tests.cpp +++ b/tests/scheduler_tests.cpp @@ -2,6 +2,10 @@ #include "doctest/doctest.h" +#include +#include +#include + #include "mlx/mlx.h" #include "mlx/scheduler.h" @@ -326,6 +330,42 @@ TEST_CASE("test scheduler races") { eval(a, y); } +TEST_CASE("test eval reads the task count while cpu tasks complete") { + auto s = new_stream(Device::cpu); + auto y = zeros({100}, s); + for (int i = 0; i < 1000; ++i) { + y = exp(y, s); + } + eval(y); + CHECK_EQ(y.size(), 100); +} + +TEST_CASE("test wait for capacity blocks until a task completes") { + auto s = default_stream(default_device()); + synchronize(s); + for (int i = 0; i < 11; ++i) { + scheduler::notify_new_task(s); + } + std::atomic returned{false}; + std::thread waiter([&returned] { + scheduler::wait_for_capacity({}); + returned = true; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + CHECK_FALSE(returned); + scheduler::notify_task_completion(s); + waiter.join(); + CHECK(returned); + for (int i = 0; i < 10; ++i) { + scheduler::notify_task_completion(s); + } +} + +TEST_CASE("test wait for capacity returns when under the limit") { + synchronize(default_stream(default_device())); + scheduler::wait_for_capacity({}); +} + // The fence orders work between two streams. Check that the consumer sees the // producer result for every combination of producer and consumer device. TEST_CASE("test cross stream fence ordering") {