Onyxl commited on
Commit
5f25447
·
verified ·
1 Parent(s): 42a8887

Upload 914 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. mlx-main/mlx-main/.clang-format +87 -0
  2. mlx-main/mlx-main/.github/ISSUE_TEMPLATE/bug_report.md +28 -0
  3. mlx-main/mlx-main/.github/actions/build-cuda-release/action.yml +31 -0
  4. mlx-main/mlx-main/.github/actions/build-docs/action.yml +38 -0
  5. mlx-main/mlx-main/.github/actions/build-linux-release/action.yml +42 -0
  6. mlx-main/mlx-main/.github/actions/build-linux/action.yml +38 -0
  7. mlx-main/mlx-main/.github/actions/build-macos-release/action.yml +36 -0
  8. mlx-main/mlx-main/.github/actions/build-macos/action.yml +82 -0
  9. mlx-main/mlx-main/.github/actions/build-windows/action.yml +26 -0
  10. mlx-main/mlx-main/.github/actions/setup-linux/action.yml +99 -0
  11. mlx-main/mlx-main/.github/actions/setup-macos/action.yml +24 -0
  12. mlx-main/mlx-main/.github/actions/setup-windows/action.yml +42 -0
  13. mlx-main/mlx-main/.github/actions/test-linux/action.yml +69 -0
  14. mlx-main/mlx-main/.github/actions/test-windows/action.yml +21 -0
  15. mlx-main/mlx-main/.github/dependabot.yml +6 -0
  16. mlx-main/mlx-main/.github/pull_request_template.md +12 -0
  17. mlx-main/mlx-main/.github/scripts/build-sanitizer-tests.sh +48 -0
  18. mlx-main/mlx-main/.github/scripts/setup+build-cpp-linux-fedora-container.sh +27 -0
  19. mlx-main/mlx-main/.github/workflows/build_and_test.yml +152 -0
  20. mlx-main/mlx-main/.github/workflows/documentation.yml +28 -0
  21. mlx-main/mlx-main/.github/workflows/nightly.yml +104 -0
  22. mlx-main/mlx-main/.github/workflows/release.yml +256 -0
  23. mlx-main/mlx-main/.gitignore +81 -0
  24. mlx-main/mlx-main/.pre-commit-config.yaml +27 -0
  25. mlx-main/mlx-main/ACKNOWLEDGMENTS.md +268 -0
  26. mlx-main/mlx-main/CITATION.cff +24 -0
  27. mlx-main/mlx-main/CMakeLists.txt +450 -0
  28. mlx-main/mlx-main/CODE_OF_CONDUCT.md +132 -0
  29. mlx-main/mlx-main/CONTRIBUTING.md +38 -0
  30. mlx-main/mlx-main/LICENSE +21 -0
  31. mlx-main/mlx-main/MANIFEST.in +6 -0
  32. mlx-main/mlx-main/README.md +121 -0
  33. mlx-main/mlx-main/benchmarks/cpp/CMakeLists.txt +11 -0
  34. mlx-main/mlx-main/benchmarks/cpp/autograd.cpp +39 -0
  35. mlx-main/mlx-main/benchmarks/cpp/compare_devices.cpp +27 -0
  36. mlx-main/mlx-main/benchmarks/cpp/irregular_strides.cpp +201 -0
  37. mlx-main/mlx-main/benchmarks/cpp/single_ops.cpp +288 -0
  38. mlx-main/mlx-main/benchmarks/cpp/time_utils.h +39 -0
  39. mlx-main/mlx-main/benchmarks/numpy/single_ops.py +39 -0
  40. mlx-main/mlx-main/benchmarks/numpy/time_utils.py +20 -0
  41. mlx-main/mlx-main/benchmarks/python/batch_matmul_bench.py +62 -0
  42. mlx-main/mlx-main/benchmarks/python/blas/bench_gemm.py +191 -0
  43. mlx-main/mlx-main/benchmarks/python/blas/bench_gemv.py +220 -0
  44. mlx-main/mlx-main/benchmarks/python/block_masked_mm_bench.py +193 -0
  45. mlx-main/mlx-main/benchmarks/python/comparative/README.md +15 -0
  46. mlx-main/mlx-main/benchmarks/python/comparative/bench_mlx.py +519 -0
  47. mlx-main/mlx-main/benchmarks/python/comparative/bench_torch.py +482 -0
  48. mlx-main/mlx-main/benchmarks/python/comparative/compare.py +284 -0
  49. mlx-main/mlx-main/benchmarks/python/compile_bench.py +107 -0
  50. mlx-main/mlx-main/benchmarks/python/conv1d_bench.py +123 -0
mlx-main/mlx-main/.clang-format ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ AccessModifierOffset: -1
3
+ AlignAfterOpenBracket: AlwaysBreak
4
+ AlignConsecutiveAssignments: false
5
+ AlignConsecutiveDeclarations: false
6
+ AlignEscapedNewlinesLeft: true
7
+ AlignOperands: false
8
+ AlignTrailingComments: false
9
+ AllowAllParametersOfDeclarationOnNextLine: false
10
+ AllowShortBlocksOnASingleLine: false
11
+ AllowShortCaseLabelsOnASingleLine: false
12
+ AllowShortFunctionsOnASingleLine: Empty
13
+ AllowShortIfStatementsOnASingleLine: false
14
+ AllowShortLoopsOnASingleLine: false
15
+ AlwaysBreakAfterReturnType: None
16
+ AlwaysBreakBeforeMultilineStrings: true
17
+ AlwaysBreakTemplateDeclarations: true
18
+ BinPackArguments: false
19
+ BinPackParameters: false
20
+ BraceWrapping:
21
+ AfterClass: false
22
+ AfterControlStatement: false
23
+ AfterEnum: false
24
+ AfterFunction: false
25
+ AfterNamespace: false
26
+ AfterObjCDeclaration: false
27
+ AfterStruct: false
28
+ AfterUnion: false
29
+ BeforeCatch: false
30
+ BeforeElse: false
31
+ IndentBraces: false
32
+ BreakBeforeBinaryOperators: None
33
+ BreakBeforeBraces: Attach
34
+ BreakBeforeTernaryOperators: true
35
+ BreakConstructorInitializersBeforeComma: false
36
+ BreakAfterJavaFieldAnnotations: false
37
+ BreakStringLiterals: false
38
+ ColumnLimit: 80
39
+ CommentPragmas: '^ IWYU pragma:'
40
+ ConstructorInitializerAllOnOneLineOrOnePerLine: true
41
+ ConstructorInitializerIndentWidth: 4
42
+ ContinuationIndentWidth: 4
43
+ Cpp11BracedListStyle: true
44
+ DerivePointerAlignment: false
45
+ DisableFormat: false
46
+ ForEachMacros: [ FOR_EACH, FOR_EACH_R, FOR_EACH_RANGE, ]
47
+ IncludeCategories:
48
+ - Regex: '^<.*\.h(pp)?>'
49
+ Priority: 1
50
+ - Regex: '^<.*'
51
+ Priority: 2
52
+ - Regex: '.*'
53
+ Priority: 3
54
+ IndentCaseLabels: true
55
+ IndentWidth: 2
56
+ IndentWrappedFunctionNames: false
57
+ KeepEmptyLinesAtTheStartOfBlocks: false
58
+ MacroBlockBegin: ''
59
+ MacroBlockEnd: ''
60
+ MaxEmptyLinesToKeep: 1
61
+ NamespaceIndentation: None
62
+ ObjCBlockIndentWidth: 2
63
+ ObjCSpaceAfterProperty: false
64
+ ObjCSpaceBeforeProtocolList: false
65
+ PenaltyBreakBeforeFirstCallParameter: 1
66
+ PenaltyBreakComment: 300
67
+ PenaltyBreakFirstLessLess: 120
68
+ PenaltyBreakString: 1000
69
+ PenaltyExcessCharacter: 1000000
70
+ PenaltyReturnTypeOnItsOwnLine: 200
71
+ PointerAlignment: Left
72
+ ReflowComments: true
73
+ SortIncludes: true
74
+ SpaceAfterCStyleCast: false
75
+ SpaceBeforeAssignmentOperators: true
76
+ SpaceBeforeParens: ControlStatements
77
+ SpaceInEmptyParentheses: false
78
+ SpacesBeforeTrailingComments: 1
79
+ SpacesInAngles: false
80
+ SpacesInContainerLiterals: true
81
+ SpacesInCStyleCastParentheses: false
82
+ SpacesInParentheses: false
83
+ SpacesInSquareBrackets: false
84
+ Standard: Cpp11
85
+ TabWidth: 8
86
+ UseTab: Never
87
+ ...
mlx-main/mlx-main/.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Create a report about an issue you've encountered
4
+ title: "[BUG] "
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Describe the bug**
11
+ A clear and concise description of what the bug is.
12
+
13
+ **To Reproduce**
14
+
15
+ Include code snippet
16
+ ```python
17
+
18
+ ```
19
+
20
+ **Expected behavior**
21
+ A clear and concise description of what you expected to happen.
22
+
23
+ **Desktop (please complete the following information):**
24
+ - OS Version: [e.g. MacOS 14.1.2]
25
+ - Version [e.g. 0.7.0]
26
+
27
+ **Additional context**
28
+ Add any other context about the problem here.
mlx-main/mlx-main/.github/actions/build-cuda-release/action.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build CUDA wheel'
2
+ description: 'Build CUDA wheel'
3
+
4
+ inputs:
5
+ arch:
6
+ description: 'Platform architecture tag'
7
+ required: true
8
+ type: choice
9
+ options:
10
+ - x86_64
11
+ - aarch64
12
+
13
+ runs:
14
+ using: "composite"
15
+ steps:
16
+ - name: Build package
17
+ shell: bash
18
+ env:
19
+ CMAKE_ARGS: -DMLX_BUILD_CUDA=ON
20
+ run: |
21
+ pip install auditwheel "build<=1.4.2" patchelf setuptools
22
+ python setup.py clean --all
23
+ MLX_DISABLE_SM90A_KERNELS=1 MLX_BUILD_STAGE=2 python -m build -w
24
+
25
+ auditwheel repair dist/mlx_cuda*.whl \
26
+ --plat manylinux_2_35_${{ inputs.arch }} \
27
+ --exclude libcublas* \
28
+ --exclude libcuda* \
29
+ --exclude libcudnn* \
30
+ --exclude libnccl* \
31
+ --exclude libnvrtc*
mlx-main/mlx-main/.github/actions/build-docs/action.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build Documentation'
2
+ description: 'Build documentation'
3
+
4
+ runs:
5
+ using: "composite"
6
+ steps:
7
+ - name: Setup machine
8
+ uses: ./.github/actions/setup-linux
9
+
10
+ - name: Install dependencies
11
+ shell: bash
12
+ run: |
13
+ sudo apt-get install -y doxygen
14
+ source .venv/bin/activate
15
+ pip install -r docs/requirements.txt
16
+ pip install . -v
17
+
18
+ - name: Build documentation
19
+ shell: bash
20
+ run: |
21
+ source .venv/bin/activate
22
+ cd docs
23
+ doxygen
24
+ make html O=-W
25
+
26
+ - name: Create artifact tar
27
+ shell: bash
28
+ run: tar -cf artifact.tar -C docs --dereference build/html index.html
29
+
30
+ # Do it manually because upload-pages-artifact requires gtar
31
+ - name: Upload artifact
32
+ id: upload-artifact
33
+ uses: actions/upload-artifact@v5
34
+ with:
35
+ name: github-pages
36
+ path: artifact.tar
37
+ retention-days: 1
38
+ if-no-files-found: error
mlx-main/mlx-main/.github/actions/build-linux-release/action.yml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build Linux wheel'
2
+ description: 'Build Linux wheel'
3
+
4
+ inputs:
5
+ build-backend:
6
+ description: 'Build the backend mlx-cpu package'
7
+ type: boolean
8
+ required: false
9
+ default: false
10
+ arch:
11
+ description: 'Platform architecture tag'
12
+ required: true
13
+ type: choice
14
+ options:
15
+ - x86_64
16
+ - aarch64
17
+
18
+ runs:
19
+ using: "composite"
20
+ steps:
21
+ - name: Build MLX
22
+ shell: bash
23
+ run: pip install -e . -v
24
+
25
+ - name: Build Python package
26
+ shell: bash
27
+ run: |
28
+ pip install auditwheel patchelf "build<=1.4.2"
29
+ python setup.py clean --all
30
+ MLX_BUILD_STAGE=1 python -m build -w
31
+ auditwheel repair dist/mlx-*.whl \
32
+ --plat manylinux_2_35_${{ inputs.arch }} \
33
+ --exclude libmlx.so* \
34
+ --only-plat
35
+
36
+ - name: Build backend package
37
+ if: ${{ inputs.build-backend }}
38
+ shell: bash
39
+ run: |
40
+ python setup.py clean --all
41
+ MLX_BUILD_STAGE=2 python -m build -w
42
+ auditwheel repair dist/mlx_cpu*.whl --plat manylinux_2_35_${{ inputs.arch }}
mlx-main/mlx-main/.github/actions/build-linux/action.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build and Test on Linux'
2
+
3
+ inputs:
4
+ toolkit:
5
+ description: 'The toolkit to build with'
6
+ required: false
7
+ default: 'cpu'
8
+
9
+ runs:
10
+ using: "composite"
11
+ steps:
12
+
13
+ - name: Install Python package
14
+ id: python_build
15
+ shell: sh
16
+ env:
17
+ DEBUG: 1
18
+ CMAKE_ARGS: >-
19
+ -DCMAKE_COMPILE_WARNING_AS_ERROR=ON
20
+ -DMLX_BUILD_CUDA=${{ startsWith(inputs.toolkit, 'cuda') && 'ON' || 'OFF' }}
21
+ run: |
22
+ if ${{ startsWith(inputs.toolkit, 'cuda') && runner.arch == 'arm64' }} ; then
23
+ # There is no GPU in arm64 runner, use a common arch.
24
+ CMAKE_ARGS="$CMAKE_ARGS -DMLX_CUDA_ARCHITECTURES=80"
25
+ # Can not build tests and stubs when the built executables can not run.
26
+ CMAKE_ARGS="$CMAKE_ARGS -DMLX_BUILD_TESTS=OFF -DMLX_BUILD_PYTHON_STUBS=OFF"
27
+ fi
28
+ # Install cpu-only torch to save space
29
+ pip install torch --index-url https://download.pytorch.org/whl/cpu
30
+ pip install --no-build-isolation -e ".[dev]" -v
31
+ # Pass the CMAKE_ARGS to following steps.
32
+ echo CMAKE_ARGS="$CMAKE_ARGS" >> $GITHUB_OUTPUT
33
+
34
+ - name: Build CPP only
35
+ shell: bash
36
+ run: |
37
+ cmake . -B build -DCMAKE_BUILD_TYPE=Debug ${{ steps.python_build.outputs.CMAKE_ARGS }}
38
+ cmake --build build -j $(nproc)
mlx-main/mlx-main/.github/actions/build-macos-release/action.yml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build macOS release'
2
+ description: 'Build MLX releases macOS'
3
+
4
+ inputs:
5
+ macos-target:
6
+ description: 'macOS build target'
7
+ required: false
8
+ default: '15.0'
9
+ build-backend:
10
+ description: 'Build the backend mlx-metal package'
11
+ type: boolean
12
+ required: false
13
+ default: false
14
+
15
+ runs:
16
+ using: "composite"
17
+ steps:
18
+ - name: Build Python package
19
+ shell: bash -l {0}
20
+ env:
21
+ DEVELOPER_DIR: /Applications/Xcode-latest.app
22
+ MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }}
23
+ run: |
24
+ pip install build
25
+ python setup.py clean --all
26
+ MLX_BUILD_STAGE=1 python -m build -w
27
+
28
+ - name: Build backend package
29
+ if: ${{ inputs.build-backend }}
30
+ shell: bash -l {0}
31
+ env:
32
+ DEVELOPER_DIR: /Applications/Xcode-latest.app
33
+ MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }}
34
+ run: |
35
+ python setup.py clean --all
36
+ MLX_BUILD_STAGE=2 python -m build -w
mlx-main/mlx-main/.github/actions/build-macos/action.yml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build and Test on macOS'
2
+ description: 'Build and test MLX on macOS'
3
+
4
+ runs:
5
+ using: "composite"
6
+ steps:
7
+ - name: Install dependencies
8
+ env:
9
+ DEBUG: 1
10
+ CMAKE_ARGS: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON"
11
+ shell: bash -l {0}
12
+ run: |
13
+ pip install --upgrade pip
14
+ pip install cmake setuptools typing_extensions
15
+ pip install -e ".[dev]" -v
16
+
17
+ - name: Install tests dependencies
18
+ shell: bash -l {0}
19
+ run: |
20
+ pip install tensorflow
21
+
22
+ - name: Run Python tests
23
+ shell: bash -l {0}
24
+ env:
25
+ LOW_MEMORY: 1
26
+ run: |
27
+ DEVICE=cpu python -m unittest discover -v python/tests
28
+ DEVICE=gpu METAL_DEVICE_WRAPPER_TYPE=1 METAL_DEBUG_ERROR_MODE=0 python -m unittest discover -v python/tests
29
+ mpirun --bind-to none -host localhost:8 -np 8 -x DYLD_LIBRARY_PATH=/opt/homebrew/lib/ python python/tests/mpi_test_distributed.py
30
+ mlx.launch --verbose -n 8 python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2)
31
+ if $(grep "\[WARN\]" stderr.log); then echo "Distributed ring test failed"; exit 1; fi
32
+
33
+ - name: Build example extension
34
+ shell: bash -l {0}
35
+ run: |
36
+ cd examples/extensions
37
+ pip install -r requirements.txt
38
+ python setup.py build_ext --inplace
39
+ python test.py
40
+
41
+ - name: Build CPP only
42
+ shell: bash -l {0}
43
+ run: |
44
+ mkdir -p build
45
+ cd build
46
+ cmake ..
47
+ make -j $(sysctl -n hw.ncpu)
48
+
49
+ - name: Run CPP tests
50
+ shell: bash -l {0}
51
+ env:
52
+ DEVICE: gpu
53
+ METAL_DEVICE_WRAPPER_TYPE: 1
54
+ METAL_DEBUG_ERROR_MODE: 0
55
+ run: |
56
+ ./build/tests/tests
57
+ ./build/tests/test_teardown
58
+
59
+ - name: Build small binary with JIT
60
+ shell: bash -l {0}
61
+ run: |
62
+ mkdir -p build
63
+ cd build
64
+ cmake .. -DCMAKE_BUILD_TYPE=MinSizeRel \
65
+ -DBUILD_SHARED_LIBS=ON \
66
+ -DMLX_BUILD_CPU=OFF \
67
+ -DMLX_BUILD_SAFETENSORS=OFF \
68
+ -DMLX_BUILD_GGUF=OFF \
69
+ -DMLX_METAL_JIT=ON
70
+ make -j $(sysctl -n hw.ncpu)
71
+
72
+ - name: Run Python tests with JIT
73
+ shell: bash -l {0}
74
+ env:
75
+ LOW_MEMORY: 1
76
+ DEVICE: gpu
77
+ METAL_DEVICE_WRAPPER_TYPE: 1
78
+ METAL_DEBUG_ERROR_MODE: 0
79
+ run: |
80
+ CMAKE_ARGS="-DMLX_METAL_JIT=ON" \
81
+ pip install -e . -v
82
+ python -m unittest discover -v python/tests
mlx-main/mlx-main/.github/actions/build-windows/action.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Build on Windows'
2
+
3
+ runs:
4
+ using: 'composite'
5
+ steps:
6
+ - name: Install Python package
7
+ id: python-build
8
+ shell: cmd
9
+ env:
10
+ # For MSVC, Ninja/Release is the only config supported by ccache.
11
+ CMAKE_ARGS: >-
12
+ -G Ninja
13
+ -DCMAKE_BUILD_TYPE=Release
14
+ -DCMAKE_C_COMPILER=cl
15
+ -DCMAKE_CXX_COMPILER=cl
16
+ -DCMAKE_RC_COMPILER=rc
17
+ run: |
18
+ uv pip install ".[dev]" -v
19
+ :: Pass the CMAKE_ARGS to following steps.
20
+ >>%GITHUB_OUTPUT% ECHO CMAKE_ARGS=%CMAKE_ARGS%
21
+
22
+ - name: Build CPP only
23
+ shell: cmd
24
+ run: |
25
+ cmake . -B build ${{ steps.python-build.outputs.CMAKE_ARGS }}
26
+ cmake --build build -j %NUMBER_OF_PROCESSORS%
mlx-main/mlx-main/.github/actions/setup-linux/action.yml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Setup Linux Environment'
2
+ description: 'Install dependencies for Linux builds'
3
+
4
+ inputs:
5
+ toolkit:
6
+ description: 'Which toolkit to install'
7
+ required: false
8
+ default: 'cpu'
9
+ python-version:
10
+ description: 'Version of python to set up'
11
+ required: false
12
+ default: '3.14'
13
+ use-ccache:
14
+ description: 'Whether to enable ccache'
15
+ required: false
16
+ default: 'true'
17
+
18
+ runs:
19
+ using: "composite"
20
+ steps:
21
+ - name: Install common dependencies
22
+ shell: bash
23
+ run: |
24
+ echo "::group::Install common dependencies"
25
+ sudo apt-get update
26
+ sudo apt-get install -y --no-install-recommends \
27
+ zip \
28
+ libblas-dev liblapack-dev liblapacke-dev \
29
+ openmpi-bin openmpi-common libopenmpi-dev
30
+ echo "::endgroup::"
31
+
32
+ - name: Use ccache
33
+ if: ${{ inputs.use-ccache == 'true' }}
34
+ uses: hendrikmuhs/ccache-action@v1.2
35
+ with:
36
+ key: ccache-${{ runner.os }}-${{ runner.arch }}-${{ inputs.toolkit }}
37
+ max-size: 1GB
38
+ # ccache-action bug: running "apt-get update" fails on large arm runner.
39
+ update-package-index: false
40
+
41
+ - uses: actions/setup-python@v6
42
+ with:
43
+ python-version: ${{ inputs.python-version }}
44
+
45
+ - name: Setup Python venv
46
+ shell: bash
47
+ run: |
48
+ echo "::group::Setup Python venv"
49
+ python -m venv .venv
50
+ source .venv/bin/activate
51
+ pip install setuptools cmake typing_extensions
52
+ echo PATH=$PATH >> $GITHUB_ENV
53
+ # Search python packages in .venv
54
+ echo PYTHONPATH=`python -c 'import sys; print(sys.path[-1])'` >> $GITHUB_ENV
55
+ echo "::endgroup::"
56
+
57
+ - name: Set swap space
58
+ if: ${{ startsWith(inputs.toolkit, 'cuda') }}
59
+ uses: pierotofy/set-swap-space@fc79b3f67fa8a838184ce84a674ca12238d2c761
60
+ with:
61
+ swap-size-gb: 16
62
+
63
+ - name: Install CUDA toolkit
64
+ if: ${{ startsWith(inputs.toolkit, 'cuda') }}
65
+ shell: bash
66
+ env:
67
+ # Note: the CI machine does not meet CUDA 13's driver requirement.
68
+ # Compatibility matrix:
69
+ # https://docs.nvidia.com/deeplearning/cudnn/backend/latest/reference/support-matrix.html
70
+ PACKAGES: |
71
+ {
72
+ "cuda-12.6": "libcudnn9-dev-cuda-12 cuda-compiler-12-6 cuda-libraries-dev-12-6",
73
+ "cuda-12.9": "libcudnn9-dev-cuda-12 cuda-compiler-12-9 cuda-libraries-dev-12-9",
74
+ "cuda-13.0": "libcudnn9-dev-cuda-13 cuda-compiler-13-0 cuda-libraries-dev-13-0"
75
+ }
76
+ run: |
77
+ echo "::group::Install CUDA toolkit"
78
+ # The CUDA binaries are hosted in the "sbsa" repo, the "arm64" repo is
79
+ # Jetson specific. SBSA means Arm Server Base System Architecture.
80
+ ARCH=${{ runner.arch == 'arm64' && 'sbsa' || 'x86_64' }}
81
+ wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/$ARCH/cuda-keyring_1.1-1_all.deb
82
+ sudo dpkg -i cuda-keyring_1.1-1_all.deb
83
+ sudo apt-get update
84
+ sudo apt-get install -y --no-install-recommends \
85
+ libnccl2 libnccl-dev \
86
+ ${{ fromJson(env.PACKAGES)[inputs.toolkit] }}
87
+ echo "/usr/local/${{ inputs.toolkit }}/bin" >> $GITHUB_PATH
88
+ echo "::endgroup::"
89
+
90
+ - name: CUDA packages and driver report
91
+ if: ${{ startsWith(inputs.toolkit, 'cuda') }}
92
+ shell: bash
93
+ run: |
94
+ echo "::group::Installed NVIDIA and CUDA packages"
95
+ dpkg -l | egrep "cuda|nvidia" -i
96
+ echo "::endgroup::"
97
+ echo "::group::NVIDIA-SMI Status"
98
+ nvidia-smi || true
99
+ echo "::endgroup::"
mlx-main/mlx-main/.github/actions/setup-macos/action.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Setup macOS Environment'
2
+ description: 'Install dependencies for macOS builds'
3
+
4
+ inputs:
5
+ python-version:
6
+ description: 'Python version to use'
7
+ required: false
8
+ default: '3.10'
9
+
10
+ runs:
11
+ using: "composite"
12
+ steps:
13
+ - name: Install Homebrew packages
14
+ shell: sh
15
+ run: /opt/homebrew/bin/brew install openmpi
16
+
17
+ - name: Verify MetalToolchain installed
18
+ shell: bash
19
+ run: xcodebuild -showComponent MetalToolchain
20
+
21
+ - uses: conda-incubator/setup-miniconda@v3
22
+ with:
23
+ miniconda-version: "latest"
24
+ python-version: ${{ inputs.python-version }}
mlx-main/mlx-main/.github/actions/setup-windows/action.yml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Setup Windows environment'
2
+
3
+ inputs:
4
+ python-version:
5
+ description: 'Version of python to set up'
6
+ required: false
7
+ default: '3.14'
8
+ use-ccache:
9
+ description: 'Whether to enable ccache'
10
+ required: false
11
+ default: 'true'
12
+
13
+ runs:
14
+ using: 'composite'
15
+ steps:
16
+ - name: Use ccache
17
+ if: ${{ inputs.use-ccache == 'true' }}
18
+ uses: hendrikmuhs/ccache-action@v1.2
19
+ with:
20
+ key: ccache-${{ runner.os }}-${{ runner.arch }}-cpu
21
+ max-size: 1GB
22
+
23
+ - name: Setup Visual Studio cmd
24
+ shell: cmd
25
+ run: |
26
+ :: Find out path to VS.
27
+ pushd "C:\Program Files (x86)\Microsoft Visual Studio\Installer\"
28
+ for /f "delims=" %%x in ('.\vswhere.exe -latest -property InstallationPath') do set VSPATH=%%x
29
+ popd
30
+ :: Import VS vars.
31
+ call "%VSPATH%\VC\Auxiliary\Build\vcvarsall.bat" x64
32
+ :: Export to all steps.
33
+ >>%GITHUB_ENV% set
34
+
35
+ - uses: astral-sh/setup-uv@v7
36
+
37
+ - name: Setup Python venv
38
+ shell: cmd
39
+ run: |
40
+ uv venv --python ${{ inputs.python-version }}
41
+ call ".venv/Scripts/activate.bat"
42
+ >>%GITHUB_ENV% set
mlx-main/mlx-main/.github/actions/test-linux/action.yml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Run Linux tests'
2
+
3
+ inputs:
4
+ has-gpu:
5
+ description: 'Run GPU tests'
6
+ required: false
7
+ default: false
8
+
9
+ runs:
10
+ using: "composite"
11
+ steps:
12
+ - name: Run MPI tests
13
+ shell: bash
14
+ run: |
15
+ echo "::group::MPI tests"
16
+ mpirun --bind-to none --allow-run-as-root -host localhost:8 -np 8 python python/tests/mpi_test_distributed.py
17
+ echo "::endgroup::"
18
+
19
+ - name: Run distributed tests
20
+ if: ${{ inputs.has-gpu == 'false' }}
21
+ shell: bash
22
+ run: |
23
+ echo "::group::Distributed tests"
24
+ mlx.launch --verbose -n 8 python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2)
25
+ if grep -Fq '[WARN]' stderr.log ; then
26
+ grep -F '[WARN]' stderr.log
27
+ echo "Distributed ring test failed";
28
+ exit 1;
29
+ fi
30
+ echo "::endgroup::"
31
+
32
+ - name: Run Python tests - CPU
33
+ if: ${{ inputs.has-gpu == 'false' }}
34
+ shell: bash
35
+ env:
36
+ DEVICE: cpu
37
+ run: |
38
+ echo "::group::Python tests - CPU"
39
+ python -m unittest discover python/tests -v
40
+ echo "::endgroup::"
41
+
42
+ - name: Run Python tests - GPU
43
+ if: ${{ inputs.has-gpu == 'true' }}
44
+ shell: bash
45
+ env:
46
+ DEVICE: gpu
47
+ run: |
48
+ echo "::group::Python tests - GPU"
49
+ python -m tests discover python/tests -v
50
+ echo "::endgroup::"
51
+
52
+ - name: Run CPP tests - CPU
53
+ shell: bash
54
+ env:
55
+ DEVICE: cpu
56
+ run: |
57
+ echo "::group::CPP tests - CPU"
58
+ ./build/tests/tests
59
+ echo "::endgroup::"
60
+
61
+ - name: Run CPP tests - GPU
62
+ if: ${{ inputs.has-gpu == 'true' }}
63
+ shell: bash
64
+ env:
65
+ DEVICE: gpu
66
+ run: |
67
+ echo "::group::CPP tests - GPU"
68
+ ./build/tests/tests -sfe="*linalg_tests.cpp"
69
+ echo "::endgroup::"
mlx-main/mlx-main/.github/actions/test-windows/action.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'Run tests on Windows'
2
+
3
+ runs:
4
+ using: 'composite'
5
+ steps:
6
+ - name: Run Python tests - CPU
7
+ shell: bash
8
+ run: |
9
+ echo "::group::Python tests - CPU"
10
+ python -m unittest discover python/tests -v
11
+ echo "::endgroup::"
12
+
13
+ - name: Run CPP tests - CPU
14
+ shell: bash
15
+ env:
16
+ DEVICE: cpu
17
+ run: |
18
+ echo "::group::CPP tests - CPU"
19
+ ./build/tests.exe -tce="*gguf*,test random uniform"
20
+ ./build/test_teardown.exe
21
+ echo "::endgroup::"
mlx-main/mlx-main/.github/dependabot.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
mlx-main/mlx-main/.github/pull_request_template.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Proposed changes
2
+
3
+ Please include a description of the problem or feature this PR is addressing. If there is a corresponding issue, include the issue #.
4
+
5
+ ## Checklist
6
+
7
+ Put an `x` in the boxes that apply.
8
+
9
+ - [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document
10
+ - [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes
11
+ - [ ] I have added tests that prove my fix is effective or that my feature works
12
+ - [ ] I have updated the necessary documentation (if needed)
mlx-main/mlx-main/.github/scripts/build-sanitizer-tests.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -ex
3
+
4
+ export CMAKE_C_COMPILER=/usr/bin/clang
5
+ export CMAKE_CXX_COMPILER=/usr/bin/clang++
6
+ BASE_CMAKE_ARGS="-DCMAKE_BUILD_TYPE=DEBUG -DCMAKE_COMPILE_WARNING_AS_ERROR=ON"
7
+ if [[ "$(uname -s)" != "Darwin" ]]; then
8
+ BASE_CMAKE_ARGS+=" -DMLX_BUILD_METAL=OFF"
9
+ fi
10
+
11
+ run_test() {
12
+ local sanitizer_name=$1
13
+ local cmake_sanitizer_flag="-DUSE_${sanitizer_name}=ON"
14
+ echo " Running tests with: ${sanitizer_name}"
15
+
16
+ case "$sanitizer_name" in
17
+ ASAN)
18
+ export ASAN_OPTIONS="detect_leaks=0"
19
+ ;;
20
+ UBSAN)
21
+ export UBSAN_OPTIONS="halt_on_error=0:print_stacktrace=1"
22
+ ;;
23
+ TSAN)
24
+ export TSAN_OPTIONS=""
25
+ ;;
26
+ esac
27
+
28
+ rm -rf build
29
+ mkdir -p build
30
+ pushd build > /dev/null
31
+
32
+ cmake .. ${BASE_CMAKE_ARGS} ${cmake_sanitizer_flag}
33
+ make -j $(nproc)
34
+ ./tests/tests
35
+
36
+ popd > /dev/null
37
+ unset ${sanitizer_name}_OPTIONS
38
+ }
39
+
40
+ sanitizer_arg=$(echo "$1" | tr '[:lower:]' '[:upper:]')
41
+
42
+ if [[ "$sanitizer_arg" == "ASAN" || "$sanitizer_arg" == "UBSAN" || "$sanitizer_arg" == "TSAN" ]]; then
43
+ run_test "$sanitizer_arg"
44
+ echo " ${sanitizer_arg} test run completed successfully."
45
+ else
46
+ echo "Error: Invalid sanitizer '$1'. Please use one of: ASAN, UBSAN, TSAN."
47
+ exit 1
48
+ fi
mlx-main/mlx-main/.github/scripts/setup+build-cpp-linux-fedora-container.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -ex
3
+
4
+ # [Setup] Install dependencies inside the container.
5
+ dnf update -y
6
+ dnf install -y \
7
+ blas-devel \
8
+ lapack-devel \
9
+ openblas-devel \
10
+ make \
11
+ cmake \
12
+ clang \
13
+ git
14
+ dnf clean all
15
+
16
+ # [C++] CI Build Sanity Check: Verifies code compilation, not for release.
17
+ export CMAKE_ARGS="-DCMAKE_COMPILE_WARNING_AS_ERROR=ON"
18
+ export DEBUG=1
19
+ export CMAKE_C_COMPILER=/usr/bin/clang
20
+ export CMAKE_CXX_COMPILER=/usr/bin/clang++
21
+
22
+ mkdir -p build
23
+ pushd build
24
+ cmake .. -DMLX_BUILD_METAL=OFF -DCMAKE_BUILD_TYPE=DEBUG
25
+ make -j $(nproc)
26
+ ./tests/tests
27
+ popd
mlx-main/mlx-main/.github/workflows/build_and_test.yml ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build and Test
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches:
7
+ - main
8
+ # For testing CI without starting a pull request:
9
+ - test/*
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ concurrency:
15
+ group: ${{ github.workflow }}-${{ github.ref }}
16
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
17
+
18
+ jobs:
19
+ check_lint:
20
+ name: Check Lint
21
+ runs-on: ubuntu-22.04
22
+ steps:
23
+ - uses: actions/checkout@v6
24
+ - uses: pre-commit/action@v3.0.1
25
+
26
+ linux_build_and_test:
27
+ name: Linux (cpu, ${{ matrix.arch }})
28
+ needs: check_lint
29
+ strategy:
30
+ fail-fast: false
31
+ matrix:
32
+ arch: ['x86_64', 'aarch64']
33
+ runs-on: ${{ matrix.arch == 'x86_64' && 'ubuntu-22.04' || 'ubuntu-22.04-arm' }}
34
+ steps:
35
+ - uses: actions/checkout@v6
36
+ - uses: ./.github/actions/setup-linux
37
+ - uses: ./.github/actions/build-linux
38
+ - uses: ./.github/actions/test-linux
39
+ - run: df -h
40
+
41
+ cuda_build_and_test:
42
+ name: Linux (${{ matrix.toolkit }}, ${{ matrix.arch }})
43
+ if: github.repository == 'ml-explore/mlx'
44
+ needs: check_lint
45
+ strategy:
46
+ fail-fast: false
47
+ matrix:
48
+ arch: ['x86_64', 'aarch64']
49
+ toolkit: ['cuda-12.6', 'cuda-12.9']
50
+ runs-on: ${{ matrix.arch == 'x86_64' && 'gpu-t4-4-core' || 'ubuntu-22.04-arm' }}
51
+ steps:
52
+ - uses: actions/checkout@v6
53
+ - uses: ./.github/actions/setup-linux
54
+ with:
55
+ toolkit: ${{ matrix.toolkit }}
56
+ - uses: ./.github/actions/build-linux
57
+ with:
58
+ toolkit: ${{ matrix.toolkit }}
59
+ - uses: ./.github/actions/test-linux
60
+ if: matrix.arch == 'x86_64'
61
+ with:
62
+ has-gpu: true
63
+
64
+ mac_build_and_test:
65
+ name: macOS (${{ matrix.macos-target }})
66
+ if: github.repository == 'ml-explore/mlx'
67
+ strategy:
68
+ matrix:
69
+ macos-target: ["14.0", "15.0", "26.0"]
70
+ runs-on: [self-hosted, macos]
71
+ env:
72
+ MACOSX_DEPLOYMENT_TARGET: ${{ matrix.macos-target }}
73
+ needs: check_lint
74
+ steps:
75
+ - uses: actions/checkout@v6
76
+ - uses: ./.github/actions/setup-macos
77
+ - uses: ./.github/actions/build-macos
78
+
79
+ windows_build_and_test:
80
+ name: Windows (cpu, x86_64)
81
+ needs: check_lint
82
+ runs-on: windows-2025
83
+ steps:
84
+ - uses: actions/checkout@v6
85
+ - uses: ./.github/actions/setup-windows
86
+ - uses: ./.github/actions/build-windows
87
+ - uses: ./.github/actions/test-windows
88
+
89
+ build_documentation:
90
+ name: Build Documentation
91
+ if: github.repository == 'ml-explore/mlx'
92
+ runs-on: ubuntu-22.04
93
+ needs: check_lint
94
+ steps:
95
+ - uses: actions/checkout@v6
96
+ - uses: ./.github/actions/build-docs
97
+
98
+ linux_sanitizer_build_and_test:
99
+ name: Linux Sanitizer Tests (${{ matrix.sanitizer }})
100
+ needs: check_lint
101
+ strategy:
102
+ fail-fast: false
103
+ matrix:
104
+ sanitizer: [ASAN, UBSAN]
105
+ # todo 12/16/2025: enable TSAN later + consider enabling ASAN for GPU backend tests.
106
+ # sanitizer: [ASAN, UBSAN, TSAN]
107
+ runs-on: ubuntu-22.04-arm
108
+ steps:
109
+ - name: Checkout code
110
+ uses: actions/checkout@v6
111
+
112
+ - name: Install Dependencies
113
+ run: |
114
+ export DEBIAN_FRONTEND=noninteractive
115
+ sudo apt-get update -y
116
+ sudo apt-get install -y \
117
+ build-essential \
118
+ libblas-dev \
119
+ liblapacke-dev \
120
+ libopenblas-dev \
121
+ cmake \
122
+ clang \
123
+ git
124
+ sudo apt-get clean
125
+ sudo rm -rf /var/lib/apt/lists/*
126
+
127
+ - name: Linux Build and Test with ${{ matrix.sanitizer }}
128
+ run: |
129
+ bash .github/scripts/build-sanitizer-tests.sh ${{ matrix.sanitizer }}
130
+
131
+ linux_fedora_build_cpp:
132
+ name: Linux Fedora (${{ matrix.arch }})
133
+ needs: check_lint
134
+ strategy:
135
+ fail-fast: false
136
+ matrix:
137
+ include:
138
+ - host: ubuntu-22.04
139
+ arch: x86_64
140
+ - host: ubuntu-22.04-arm
141
+ arch: aarch64
142
+
143
+ runs-on: ${{ matrix.host }}
144
+ container:
145
+ image: fedora:42
146
+ steps:
147
+ - name: Checkout code
148
+ uses: actions/checkout@v6
149
+
150
+ - name: CPP Build Test - No Release
151
+ run: |
152
+ bash ./.github/scripts/setup+build-cpp-linux-fedora-container.sh
mlx-main/mlx-main/.github/workflows/documentation.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Documentation
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ permissions:
7
+ contents: read
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-22.04
12
+ steps:
13
+ - uses: actions/checkout@v6
14
+ - uses: ./.github/actions/build-docs
15
+
16
+ deploy:
17
+ needs: build
18
+ permissions:
19
+ pages: write
20
+ id-token: write
21
+ runs-on: ubuntu-latest
22
+ environment:
23
+ name: github-pages
24
+ url: ${{ steps.deployment.outputs.page_url }}
25
+ steps:
26
+ - name: Deploy to GitHub Pages
27
+ id: deployment
28
+ uses: actions/deploy-pages@v5
mlx-main/mlx-main/.github/workflows/nightly.yml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Nightly Build
2
+
3
+ on:
4
+ schedule:
5
+ - cron: 33 6 * * 1-5
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build_linux_release:
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ python_version: ["3.10", "3.14"]
17
+ runs-on: ubuntu-22.04
18
+ steps:
19
+ - uses: actions/checkout@v6
20
+ - uses: ./.github/actions/setup-linux
21
+ - uses: ./.github/actions/build-linux-release
22
+ with:
23
+ build-backend: ${{ matrix.python-version == '3.10' }}
24
+ arch: "x86_64"
25
+ - name: Upload mlx artifacts
26
+ uses: actions/upload-artifact@v7
27
+ with:
28
+ name: linux-wheels-${{ matrix.python_version }}
29
+ path: wheelhouse/mlx-*.whl
30
+ retention-days: 7
31
+ - name: Upload mlx-cpu artifacts
32
+ if: matrix.python_version == '3.10'
33
+ uses: actions/upload-artifact@v7
34
+ with:
35
+ name: mlx-cpu
36
+ path: wheelhouse/mlx_cpu-*.whl
37
+ retention-days: 7
38
+ - run: df -h
39
+
40
+ build_linux_with_tests:
41
+ strategy:
42
+ fail-fast: false
43
+ matrix:
44
+ python_version: ["3.11", "3.12", "3.13", "3.14"]
45
+ runner:
46
+ - ubuntu-22.04
47
+ - ubuntu-22.04-arm
48
+ runs-on: ${{ matrix.runner }}
49
+ steps:
50
+ - uses: actions/checkout@v6
51
+ - uses: ./.github/actions/setup-linux
52
+ with:
53
+ python-version: ${{ matrix.python_version }}
54
+ - uses: ./.github/actions/build-linux
55
+ - uses: ./.github/actions/test-linux
56
+ - run: df -h
57
+
58
+ build_mac_release:
59
+ if: github.repository == 'ml-explore/mlx'
60
+ strategy:
61
+ matrix:
62
+ python-version: ["3.10", "3.13"]
63
+ runs-on: [self-hosted, macos]
64
+ steps:
65
+ - uses: actions/checkout@v6
66
+ - uses: ./.github/actions/setup-macos
67
+ with:
68
+ python-version: ${{ matrix.python-version }}
69
+ - uses: ./.github/actions/build-macos
70
+ - name: Build macOS 26 package
71
+ uses: ./.github/actions/build-macos-release
72
+ with:
73
+ macos-target: 26.0
74
+ build-backend: ${{ matrix.python-version == '3.10' }}
75
+ - name: Build macOS 15 package
76
+ uses: ./.github/actions/build-macos-release
77
+ with:
78
+ macos-target: 15.0
79
+ build-backend: ${{ matrix.python-version == '3.10' }}
80
+ - name: Build macOS 14 package
81
+ uses: ./.github/actions/build-macos-release
82
+ with:
83
+ macos-target: 14.0
84
+ build-backend: ${{ matrix.python-version == '3.10' }}
85
+
86
+ build_cuda_release:
87
+ if: github.repository == 'ml-explore/mlx'
88
+ runs-on: ubuntu-22-large
89
+ steps:
90
+ - uses: actions/checkout@v6
91
+ - uses: ./.github/actions/setup-linux
92
+ with:
93
+ toolkit: 'cuda-12.9'
94
+ - name: Build Python package
95
+ uses: ./.github/actions/build-cuda-release
96
+ with:
97
+ toolkit: 'cuda-12.9'
98
+ arch: 'x86_64'
99
+ - name: Upload artifacts
100
+ uses: actions/upload-artifact@v7
101
+ with:
102
+ name: mlx-cuda
103
+ path: wheelhouse/mlx_cuda_*.whl
104
+ retention-days: 7
mlx-main/mlx-main/.github/workflows/release.yml ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: PyPI Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+ branches:
8
+ - 'test-publish/*'
9
+ workflow_dispatch:
10
+ inputs:
11
+ dry_run:
12
+ description: 'Dry run (do not publish to PyPi)'
13
+ required: false
14
+ type: boolean
15
+ dev_release:
16
+ description: 'Development release (DEV_RELEASE=1)'
17
+ required: false
18
+ type: boolean
19
+
20
+ permissions:
21
+ contents: read
22
+
23
+ jobs:
24
+ build_documentation:
25
+ if: github.repository == 'ml-explore/mlx'
26
+ runs-on: ubuntu-22.04
27
+ steps:
28
+ - uses: actions/checkout@v6
29
+ - uses: ./.github/actions/build-docs
30
+
31
+ deploy_documentation:
32
+ if: ${{ !inputs.dry_run }}
33
+ needs: build_documentation
34
+ permissions:
35
+ pages: write
36
+ id-token: write
37
+ runs-on: ubuntu-latest
38
+ environment:
39
+ name: github-pages
40
+ url: ${{ steps.deployment.outputs.page_url }}
41
+ steps:
42
+ - name: Deploy to GitHub Pages
43
+ id: deployment
44
+ uses: actions/deploy-pages@v5
45
+
46
+ build_linux_release:
47
+ if: github.repository == 'ml-explore/mlx'
48
+ strategy:
49
+ matrix:
50
+ python_version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
51
+ arch: ['x86_64', 'aarch64']
52
+ runs-on: ${{ matrix.arch == 'x86_64' && 'ubuntu-22.04' || 'ubuntu-22.04-arm' }}
53
+ env:
54
+ PYPI_RELEASE: 1
55
+ DEV_RELEASE: ${{ inputs.dev_release && 1 || 0 }}
56
+ steps:
57
+ - uses: actions/checkout@v6
58
+ - uses: ./.github/actions/setup-linux
59
+ with:
60
+ python-version: ${{ matrix.python_version }}
61
+ use-ccache: false
62
+ - uses: ./.github/actions/build-linux-release
63
+ with:
64
+ build-backend: ${{ matrix.python_version == '3.10' }}
65
+ arch: ${{ matrix.arch }}
66
+ - name: Upload MLX artifacts
67
+ uses: actions/upload-artifact@v7
68
+ with:
69
+ overwrite: true
70
+ name: linux-wheels-${{ matrix.python_version }}-${{ matrix.arch }}
71
+ path: wheelhouse/mlx-*.whl
72
+ if-no-files-found: error
73
+ - name: Upload CPU artifacts
74
+ if: matrix.python_version == '3.10'
75
+ uses: actions/upload-artifact@v7
76
+ with:
77
+ overwrite: true
78
+ name: mlx-cpu-${{ matrix.arch }}
79
+ path: wheelhouse/mlx_cpu-*.whl
80
+ if-no-files-found: error
81
+
82
+ build_mac_release:
83
+ if: github.repository == 'ml-explore/mlx'
84
+ strategy:
85
+ matrix:
86
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
87
+ runs-on: [self-hosted, macos]
88
+ env:
89
+ PYPI_RELEASE: 1
90
+ DEV_RELEASE: ${{ inputs.dev_release && 1 || 0 }}
91
+ steps:
92
+ - uses: actions/checkout@v6
93
+ - uses: ./.github/actions/setup-macos
94
+ with:
95
+ python-version: ${{ matrix.python-version }}
96
+
97
+ - name: Install dependencies
98
+ shell: bash -l {0}
99
+ run: |
100
+ pip install --upgrade pip
101
+ pip install cmake setuptools typing_extensions
102
+ pip install -e . -v
103
+ - name: Build macOS 14 package
104
+ uses: ./.github/actions/build-macos-release
105
+ with:
106
+ macos-target: 14.0
107
+ build-backend: ${{ matrix.python-version == '3.10' }}
108
+ - name: Build macOS 15 package
109
+ uses: ./.github/actions/build-macos-release
110
+ with:
111
+ macos-target: 15.0
112
+ build-backend: ${{ matrix.python-version == '3.10' }}
113
+ - name: Build macOS 26 package
114
+ uses: ./.github/actions/build-macos-release
115
+ with:
116
+ macos-target: 26.0
117
+ build-backend: ${{ matrix.python-version == '3.10' }}
118
+ - name: Upload MLX artifacts
119
+ uses: actions/upload-artifact@v7
120
+ with:
121
+ overwrite: true
122
+ name: mac-wheels-${{ matrix.python-version }}
123
+ path: dist/mlx-*.whl
124
+ if-no-files-found: error
125
+ - name: Upload Metal artifacts
126
+ if: matrix.python-version == '3.10'
127
+ uses: actions/upload-artifact@v7
128
+ with:
129
+ overwrite: true
130
+ name: mlx-metal
131
+ path: dist/mlx_metal-*.whl
132
+ if-no-files-found: error
133
+
134
+ build_cuda_release:
135
+ if: github.repository == 'ml-explore/mlx'
136
+ strategy:
137
+ matrix:
138
+ arch: ['x86_64', 'aarch64']
139
+ toolkit: ['cuda-12.9', 'cuda-13.0']
140
+ runs-on: ${{ matrix.arch == 'x86_64' && 'ubuntu-22-large' || 'ubuntu-22-large-arm' }}
141
+ env:
142
+ PYPI_RELEASE: 1
143
+ DEV_RELEASE: ${{ inputs.dev_release && 1 || 0 }}
144
+ steps:
145
+ - uses: actions/checkout@v6
146
+ - uses: ./.github/actions/setup-linux
147
+ with:
148
+ toolkit: ${{ matrix.toolkit }}
149
+ use-ccache: false
150
+ - name: Build Python package
151
+ uses: ./.github/actions/build-cuda-release
152
+ with:
153
+ arch: ${{ matrix.arch }}
154
+ - name: Upload artifacts
155
+ uses: actions/upload-artifact@v7
156
+ with:
157
+ overwrite: true
158
+ name: mlx-${{ matrix.toolkit }}-${{ matrix.arch }}
159
+ path: wheelhouse/mlx_cuda_*.whl
160
+ if-no-files-found: error
161
+
162
+ pypi-publish:
163
+ name: Upload release to PyPI
164
+ runs-on: ubuntu-latest
165
+ needs: [build_linux_release, build_mac_release]
166
+ permissions:
167
+ id-token: write
168
+ environment:
169
+ name: ${{ inputs.dry_run && 'dry-run' || 'pypi' }}
170
+ url: https://pypi.org/p/mlx
171
+ steps:
172
+ - uses: actions/download-artifact@v8
173
+ with:
174
+ pattern: linux-wheels-*
175
+ merge-multiple: true
176
+ path: dist
177
+ - uses: actions/download-artifact@v8
178
+ with:
179
+ pattern: mac-wheels-*
180
+ merge-multiple: true
181
+ path: dist
182
+ - name: Display structure of downloaded files
183
+ run: du -ah dist
184
+ - name: Publish package distributions to PyPI
185
+ if: ${{ !inputs.dry_run }}
186
+ uses: pypa/gh-action-pypi-publish@release/v1
187
+ with:
188
+ repository-url: https://upload.pypi.org/legacy/
189
+
190
+ pypi-publish-cuda:
191
+ name: Upload CUDA release to PyPI
192
+ runs-on: ubuntu-latest
193
+ needs: [build_cuda_release]
194
+ permissions:
195
+ id-token: write
196
+ environment:
197
+ name: ${{ inputs.dry_run && 'dry-run' || 'pypi' }}
198
+ url: https://pypi.org/p/mlx-cuda
199
+ steps:
200
+ - uses: actions/download-artifact@v8
201
+ with:
202
+ pattern: mlx-cuda-*
203
+ merge-multiple: true
204
+ path: dist
205
+ - name: Display structure of downloaded files
206
+ run: du -ah dist
207
+ - name: Publish package distributions to PyPI
208
+ if: ${{ !inputs.dry_run }}
209
+ uses: pypa/gh-action-pypi-publish@release/v1
210
+ with:
211
+ repository-url: https://upload.pypi.org/legacy/
212
+
213
+ pypi-publish-cpu:
214
+ name: Upload CPU release to PyPI
215
+ runs-on: ubuntu-latest
216
+ needs: [build_linux_release]
217
+ permissions:
218
+ id-token: write
219
+ environment:
220
+ name: ${{ inputs.dry_run && 'dry-run' || 'pypi' }}
221
+ url: https://pypi.org/p/mlx-cpu
222
+ steps:
223
+ - uses: actions/download-artifact@v8
224
+ with:
225
+ pattern: mlx-cpu-*
226
+ merge-multiple: true
227
+ path: dist
228
+ - name: Display structure of downloaded files
229
+ run: du -ah dist
230
+ - name: Publish package distributions to PyPI
231
+ if: ${{ !inputs.dry_run }}
232
+ uses: pypa/gh-action-pypi-publish@release/v1
233
+ with:
234
+ repository-url: https://upload.pypi.org/legacy/
235
+
236
+ pypi-publish-metal:
237
+ name: Upload Metal release to PyPI
238
+ runs-on: ubuntu-latest
239
+ needs: [build_mac_release]
240
+ permissions:
241
+ id-token: write
242
+ environment:
243
+ name: ${{ inputs.dry_run && 'dry-run' || 'pypi' }}
244
+ url: https://pypi.org/p/mlx-metal
245
+ steps:
246
+ - uses: actions/download-artifact@v8
247
+ with:
248
+ name: mlx-metal
249
+ path: dist
250
+ - name: Display structure of downloaded files
251
+ run: du -ah dist
252
+ - name: Publish package distributions to PyPI
253
+ if: ${{ !inputs.dry_run }}
254
+ uses: pypa/gh-action-pypi-publish@release/v1
255
+ with:
256
+ repository-url: https://upload.pypi.org/legacy/
mlx-main/mlx-main/.gitignore ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # tensor files
7
+ *.safe
8
+ *.safetensors
9
+
10
+ # Metal libraries
11
+ *.metallib
12
+
13
+ # Distribution / packaging
14
+ python/mlx/core
15
+ python/mlx/share
16
+ python/mlx/include
17
+ .Python
18
+ build/
19
+ develop-eggs/
20
+ dist/
21
+ downloads/
22
+ eggs/
23
+ .eggs/
24
+ lib/
25
+ lib64/
26
+ parts/
27
+ sdist/
28
+ var/
29
+ venv/
30
+ wheels/
31
+ share/python-wheels/
32
+ *.egg-info/
33
+ .installed.cfg
34
+ *.egg
35
+ MANIFEST
36
+ uv.lock
37
+ .DS_Store
38
+
39
+ # Prerequisites
40
+ *.d
41
+
42
+ # Compiled Object files
43
+ *.slo
44
+ *.lo
45
+ *.o
46
+ *.obj
47
+ *.ilk
48
+
49
+ # Precompiled Headers
50
+ *.gch
51
+ *.pch
52
+
53
+ # Compiled Dynamic libraries
54
+ *.so
55
+ *.dylib
56
+ *.dll
57
+
58
+ # Fortran module files
59
+ *.mod
60
+ *.smod
61
+
62
+ # Compiled Static libraries
63
+ *.lai
64
+ *.la
65
+ *.a
66
+ *.lib
67
+
68
+ # Executables
69
+ *.exe
70
+ *.out
71
+ *.app
72
+
73
+ # Debug symbols
74
+ *.pdb
75
+
76
+ # VSCode
77
+ .vscode/
78
+ # Jetbrains
79
+ .cache/
80
+ # vim
81
+ *.swp
mlx-main/mlx-main/.pre-commit-config.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v6.0.0
4
+ hooks:
5
+ - id: check-yaml
6
+ # - id: end-of-file-fixer
7
+ # - id: trailing-whitespace
8
+ - repo: https://github.com/pre-commit/mirrors-clang-format
9
+ rev: v21.1.8
10
+ hooks:
11
+ - id: clang-format
12
+ # Using this mirror lets us use mypyc-compiled black, which is about 2x faster
13
+ - repo: https://github.com/psf/black-pre-commit-mirror
14
+ rev: 26.1.0
15
+ hooks:
16
+ - id: black
17
+
18
+ - repo: https://github.com/pycqa/isort
19
+ rev: 7.0.0
20
+ hooks:
21
+ - id: isort
22
+ args:
23
+ - --profile=black
24
+ - repo: https://github.com/cheshirekow/cmake-format-precommit
25
+ rev: v0.6.13
26
+ hooks:
27
+ - id: cmake-format
mlx-main/mlx-main/ACKNOWLEDGMENTS.md ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Individual Contributors
2
+
3
+ If you wish to be acknowledged for your contributions, please list your name
4
+ with a short description of your contribution(s) below. For example:
5
+
6
+ - Jane Smith: Added the `foo` and `bar` ops.
7
+
8
+ MLX was developed with contributions from the following individuals:
9
+
10
+ - Nripesh Niketan: Added `softsign`, `softmax`, `hardswish`, `logsoftmax` activation functions. Added `dropout3d` ops. Added `LogicalAnd` and `LogicalOR` ops. Added `clip_grad_norm` along with `tree_reduce`. Added `cross`. Added `orthogonal` initializer.
11
+ - Juarez Bochi: Fixed bug in cross attention.
12
+ - Justin Deschenaux: Sine, Cosine, arange, randint, truncated normal, bernoulli, lion optimizer, Dropout2d, linear and logistic regression python example.
13
+ - Diogo Da Cruz: Added `tri`, `tril`, `triu`, `tensordot`, `inner`, `outer`, `tile`, `StreamContext`, `stream`, safetensors support, `einsum`, and `einsum_path`.
14
+ - Gabrijel Boduljak: Added `mlx.core.linalg`, implemented `norm` method and `InstanceNorm` layer. Implemented pooling layers and ``Upsample``.
15
+ - Hinrik Snær Guðmundsson: Added `atleast_1d`, `atleast_2d`, `atleast_3d` ops.
16
+ - Luca Arnaboldi: Added `Ceil` and `Floor` ops; implemented pickling, copy and deepcopy for mlx arrays.
17
+ - Brian Keene & Atila Orhon, with Argmax Inc.: Added `fast.scaled_dot_product_attention`
18
+ - AmirHossein Razlighi: Added chaining support for some of the ops in `nn.Module`. Comparison works for non array objects in `mlx.core.array`. Exception handling for invalid operations in `mlx.core.array`.
19
+ - Gleb Pobudzey: Added the `where` primitive, and groups in 1D and 2D convolutions.
20
+ - Paul Paczuski: Improved stability of BCE loss calculation
21
+ - Max-Heinrich Laves: Added `conv_transpose1d`, `conv_transpose2d`, and `conv_transpose3d` ops.
22
+ - Gökdeniz Gülmez: Added the `Muon (MomentUm Orthogonalized by Newton-schulz)` optimizer, and the `ReLU²` activation function.
23
+
24
+ <a href="https://github.com/ml-explore/mlx/graphs/contributors">
25
+ <img class="dark-light" src="https://contrib.rocks/image?repo=ml-explore/mlx&anon=0&columns=20&max=100&r=true" />
26
+ </a>
27
+
28
+ # Organizations
29
+
30
+ MLX has received contributions from the following companies:
31
+ - NVIDIA Corporation & Affiliates
32
+
33
+ # Third-Party Software
34
+
35
+ MLX leverages several third-party software, listed here together with
36
+ their license copied verbatim.
37
+
38
+ ## PocketFFT
39
+
40
+ Copyright (C) 2010-2018 Max-Planck-Society
41
+ All rights reserved.
42
+
43
+ Redistribution and use in source and binary forms, with or without modification,
44
+ are permitted provided that the following conditions are met:
45
+
46
+ * Redistributions of source code must retain the above copyright notice, this
47
+ list of conditions and the following disclaimer.
48
+ * Redistributions in binary form must reproduce the above copyright notice, this
49
+ list of conditions and the following disclaimer in the documentation and/or
50
+ other materials provided with the distribution.
51
+ * Neither the name of the copyright holder nor the names of its contributors may
52
+ be used to endorse or promote products derived from this software without
53
+ specific prior written permission.
54
+
55
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
56
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
57
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
58
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
59
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
60
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
62
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
63
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65
+
66
+ ## metal-cpp
67
+
68
+ Apache License
69
+ Version 2.0, January 2004
70
+ http://www.apache.org/licenses/
71
+
72
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
73
+
74
+ 1. Definitions.
75
+
76
+ "License" shall mean the terms and conditions for use, reproduction,
77
+ and distribution as defined by Sections 1 through 9 of this document.
78
+
79
+ "Licensor" shall mean the copyright owner or entity authorized by
80
+ the copyright owner that is granting the License.
81
+
82
+ "Legal Entity" shall mean the union of the acting entity and all
83
+ other entities that control, are controlled by, or are under common
84
+ control with that entity. For the purposes of this definition,
85
+ "control" means (i) the power, direct or indirect, to cause the
86
+ direction or management of such entity, whether by contract or
87
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
88
+ outstanding shares, or (iii) beneficial ownership of such entity.
89
+
90
+ "You" (or "Your") shall mean an individual or Legal Entity
91
+ exercising permissions granted by this License.
92
+
93
+ "Source" form shall mean the preferred form for making modifications,
94
+ including but not limited to software source code, documentation
95
+ source, and configuration files.
96
+
97
+ "Object" form shall mean any form resulting from mechanical
98
+ transformation or translation of a Source form, including but
99
+ not limited to compiled object code, generated documentation,
100
+ and conversions to other media types.
101
+
102
+ "Work" shall mean the work of authorship, whether in Source or
103
+ Object form, made available under the License, as indicated by a
104
+ copyright notice that is included in or attached to the work
105
+ (an example is provided in the Appendix below).
106
+
107
+ "Derivative Works" shall mean any work, whether in Source or Object
108
+ form, that is based on (or derived from) the Work and for which the
109
+ editorial revisions, annotations, elaborations, or other modifications
110
+ represent, as a whole, an original work of authorship. For the purposes
111
+ of this License, Derivative Works shall not include works that remain
112
+ separable from, or merely link (or bind by name) to the interfaces of,
113
+ the Work and Derivative Works thereof.
114
+
115
+ "Contribution" shall mean any work of authorship, including
116
+ the original version of the Work and any modifications or additions
117
+ to that Work or Derivative Works thereof, that is intentionally
118
+ submitted to Licensor for inclusion in the Work by the copyright owner
119
+ or by an individual or Legal Entity authorized to submit on behalf of
120
+ the copyright owner. For the purposes of this definition, "submitted"
121
+ means any form of electronic, verbal, or written communication sent
122
+ to the Licensor or its representatives, including but not limited to
123
+ communication on electronic mailing lists, source code control systems,
124
+ and issue tracking systems that are managed by, or on behalf of, the
125
+ Licensor for the purpose of discussing and improving the Work, but
126
+ excluding communication that is conspicuously marked or otherwise
127
+ designated in writing by the copyright owner as "Not a Contribution."
128
+
129
+ "Contributor" shall mean Licensor and any individual or Legal Entity
130
+ on behalf of whom a Contribution has been received by Licensor and
131
+ subsequently incorporated within the Work.
132
+
133
+ 2. Grant of Copyright License. Subject to the terms and conditions of
134
+ this License, each Contributor hereby grants to You a perpetual,
135
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
136
+ copyright license to reproduce, prepare Derivative Works of,
137
+ publicly display, publicly perform, sublicense, and distribute the
138
+ Work and such Derivative Works in Source or Object form.
139
+
140
+ 3. Grant of Patent License. Subject to the terms and conditions of
141
+ this License, each Contributor hereby grants to You a perpetual,
142
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
143
+ (except as stated in this section) patent license to make, have made,
144
+ use, offer to sell, sell, import, and otherwise transfer the Work,
145
+ where such license applies only to those patent claims licensable
146
+ by such Contributor that are necessarily infringed by their
147
+ Contribution(s) alone or by combination of their Contribution(s)
148
+ with the Work to which such Contribution(s) was submitted. If You
149
+ institute patent litigation against any entity (including a
150
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
151
+ or a Contribution incorporated within the Work constitutes direct
152
+ or contributory patent infringement, then any patent licenses
153
+ granted to You under this License for that Work shall terminate
154
+ as of the date such litigation is filed.
155
+
156
+ 4. Redistribution. You may reproduce and distribute copies of the
157
+ Work or Derivative Works thereof in any medium, with or without
158
+ modifications, and in Source or Object form, provided that You
159
+ meet the following conditions:
160
+
161
+ (a) You must give any other recipients of the Work or
162
+ Derivative Works a copy of this License; and
163
+
164
+ (b) You must cause any modified files to carry prominent notices
165
+ stating that You changed the files; and
166
+
167
+ (c) You must retain, in the Source form of any Derivative Works
168
+ that You distribute, all copyright, patent, trademark, and
169
+ attribution notices from the Source form of the Work,
170
+ excluding those notices that do not pertain to any part of
171
+ the Derivative Works; and
172
+
173
+ (d) If the Work includes a "NOTICE" text file as part of its
174
+ distribution, then any Derivative Works that You distribute must
175
+ include a readable copy of the attribution notices contained
176
+ within such NOTICE file, excluding those notices that do not
177
+ pertain to any part of the Derivative Works, in at least one
178
+ of the following places: within a NOTICE text file distributed
179
+ as part of the Derivative Works; within the Source form or
180
+ documentation, if provided along with the Derivative Works; or,
181
+ within a display generated by the Derivative Works, if and
182
+ wherever such third-party notices normally appear. The contents
183
+ of the NOTICE file are for informational purposes only and
184
+ do not modify the License. You may add Your own attribution
185
+ notices within Derivative Works that You distribute, alongside
186
+ or as an addendum to the NOTICE text from the Work, provided
187
+ that such additional attribution notices cannot be construed
188
+ as modifying the License.
189
+
190
+ You may add Your own copyright statement to Your modifications and
191
+ may provide additional or different license terms and conditions
192
+ for use, reproduction, or distribution of Your modifications, or
193
+ for any such Derivative Works as a whole, provided Your use,
194
+ reproduction, and distribution of the Work otherwise complies with
195
+ the conditions stated in this License.
196
+
197
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
198
+ any Contribution intentionally submitted for inclusion in the Work
199
+ by You to the Licensor shall be under the terms and conditions of
200
+ this License, without any additional terms or conditions.
201
+ Notwithstanding the above, nothing herein shall supersede or modify
202
+ the terms of any separate license agreement you may have executed
203
+ with Licensor regarding such Contributions.
204
+
205
+ 6. Trademarks. This License does not grant permission to use the trade
206
+ names, trademarks, service marks, or product names of the Licensor,
207
+ except as required for reasonable and customary use in describing the
208
+ origin of the Work and reproducing the content of the NOTICE file.
209
+
210
+ 7. Disclaimer of Warranty. Unless required by applicable law or
211
+ agreed to in writing, Licensor provides the Work (and each
212
+ Contributor provides its Contributions) on an "AS IS" BASIS,
213
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
214
+ implied, including, without limitation, any warranties or conditions
215
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
216
+ PARTICULAR PURPOSE. You are solely responsible for determining the
217
+ appropriateness of using or redistributing the Work and assume any
218
+ risks associated with Your exercise of permissions under this License.
219
+
220
+ 8. Limitation of Liability. In no event and under no legal theory,
221
+ whether in tort (including negligence), contract, or otherwise,
222
+ unless required by applicable law (such as deliberate and grossly
223
+ negligent acts) or agreed to in writing, shall any Contributor be
224
+ liable to You for damages, including any direct, indirect, special,
225
+ incidental, or consequential damages of any character arising as a
226
+ result of this License or out of the use or inability to use the
227
+ Work (including but not limited to damages for loss of goodwill,
228
+ work stoppage, computer failure or malfunction, or any and all
229
+ other commercial damages or losses), even if such Contributor
230
+ has been advised of the possibility of such damages.
231
+
232
+ 9. Accepting Warranty or Additional Liability. While redistributing
233
+ the Work or Derivative Works thereof, You may choose to offer,
234
+ and charge a fee for, acceptance of support, warranty, indemnity,
235
+ or other liability obligations and/or rights consistent with this
236
+ License. However, in accepting such obligations, You may act only
237
+ on Your own behalf and on Your sole responsibility, not on behalf
238
+ of any other Contributor, and only if You agree to indemnify,
239
+ defend, and hold each Contributor harmless for any liability
240
+ incurred by, or claims asserted against, such Contributor by reason
241
+ of your accepting any such warranty or additional liability.
242
+
243
+ END OF TERMS AND CONDITIONS
244
+
245
+ APPENDIX: How to apply the Apache License to your work.
246
+
247
+ To apply the Apache License to your work, attach the following
248
+ boilerplate notice, with the fields enclosed by brackets "[]"
249
+ replaced with your own identifying information. (Don't include
250
+ the brackets!) The text should be enclosed in the appropriate
251
+ comment syntax for the file format. We also recommend that a
252
+ file or class name and description of purpose be included on the
253
+ same "printed page" as the copyright notice for easier
254
+ identification within third-party archives.
255
+
256
+ Copyright © 2023 Apple Inc.
257
+
258
+ Licensed under the Apache License, Version 2.0 (the "License");
259
+ you may not use this file except in compliance with the License.
260
+ You may obtain a copy of the License at
261
+
262
+ http://www.apache.org/licenses/LICENSE-2.0
263
+
264
+ Unless required by applicable law or agreed to in writing, software
265
+ distributed under the License is distributed on an "AS IS" BASIS,
266
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
267
+ See the License for the specific language governing permissions and
268
+ limitations under the License.
mlx-main/mlx-main/CITATION.cff ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ title: mlx
3
+ message: >-
4
+ If you use this software, please cite it using the
5
+ metadata from this file.
6
+ type: software
7
+ authors:
8
+ - given-names: Awni
9
+ family-names: Hannun
10
+ affiliation: Apple
11
+ - given-names: Jagrit
12
+ family-names: Digani
13
+ affiliation: Apple
14
+ - given-names: Angelos
15
+ family-names: Katharopoulos
16
+ affiliation: Apple
17
+ - given-names: Ronan
18
+ family-names: Collobert
19
+ affiliation: Apple
20
+ repository-code: 'https://github.com/ml-explore'
21
+ abstract: >-
22
+ MLX: efficient and flexible machine learning on Apple
23
+ silicon
24
+ license: MIT
mlx-main/mlx-main/CMakeLists.txt ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cmake_minimum_required(VERSION 3.25)
2
+
3
+ if(NOT MLX_VERSION)
4
+ file(STRINGS "mlx/version.h" _mlx_h_version REGEX "^#define MLX_VERSION_.*$")
5
+ string(REGEX MATCH "#define MLX_VERSION_MAJOR ([0-9]+)" _ "${_mlx_h_version}")
6
+ set(_major ${CMAKE_MATCH_1})
7
+ string(REGEX MATCH "#define MLX_VERSION_MINOR ([0-9]+)" _ "${_mlx_h_version}")
8
+ set(_minor ${CMAKE_MATCH_1})
9
+ string(REGEX MATCH "#define MLX_VERSION_PATCH ([0-9]+)" _ "${_mlx_h_version}")
10
+ set(_patch ${CMAKE_MATCH_1})
11
+ set(MLX_PROJECT_VERSION "${_major}.${_minor}.${_patch}")
12
+ set(MLX_VERSION ${MLX_PROJECT_VERSION})
13
+ else()
14
+ string(REGEX REPLACE "^([0-9]+\.[0-9]+\.[0-9]+).*" "\\1" MLX_PROJECT_VERSION
15
+ ${MLX_VERSION})
16
+ endif()
17
+
18
+ project(
19
+ mlx
20
+ LANGUAGES C CXX
21
+ VERSION ${MLX_PROJECT_VERSION})
22
+
23
+ # ----------------------------- Setup -----------------------------
24
+ set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
25
+ set(CMAKE_CXX_STANDARD 20)
26
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
27
+ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
28
+ set(CMAKE_INSTALL_MESSAGE NEVER)
29
+ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
30
+
31
+ # ----------------------------- Configuration -----------------------------
32
+ option(MLX_BUILD_TESTS "Build tests for mlx" ON)
33
+ option(MLX_BUILD_EXAMPLES "Build examples for mlx" ON)
34
+ option(MLX_BUILD_BENCHMARKS "Build benchmarks for mlx" OFF)
35
+ option(MLX_BUILD_PYTHON_BINDINGS "Build python bindings for mlx" OFF)
36
+ option(MLX_BUILD_METAL "Build metal backend" ON)
37
+ option(MLX_BUILD_CPU "Build cpu backend" ON)
38
+ option(MLX_BUILD_CUDA "Build cuda backend" OFF)
39
+ option(MLX_METAL_DEBUG "Enhance metal debug workflow" OFF)
40
+ option(MLX_ENABLE_X64_MAC "Enable building for x64 macOS" OFF)
41
+ option(MLX_BUILD_GGUF "Include support for GGUF format" ON)
42
+ option(MLX_BUILD_SAFETENSORS "Include support for safetensors format" ON)
43
+ option(MLX_BUILD_PYTHON_STUBS "Build stub files for python bindings" ON)
44
+ option(MLX_METAL_JIT "Use JIT compilation for Metal kernels" OFF)
45
+ option(MLX_USE_CCACHE "Use CCache for compilation cache when available" ON)
46
+ option(BUILD_SHARED_LIBS "Build mlx as a shared library" OFF)
47
+ option(USE_SYSTEM_FMT "Use system's provided fmt library" OFF)
48
+ option(USE_ASAN "Enable AddressSanitizer (ASan)" OFF)
49
+ option(USE_UBSAN "Enable UndefinedBehaviorSanitizer (UBSan)" OFF)
50
+ option(USE_TSAN "Enable ThreadSanitizer (TSan)" OFF)
51
+
52
+ # --------------------- Processor tests -------------------------
53
+ message(
54
+ STATUS
55
+ "Building MLX for ${CMAKE_SYSTEM_PROCESSOR} processor on ${CMAKE_SYSTEM_NAME}"
56
+ )
57
+
58
+ if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
59
+ if(${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86_64")
60
+ if(NOT MLX_ENABLE_X64_MAC)
61
+ message(
62
+ FATAL_ERROR
63
+ "Building for x86_64 on macOS is not supported."
64
+ " If you are on an Apple silicon system, check the build"
65
+ " documentation for possible fixes: "
66
+ "https://ml-explore.github.io/mlx/build/html/install.html#build-from-source"
67
+ )
68
+ else()
69
+ set(MLX_BUILD_METAL OFF)
70
+ message(WARNING "Building for x86_64 arch is not officially supported.")
71
+ endif()
72
+ endif()
73
+ else()
74
+ set(MLX_BUILD_METAL OFF)
75
+ endif()
76
+
77
+ if(MLX_USE_CCACHE)
78
+ find_program(CCACHE_PROGRAM ccache)
79
+ if(CCACHE_PROGRAM)
80
+ message(STATUS "Found CCache: ${CCACHE_PROGRAM}")
81
+ set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
82
+ set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
83
+ set(CMAKE_CUDA_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
84
+ endif()
85
+ endif()
86
+
87
+ if(USE_ASAN AND USE_TSAN)
88
+ message(
89
+ FATAL_ERROR
90
+ "AddressSanitizer (ASan) and ThreadSanitizer (TSan) are mutually exclusive and cannot be enabled at the same time."
91
+ )
92
+ endif()
93
+
94
+ set(SANITIZER_COMPILE_FLAGS "")
95
+ set(SANITIZER_LINK_FLAGS "")
96
+
97
+ if(USE_ASAN)
98
+ if(WIN32 AND MSVC)
99
+ list(APPEND SANITIZER_COMPILE_FLAGS /fsanitize=address)
100
+ list(APPEND SANITIZER_LINK_FLAGS /fsanitize=address)
101
+ else()
102
+ list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=address)
103
+ list(APPEND SANITIZER_LINK_FLAGS -fsanitize=address)
104
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
105
+ list(APPEND SANITIZER_LINK_FLAGS -lpthread)
106
+ endif()
107
+ endif()
108
+ endif()
109
+
110
+ if(USE_UBSAN)
111
+ if(WIN32 AND MSVC)
112
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
113
+ list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=undefined)
114
+ list(APPEND SANITIZER_LINK_FLAGS -fsanitize=undefined)
115
+ else()
116
+ message(
117
+ WARNING
118
+ "UndefinedBehaviorSanitizer (UBSan) is not directly supported via a simple flag in MSVC."
119
+ )
120
+ endif()
121
+ else()
122
+ list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=undefined)
123
+ list(APPEND SANITIZER_LINK_FLAGS -fsanitize=undefined)
124
+ endif()
125
+ endif()
126
+
127
+ if(USE_TSAN)
128
+ if(WIN32 AND MSVC)
129
+ message(
130
+ FATAL_ERROR
131
+ "ThreadSanitizer (TSan) is not supported by the MSVC compiler. Please use Clang or GCC."
132
+ )
133
+ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
134
+ message(FATAL_ERROR "ThreadSanitizer (TSan) is not supported on macOS.")
135
+ else()
136
+ list(APPEND SANITIZER_COMPILE_FLAGS -fsanitize=thread)
137
+ list(APPEND SANITIZER_LINK_FLAGS -fsanitize=thread)
138
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
139
+ list(APPEND SANITIZER_LINK_FLAGS -lpthread)
140
+ endif()
141
+ endif()
142
+ endif()
143
+
144
+ # ----------------------------- Lib -----------------------------
145
+
146
+ include(FetchContent)
147
+ # Avoid warning about DOWNLOAD_EXTRACT_TIMESTAMP in CMake 3.24:
148
+ cmake_policy(SET CMP0135 NEW)
149
+
150
+ add_library(mlx)
151
+
152
+ target_compile_options(mlx PUBLIC ${SANITIZER_COMPILE_FLAGS})
153
+ target_link_options(mlx PUBLIC ${SANITIZER_LINK_FLAGS})
154
+
155
+ if(MLX_BUILD_CUDA)
156
+ enable_language(CUDA)
157
+ find_package(CUDAToolkit REQUIRED)
158
+ find_package(CUDNN REQUIRED)
159
+ if(CUDAToolkit_VERSION VERSION_GREATER_EQUAL "13.1" AND CUDAToolkit_VERSION
160
+ VERSION_LESS "13.2")
161
+ message(FATAL_ERROR "CUDA Toolkit 13.1 is not supported.")
162
+ endif()
163
+ endif()
164
+
165
+ if(MLX_BUILD_METAL)
166
+ find_library(METAL_LIB Metal)
167
+ find_library(FOUNDATION_LIB Foundation)
168
+ find_library(QUARTZ_LIB QuartzCore)
169
+ if(METAL_LIB)
170
+ message(STATUS "Metal found ${METAL_LIB}")
171
+ else()
172
+ message(
173
+ FATAL_ERROR
174
+ "Metal not found. Set MLX_BUILD_METAL=OFF to build without GPU")
175
+ endif()
176
+
177
+ if(MLX_METAL_DEBUG)
178
+ add_compile_definitions(MLX_METAL_DEBUG)
179
+ endif()
180
+
181
+ # Throw an error if xcrun not found
182
+ execute_process(
183
+ COMMAND zsh "-c" "/usr/bin/xcrun -sdk macosx --show-sdk-version"
184
+ OUTPUT_VARIABLE MACOS_SDK_VERSION
185
+ OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
186
+
187
+ if(${MACOS_SDK_VERSION} LESS 14.0)
188
+ message(
189
+ FATAL_ERROR
190
+ "MLX requires macOS SDK >= 14.0 to be built with MLX_BUILD_METAL=ON")
191
+ endif()
192
+ message(STATUS "Building with macOS SDK version ${MACOS_SDK_VERSION}")
193
+
194
+ set(METAL_CPP_URL
195
+ https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip)
196
+
197
+ if(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "")
198
+ if(${CMAKE_OSX_DEPLOYMENT_TARGET} LESS 14.0)
199
+ message(FATAL_ERROR "MLX requires macOS >= 14.0")
200
+ endif()
201
+ set(XCRUN_FLAGS "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
202
+ endif()
203
+ execute_process(
204
+ COMMAND
205
+ zsh "-c"
206
+ "echo \"__METAL_VERSION__\" | xcrun -sdk macosx metal ${XCRUN_FLAGS} -E -x metal -P - | tail -1 | tr -d '\n'"
207
+ OUTPUT_VARIABLE MLX_METAL_VERSION COMMAND_ERROR_IS_FATAL ANY)
208
+ FetchContent_Declare(metal_cpp URL ${METAL_CPP_URL})
209
+ FetchContent_MakeAvailable(metal_cpp)
210
+ target_include_directories(
211
+ mlx PUBLIC $<BUILD_INTERFACE:${metal_cpp_SOURCE_DIR}>
212
+ $<INSTALL_INTERFACE:include/metal_cpp>)
213
+ target_link_libraries(mlx PUBLIC ${METAL_LIB} ${FOUNDATION_LIB} ${QUARTZ_LIB})
214
+ endif()
215
+
216
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
217
+ # With newer clang/gcc versions following libs are implicitly linked, but when
218
+ # building on old distributions they need to be explicitly listed.
219
+ target_link_libraries(mlx PRIVATE dl pthread)
220
+ endif()
221
+
222
+ if(WIN32)
223
+ if(MSVC)
224
+ # GGUF does not build with MSVC.
225
+ set(MLX_BUILD_GGUF OFF)
226
+ endif()
227
+ # Generate DLL and EXE in the same dir, otherwise EXE will not be able to run.
228
+ # This is only done when MLX is built as the top project.
229
+ if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
230
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
231
+ endif()
232
+ # Windows implementation of dlfcn.h APIs.
233
+ FetchContent_Declare(
234
+ dlfcn-win32
235
+ GIT_REPOSITORY https://github.com/dlfcn-win32/dlfcn-win32.git
236
+ GIT_TAG v1.4.2
237
+ EXCLUDE_FROM_ALL)
238
+ block()
239
+ set(BUILD_SHARED_LIBS OFF)
240
+ FetchContent_MakeAvailable(dlfcn-win32)
241
+ endblock()
242
+ target_include_directories(mlx PRIVATE "${dlfcn-win32_SOURCE_DIR}/src")
243
+ target_link_libraries(mlx PRIVATE dl)
244
+ endif()
245
+
246
+ if(MLX_BUILD_CPU)
247
+ find_library(ACCELERATE_LIBRARY Accelerate)
248
+ if(ACCELERATE_LIBRARY)
249
+ message(STATUS "Accelerate found ${ACCELERATE_LIBRARY}")
250
+ set(MLX_BUILD_ACCELERATE ON)
251
+ else()
252
+ message(STATUS "Accelerate not found, using default backend.")
253
+ set(MLX_BUILD_ACCELERATE OFF)
254
+ endif()
255
+
256
+ if(MLX_BUILD_ACCELERATE)
257
+ target_link_libraries(mlx PUBLIC ${ACCELERATE_LIBRARY})
258
+ add_compile_definitions(MLX_USE_ACCELERATE)
259
+ add_compile_definitions(ACCELERATE_NEW_LAPACK)
260
+ elseif(WIN32)
261
+ # Download and link prebuilt binaries of OpenBLAS. Note that we can only
262
+ # link with the dynamic library, the prebuilt binaries were built with MinGW
263
+ # so static-linking would require linking with MinGW's runtime.
264
+ FetchContent_Declare(
265
+ openblas
266
+ URL "https://github.com/OpenMathLib/OpenBLAS/releases/download/v0.3.31/OpenBLAS-0.3.31-x64.zip"
267
+ )
268
+ FetchContent_MakeAvailable(openblas)
269
+ target_link_libraries(mlx
270
+ PRIVATE "${openblas_SOURCE_DIR}/lib/libopenblas.lib")
271
+ target_include_directories(mlx PRIVATE "${openblas_SOURCE_DIR}/include")
272
+ # Make sure the DLL file is placed in the same dir with executables.
273
+ set(OPENBLAS_DLL_FILE "${openblas_SOURCE_DIR}/bin/libopenblas.dll")
274
+ add_custom_command(
275
+ TARGET mlx
276
+ POST_BUILD
277
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${OPENBLAS_DLL_FILE}
278
+ ${CMAKE_BINARY_DIR})
279
+ else()
280
+ if(${CMAKE_HOST_APPLE})
281
+ # The blas shipped in macOS SDK is not supported, search homebrew for
282
+ # openblas instead.
283
+ set(BLA_VENDOR OpenBLAS)
284
+ set(LAPACK_ROOT
285
+ "${LAPACK_ROOT};$ENV{LAPACK_ROOT};/usr/local/opt/openblas")
286
+ endif()
287
+ # Search and link with lapack.
288
+ find_package(LAPACK REQUIRED)
289
+ if(NOT LAPACK_FOUND)
290
+ message(FATAL_ERROR "Must have LAPACK installed")
291
+ endif()
292
+ find_path(LAPACK_INCLUDE_DIRS lapacke.h /usr/include /usr/local/include
293
+ /usr/local/opt/openblas/include)
294
+ message(STATUS "Lapack lib " ${LAPACK_LIBRARIES})
295
+ message(STATUS "Lapack include " ${LAPACK_INCLUDE_DIRS})
296
+ target_include_directories(mlx PRIVATE ${LAPACK_INCLUDE_DIRS})
297
+ target_link_libraries(mlx PRIVATE ${LAPACK_LIBRARIES})
298
+ # List blas after lapack otherwise we may accidentally incldue an old
299
+ # version of lapack.h from the include dirs of blas.
300
+ find_package(BLAS REQUIRED)
301
+ if(NOT BLAS_FOUND)
302
+ message(FATAL_ERROR "Must have BLAS installed")
303
+ endif()
304
+ # TODO find a cleaner way to do this
305
+ find_path(BLAS_INCLUDE_DIRS cblas.h /usr/include /usr/local/include
306
+ $ENV{BLAS_HOME}/include)
307
+ message(STATUS "Blas lib " ${BLAS_LIBRARIES})
308
+ message(STATUS "Blas include " ${BLAS_INCLUDE_DIRS})
309
+ target_include_directories(mlx PRIVATE ${BLAS_INCLUDE_DIRS})
310
+ target_link_libraries(mlx PRIVATE ${BLAS_LIBRARIES})
311
+ endif()
312
+ else()
313
+ set(MLX_BUILD_ACCELERATE OFF)
314
+ endif()
315
+
316
+ message(STATUS "Downloading json")
317
+ FetchContent_Declare(
318
+ json
319
+ URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)
320
+ FetchContent_MakeAvailable(json)
321
+ target_include_directories(
322
+ mlx PRIVATE $<BUILD_INTERFACE:${json_SOURCE_DIR}/single_include/nlohmann>)
323
+
324
+ # Add standalone JACCL library (RDMA over Thunderbolt distributed backend)
325
+ if(MLX_BUILD_CPU
326
+ AND ${CMAKE_SYSTEM_NAME} MATCHES "Darwin"
327
+ AND DEFINED MACOS_SDK_VERSION
328
+ AND MACOS_SDK_VERSION GREATER_EQUAL 26.2)
329
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/mlx/distributed/jaccl/lib
330
+ ${CMAKE_BINARY_DIR}/jaccl)
331
+ endif()
332
+
333
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/mlx)
334
+
335
+ target_include_directories(
336
+ mlx PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}>
337
+ $<INSTALL_INTERFACE:include>)
338
+
339
+ if(USE_SYSTEM_FMT)
340
+ find_package(fmt REQUIRED)
341
+ else()
342
+ FetchContent_Declare(
343
+ fmt
344
+ GIT_REPOSITORY https://github.com/fmtlib/fmt.git
345
+ GIT_TAG 12.1.0
346
+ EXCLUDE_FROM_ALL)
347
+ FetchContent_MakeAvailable(fmt)
348
+ endif()
349
+ target_link_libraries(mlx PRIVATE $<BUILD_INTERFACE:fmt::fmt-header-only>)
350
+
351
+ if(MLX_BUILD_PYTHON_BINDINGS)
352
+ message(STATUS "Building Python bindings.")
353
+ find_package(
354
+ Python 3.10
355
+ COMPONENTS Interpreter Development.Module
356
+ REQUIRED)
357
+ FetchContent_Declare(
358
+ nanobind
359
+ GIT_REPOSITORY https://github.com/wjakob/nanobind.git
360
+ GIT_TAG v2.12.0
361
+ GIT_SHALLOW TRUE
362
+ EXCLUDE_FROM_ALL)
363
+ FetchContent_MakeAvailable(nanobind)
364
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/python/src)
365
+ endif()
366
+
367
+ if(MLX_BUILD_TESTS)
368
+ include(CTest)
369
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/tests)
370
+ endif()
371
+
372
+ if(MLX_BUILD_EXAMPLES)
373
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/examples/cpp)
374
+ endif()
375
+
376
+ if(MLX_BUILD_BENCHMARKS)
377
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/benchmarks/cpp)
378
+ endif()
379
+
380
+ # ----------------------------- Installation -----------------------------
381
+ include(GNUInstallDirs)
382
+
383
+ if(WIN32)
384
+ # Install DLLs to the same dir with extension file (core.pyd) on Windows.
385
+ set(CMAKE_INSTALL_BINDIR ".")
386
+ if(MLX_BUILD_CPU)
387
+ # Install OpenBLAS.
388
+ install(FILES ${OPENBLAS_DLL_FILE} TYPE BIN)
389
+ endif()
390
+ endif()
391
+
392
+ # Install library
393
+ install(
394
+ TARGETS mlx
395
+ EXPORT MLXTargets
396
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
397
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
398
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
399
+ INCLUDES
400
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
401
+
402
+ # Install headers
403
+ install(
404
+ DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/mlx
405
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
406
+ COMPONENT headers
407
+ FILES_MATCHING
408
+ PATTERN "*.h"
409
+ PATTERN "backend/metal/kernels.h" EXCLUDE)
410
+
411
+ # Install metal dependencies
412
+ if(MLX_BUILD_METAL)
413
+
414
+ # Install metal cpp
415
+ install(
416
+ DIRECTORY ${metal_cpp_SOURCE_DIR}/
417
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/metal_cpp
418
+ COMPONENT metal_cpp_source)
419
+
420
+ endif()
421
+
422
+ # Install cmake config
423
+ set(MLX_CMAKE_BUILD_CONFIG ${CMAKE_BINARY_DIR}/MLXConfig.cmake)
424
+ set(MLX_CMAKE_BUILD_VERSION_CONFIG ${CMAKE_BINARY_DIR}/MLXConfigVersion.cmake)
425
+ set(MLX_CMAKE_INSTALL_MODULE_DIR share/cmake/MLX)
426
+
427
+ install(
428
+ EXPORT MLXTargets
429
+ FILE MLXTargets.cmake
430
+ DESTINATION ${MLX_CMAKE_INSTALL_MODULE_DIR})
431
+
432
+ include(CMakePackageConfigHelpers)
433
+
434
+ write_basic_package_version_file(
435
+ ${MLX_CMAKE_BUILD_VERSION_CONFIG}
436
+ COMPATIBILITY SameMajorVersion
437
+ VERSION ${MLX_VERSION})
438
+
439
+ configure_package_config_file(
440
+ ${CMAKE_CURRENT_LIST_DIR}/mlx.pc.in ${MLX_CMAKE_BUILD_CONFIG}
441
+ INSTALL_DESTINATION ${MLX_CMAKE_INSTALL_MODULE_DIR}
442
+ NO_CHECK_REQUIRED_COMPONENTS_MACRO
443
+ PATH_VARS CMAKE_INSTALL_LIBDIR CMAKE_INSTALL_INCLUDEDIR
444
+ MLX_CMAKE_INSTALL_MODULE_DIR)
445
+
446
+ install(FILES ${MLX_CMAKE_BUILD_CONFIG} ${MLX_CMAKE_BUILD_VERSION_CONFIG}
447
+ DESTINATION ${MLX_CMAKE_INSTALL_MODULE_DIR})
448
+
449
+ install(DIRECTORY ${CMAKE_MODULE_PATH}/
450
+ DESTINATION ${MLX_CMAKE_INSTALL_MODULE_DIR})
mlx-main/mlx-main/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [opensource-conduct@group.apple.com](mailto:opensource-conduct@group.apple.com).
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
mlx-main/mlx-main/CONTRIBUTING.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to MLX
2
+
3
+ We want to make contributing to this project as easy and transparent as
4
+ possible.
5
+
6
+ ## Pull Requests
7
+
8
+ 1. Fork and submit pull requests to the repo.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If a change is likely to impact efficiency, run some of the benchmarks before
11
+ and after the change. Examples of benchmarks can be found in `benchmarks/python/`.
12
+ 4. If you've changed APIs, update the documentation.
13
+ 5. Every PR should have passing tests and at least one review.
14
+ 6. For code formatting install `pre-commit` using something like `pip install pre-commit` and run `pre-commit install`.
15
+ This should install hooks for running `black` and `clang-format` to ensure
16
+ consistent style for C++ and python code.
17
+
18
+ You can also run the formatters manually as follows:
19
+
20
+ ```shell
21
+ clang-format -i file.cpp
22
+ ```
23
+
24
+ ```shell
25
+ black file.py
26
+ ```
27
+
28
+ or run `pre-commit run --all-files` to check all files in the repo.
29
+
30
+ ## Issues
31
+
32
+ We use GitHub issues to track public bugs. Please ensure your description is
33
+ clear and has sufficient instructions to be able to reproduce the issue.
34
+
35
+ ## License
36
+
37
+ By contributing to MLX, you agree that your contributions will be licensed
38
+ under the LICENSE file in the root directory of this source tree.
mlx-main/mlx-main/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright © 2023 Apple Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mlx-main/mlx-main/MANIFEST.in ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ include CMakeLists.txt
2
+ include mlx.pc.in
3
+ recursive-include mlx/ *
4
+ include cmake/*
5
+ include python/src/*
6
+ include python/mlx/py.typed # support type hinting as in PEP-561
mlx-main/mlx-main/README.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MLX
2
+
3
+ [**Quickstart**](#quickstart) | [**Installation**](#installation) |
4
+ [**Documentation**](https://ml-explore.github.io/mlx/build/html/index.html) |
5
+ [**Examples**](#examples)
6
+
7
+ [![CircleCI](https://circleci.com/gh/ml-explore/mlx.svg?style=svg)](https://circleci.com/gh/ml-explore/mlx)
8
+
9
+ MLX is an array framework for machine learning on Apple silicon,
10
+ brought to you by Apple machine learning research.
11
+
12
+ Some key features of MLX include:
13
+
14
+ - **Familiar APIs**: MLX has a Python API that closely follows NumPy. MLX
15
+ also has fully featured C++, [C](https://github.com/ml-explore/mlx-c), and
16
+ [Swift](https://github.com/ml-explore/mlx-swift/) APIs, which closely mirror
17
+ the Python API. MLX has higher-level packages like `mlx.nn` and
18
+ `mlx.optimizers` with APIs that closely follow PyTorch to simplify building
19
+ more complex models.
20
+
21
+ - **Composable function transformations**: MLX supports composable function
22
+ transformations for automatic differentiation, automatic vectorization,
23
+ and computation graph optimization.
24
+
25
+ - **Lazy computation**: Computations in MLX are lazy. Arrays are only
26
+ materialized when needed.
27
+
28
+ - **Dynamic graph construction**: Computation graphs in MLX are constructed
29
+ dynamically. Changing the shapes of function arguments does not trigger
30
+ slow compilations, and debugging is simple and intuitive.
31
+
32
+ - **Multi-device**: Operations can run on any of the supported devices
33
+ (currently the CPU and the GPU).
34
+
35
+ - **Unified memory**: A notable difference from MLX and other frameworks
36
+ is the *unified memory model*. Arrays in MLX live in shared memory.
37
+ Operations on MLX arrays can be performed on any of the supported
38
+ device types without transferring data.
39
+
40
+ MLX is designed by machine learning researchers for machine learning
41
+ researchers. The framework is intended to be user-friendly, but still efficient
42
+ to train and deploy models. The design of the framework itself is also
43
+ conceptually simple. We intend to make it easy for researchers to extend and
44
+ improve MLX with the goal of quickly exploring new ideas.
45
+
46
+ The design of MLX is inspired by frameworks like
47
+ [NumPy](https://numpy.org/doc/stable/index.html),
48
+ [PyTorch](https://pytorch.org/), [Jax](https://github.com/google/jax), and
49
+ [ArrayFire](https://arrayfire.org/).
50
+
51
+ ## Examples
52
+
53
+ The [MLX examples repo](https://github.com/ml-explore/mlx-examples) has a
54
+ variety of examples, including:
55
+
56
+ - [Transformer language model](https://github.com/ml-explore/mlx-examples/tree/main/transformer_lm) training.
57
+ - Large-scale text generation with
58
+ [LLaMA](https://github.com/ml-explore/mlx-examples/tree/main/llms/llama) and
59
+ finetuning with [LoRA](https://github.com/ml-explore/mlx-examples/tree/main/lora).
60
+ - Generating images with [Stable Diffusion](https://github.com/ml-explore/mlx-examples/tree/main/stable_diffusion).
61
+ - Speech recognition with [OpenAI's Whisper](https://github.com/ml-explore/mlx-examples/tree/main/whisper).
62
+
63
+ ## Quickstart
64
+
65
+ See the [quick start
66
+ guide](https://ml-explore.github.io/mlx/build/html/usage/quick_start.html)
67
+ in the documentation.
68
+
69
+ ## Installation
70
+
71
+ MLX is available on [PyPI](https://pypi.org/project/mlx/). To install MLX on
72
+ macOS, run:
73
+
74
+ ```bash
75
+ pip install mlx
76
+ ```
77
+
78
+ To install the CUDA backend on Linux, run:
79
+
80
+ ```bash
81
+ pip install mlx[cuda]
82
+ ```
83
+
84
+ To install a CPU-only Linux package, run:
85
+
86
+ ```bash
87
+ pip install mlx[cpu]
88
+ ```
89
+
90
+ Checkout the
91
+ [documentation](https://ml-explore.github.io/mlx/build/html/install.html#)
92
+ for more information on building the C++ and Python APIs from source.
93
+
94
+ ## Contributing
95
+
96
+ Check out the [contribution guidelines](https://github.com/ml-explore/mlx/tree/main/CONTRIBUTING.md) for more information
97
+ on contributing to MLX. See the
98
+ [docs](https://ml-explore.github.io/mlx/build/html/install.html) for more
99
+ information on building from source, and running tests.
100
+
101
+ We are grateful for all of [our
102
+ contributors](https://github.com/ml-explore/mlx/tree/main/ACKNOWLEDGMENTS.md#Individual-Contributors). If you contribute
103
+ to MLX and wish to be acknowledged, please add your name to the list in your
104
+ pull request.
105
+
106
+ ## Citing MLX
107
+
108
+ The MLX software suite was initially developed with equal contribution by Awni
109
+ Hannun, Jagrit Digani, Angelos Katharopoulos, and Ronan Collobert. If you find
110
+ MLX useful in your research and wish to cite it, please use the following
111
+ BibTex entry:
112
+
113
+ ```text
114
+ @software{mlx2023,
115
+ author = {Awni Hannun and Jagrit Digani and Angelos Katharopoulos and Ronan Collobert},
116
+ title = {{MLX}: Efficient and flexible machine learning on Apple silicon},
117
+ url = {https://github.com/ml-explore},
118
+ version = {0.0},
119
+ year = {2023},
120
+ }
121
+ ```
mlx-main/mlx-main/benchmarks/cpp/CMakeLists.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function(build_benchmark SRCFILE)
2
+ get_filename_component(src_name ${SRCFILE} NAME_WE)
3
+ set(target "${src_name}")
4
+ add_executable(${target} ${SRCFILE})
5
+ target_link_libraries(${target} PRIVATE mlx)
6
+ endfunction(build_benchmark)
7
+
8
+ build_benchmark(single_ops.cpp)
9
+ build_benchmark(irregular_strides.cpp)
10
+ build_benchmark(compare_devices.cpp)
11
+ build_benchmark(autograd.cpp)
mlx-main/mlx-main/benchmarks/cpp/autograd.cpp ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #include <iostream>
4
+
5
+ #include "mlx/mlx.h"
6
+ #include "time_utils.h"
7
+
8
+ namespace mx = mlx::core;
9
+
10
+ void time_value_and_grad() {
11
+ auto x = mx::ones({200, 1000});
12
+ mx::eval(x);
13
+ auto fn = [](mx::array x) {
14
+ for (int i = 0; i < 20; ++i) {
15
+ x = mx::log(mx::exp(x));
16
+ }
17
+ return mx::sum(x);
18
+ };
19
+
20
+ auto grad_fn = mx::grad(fn);
21
+ auto independent_value_and_grad = [&]() {
22
+ auto value = fn(x);
23
+ auto dfdx = grad_fn(x);
24
+ return std::vector<mx::array>{value, dfdx};
25
+ };
26
+ TIME(independent_value_and_grad);
27
+
28
+ auto value_and_grad_fn = mx::value_and_grad(fn);
29
+ auto combined_value_and_grad = [&]() {
30
+ auto [value, dfdx] = value_and_grad_fn(x);
31
+ return std::vector<mx::array>{value, dfdx};
32
+ };
33
+ TIME(combined_value_and_grad);
34
+ }
35
+
36
+ int main() {
37
+ std::cout << "Benchmarks for " << mx::default_device() << std::endl;
38
+ time_value_and_grad();
39
+ }
mlx-main/mlx-main/benchmarks/cpp/compare_devices.cpp ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #include <iostream>
4
+ #include "mlx/mlx.h"
5
+ #include "time_utils.h"
6
+
7
+ namespace mx = mlx::core;
8
+
9
+ void time_add_op() {
10
+ std::vector<int> sizes(1, 1);
11
+ for (int i = 0; i < 9; ++i) {
12
+ sizes.push_back(10 * sizes.back());
13
+ }
14
+ set_default_device(mx::Device::cpu);
15
+ for (auto size : sizes) {
16
+ auto a = mx::random::uniform({size});
17
+ auto b = mx::random::uniform({size});
18
+ mx::eval(a, b);
19
+ std::cout << "Size " << size << std::endl;
20
+ TIMEM("cpu", mx::add, a, b, mx::Device::cpu);
21
+ TIMEM("gpu", mx::add, a, b, mx::Device::gpu);
22
+ }
23
+ }
24
+
25
+ int main() {
26
+ time_add_op();
27
+ }
mlx-main/mlx-main/benchmarks/cpp/irregular_strides.cpp ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #include <cstring>
4
+ #include <iostream>
5
+ #include <sstream>
6
+
7
+ #include "mlx/mlx.h"
8
+ #include "time_utils.h"
9
+
10
+ namespace mx = mlx::core;
11
+
12
+ void time_irregular_binary_ops_1D() {
13
+ auto device = mx::default_device();
14
+ int size = 1000000;
15
+ int step = 2;
16
+ auto a = mx::random::uniform({size});
17
+ auto b = mx::random::uniform({size});
18
+ mx::eval(a, b);
19
+ a = slice(a, {0}, {size}, {step});
20
+ b = slice(b, {0}, {size}, {step});
21
+ TIMEM("1D strided", mx::add, a, b, device);
22
+ }
23
+
24
+ void time_irregular_binary_ops_2D() {
25
+ auto device = mx::default_device();
26
+ int size = 2048;
27
+ auto a = mx::random::uniform({size, size});
28
+ auto b = mx::random::uniform({size, size});
29
+ mx::eval(a, b);
30
+ TIMEM("2D regular", mx::add, a, b, device);
31
+
32
+ b = mx::transpose(b);
33
+ mx::eval(b);
34
+ TIMEM("2D mx::transpose", mx::add, a, b, device);
35
+
36
+ b = mx::random::uniform({size});
37
+ mx::eval(b);
38
+ TIMEM("2D broadcast dim 0", mx::add, a, b, device);
39
+
40
+ b = mx::reshape(b, {size, 1});
41
+ mx::eval(b);
42
+ TIMEM("2D broadcast dim 1", mx::add, a, b, device);
43
+ }
44
+
45
+ void time_irregular_binary_ops_3D() {
46
+ auto device = mx::default_device();
47
+ int d0 = 32;
48
+ int d1 = 512;
49
+ int d2 = 512;
50
+ auto a = mx::random::uniform({d0, d1, d2});
51
+ auto b = mx::random::uniform({d0, d1, d2});
52
+ TIMEM("3D regular", mx::add, a, b, device);
53
+
54
+ b = mx::transpose(b, {0, 2, 1});
55
+ TIMEM("3D mx::transpose", mx::add, a, b, device);
56
+
57
+ b = mx::random::uniform({d1, d2});
58
+ TIMEM("3D broadcast dim 0", mx::add, a, b, device);
59
+
60
+ b = mx::random::uniform({d0, 1, d2});
61
+ TIMEM("3D broadcast dim 1", mx::add, a, b, device);
62
+
63
+ b = mx::random::uniform({d0, d1, 1});
64
+ TIMEM("3D broadcast dim 2", mx::add, a, b, device);
65
+
66
+ b = mx::random::uniform({d2});
67
+ TIMEM("3D broadcast dims 0, 1", mx::add, a, b, device);
68
+
69
+ b = mx::random::uniform({d1, 1});
70
+ TIMEM("3D broadcast dims 0, 2", mx::add, a, b, device);
71
+
72
+ b = mx::random::uniform({d0, 1, 1});
73
+ TIMEM("3D broadcast dims 1, 2", mx::add, a, b, device);
74
+ }
75
+
76
+ void time_irregular_binary_ops_4D() {
77
+ auto device = mx::default_device();
78
+ mx::Shape shape = {8, 8, 512, 512};
79
+ auto a = mx::random::uniform(shape);
80
+ auto b = mx::random::uniform(shape);
81
+
82
+ TIMEM("4D regular", mx::add, a, b, device);
83
+
84
+ b = mx::transpose(b, {0, 1, 3, 2});
85
+ TIMEM("4D mx::transpose", mx::add, a, b, device);
86
+
87
+ std::string om = "4D broadcast dims ";
88
+ for (int i = 0; i < shape.size(); ++i) {
89
+ shape[i] = 1;
90
+ b = mx::random::uniform(shape);
91
+ std::ostringstream msg;
92
+ msg << om << i;
93
+ TIMEM(msg.str(), mx::add, a, b, device);
94
+
95
+ for (int j = i + 1; j < shape.size(); ++j) {
96
+ shape[j] = 1;
97
+ std::ostringstream msg;
98
+ msg << om << i << ", " << j;
99
+ b = mx::random::uniform(shape);
100
+ TIMEM(msg.str(), mx::add, a, b, device);
101
+ shape[j] = a.shape(j);
102
+
103
+ for (int k = j + 1; k < shape.size(); ++k) {
104
+ shape[k] = 1;
105
+ std::ostringstream msg;
106
+ msg << om << i << ", " << j << ", " << k;
107
+ b = mx::random::uniform(shape);
108
+ TIMEM(msg.str(), mx::add, a, b, device);
109
+ shape[k] = a.shape(k);
110
+ }
111
+ }
112
+ shape[i] = a.shape(i);
113
+ }
114
+ }
115
+
116
+ void time_irregular_reshape() {
117
+ auto device = mx::default_device();
118
+ mx::Shape shape;
119
+ auto reshape_fn = [&shape, device](const mx::array& a) {
120
+ return mx::reshape(a, shape, device);
121
+ };
122
+
123
+ int size = 64;
124
+ int d = 2 * size;
125
+
126
+ auto a = mx::random::uniform({d, d, d});
127
+
128
+ shape = {8 * size, size, size};
129
+ TIMEM("3D contiguous", reshape_fn, a);
130
+
131
+ a = mx::transpose(a);
132
+ shape = {8 * size, size, size};
133
+ TIMEM("3D mx::transpose", reshape_fn, a);
134
+
135
+ a = mx::transpose(a, {1, 2, 0});
136
+ shape = {8 * size, size, size};
137
+ TIMEM("3D mx::transpose dims 1 2", reshape_fn, a);
138
+
139
+ a = mx::broadcast_to(mx::random::uniform({d, d}), {d, d, d});
140
+ TIMEM("3D broadcast dim 0", reshape_fn, a);
141
+
142
+ a = mx::broadcast_to(mx::random::uniform({d, 1, d}), {d, d, d});
143
+ TIMEM("3D broadcast dim 1", reshape_fn, a);
144
+
145
+ a = mx::broadcast_to(mx::random::uniform({d, d, 1}), {d, d, d});
146
+ TIMEM("3D broadcast dim 2", reshape_fn, a);
147
+
148
+ a = mx::broadcast_to(mx::random::uniform({d}), {d, d, d});
149
+ TIMEM("3D broadcast dims 0, 1", reshape_fn, a);
150
+
151
+ a = mx::broadcast_to(mx::random::uniform({d, 1}), {d, d, d});
152
+ TIMEM("3D broadcast dims 0, 2", reshape_fn, a);
153
+
154
+ a = mx::broadcast_to(mx::random::uniform({d, 1, 1}), {d, d, d});
155
+ TIMEM("3D broadcast dims 1, 2", reshape_fn, a);
156
+
157
+ a = mx::broadcast_to(mx::random::uniform({1, 1, 1}), {d, d, d});
158
+ TIMEM("3D broadcast dims 1, 2, 3", reshape_fn, a);
159
+ }
160
+
161
+ void time_irregular_astype_1D() {
162
+ auto device = mx::default_device();
163
+ int size = 1000000;
164
+ int step = 2;
165
+ auto a = mx::random::uniform({size});
166
+ a = slice(a, {0}, {size}, {step});
167
+ TIMEM("1D strided", mx::astype, a, mx::int32, device);
168
+ }
169
+
170
+ void time_irregular_astype_2D() {
171
+ auto device = mx::default_device();
172
+ int size = 2048;
173
+ mx::Shape shape = {size, size};
174
+
175
+ auto a = mx::random::uniform(shape);
176
+ TIMEM("2D regular", mx::astype, a, mx::int32, device);
177
+
178
+ a = mx::transpose(a);
179
+ TIMEM("2D mx::transpose", mx::astype, a, mx::int32, device);
180
+
181
+ a = mx::broadcast_to(mx::random::uniform({size}), shape);
182
+ TIMEM("2D broadcast dim 0", mx::astype, a, mx::int32, device);
183
+
184
+ a = mx::broadcast_to(mx::random::uniform({size, 1}), shape);
185
+ TIMEM("2D broadcast dim 1", mx::astype, a, mx::int32, device);
186
+ }
187
+
188
+ int main(int argc, char** argv) {
189
+ if (argc > 1) {
190
+ bool use_gpu = !strcmp(argv[1], "gpu");
191
+ set_default_device(use_gpu ? mx::Device::gpu : mx::Device::cpu);
192
+ }
193
+ std::cout << "Benchmarks for " << mx::default_device() << std::endl;
194
+ time_irregular_binary_ops_1D();
195
+ time_irregular_binary_ops_2D();
196
+ time_irregular_binary_ops_3D();
197
+ time_irregular_binary_ops_4D();
198
+ time_irregular_reshape();
199
+ time_irregular_astype_1D();
200
+ time_irregular_astype_2D();
201
+ }
mlx-main/mlx-main/benchmarks/cpp/single_ops.cpp ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #include "mlx/mlx.h"
4
+ #include "time_utils.h"
5
+
6
+ namespace mx = mlx::core;
7
+
8
+ void time_creation_ops() {
9
+ int M = 2000;
10
+ int N = 500;
11
+ auto shape = {M, N};
12
+ auto full_fp32 = [&]() { return mx::full(shape, 3.3f); };
13
+ TIME(full_fp32);
14
+ auto zeros_fp32 = [&]() { return mx::zeros(shape, mx::float32); };
15
+ TIME(zeros_fp32);
16
+ auto ones_fp32 = [&]() { return mx::ones(shape, mx::float32); };
17
+ TIME(ones_fp32);
18
+
19
+ auto arange_fp32 = [&]() { return mx::arange(0.0, 10.0, 1e-4); };
20
+ TIME(arange_fp32);
21
+ }
22
+
23
+ void time_type_conversions() {
24
+ int M = 2000;
25
+ int N = 500;
26
+ auto shape = {M, N};
27
+ auto device = mx::default_device();
28
+
29
+ auto a = mx::zeros(shape, mx::float32);
30
+ mx::eval(a);
31
+ TIMEM("mx::float32 to mx::int32", mx::astype, a, mx::int32, device);
32
+ TIMEM("mx::float32 to mx::uint32", mx::astype, a, mx::uint32, device);
33
+
34
+ a = mx::zeros(shape, mx::int32);
35
+ mx::eval(a);
36
+ TIMEM("mx::int32 to mx::float32", mx::astype, a, mx::float32, device);
37
+
38
+ a = mx::zeros(shape, mx::bool_);
39
+ mx::eval(a);
40
+ TIMEM("bool to mx::float32", mx::astype, a, mx::float32, device);
41
+ TIMEM("bool to mx::int32", mx::astype, a, mx::int32, device);
42
+ TIMEM("bool to mx::uint32", mx::astype, a, mx::uint32, device);
43
+ }
44
+
45
+ void time_random_generation() {
46
+ int M = 2000;
47
+ int N = 500;
48
+
49
+ auto uniform = [&]() { return mx::random::uniform({M, N}, mx::float32); };
50
+ TIME(uniform);
51
+ auto normal = [&]() { return mx::random::normal({M, N}, mx::float32); };
52
+ TIME(normal);
53
+ }
54
+
55
+ void time_unary_ops() {
56
+ int M = 2000;
57
+ int N = 500;
58
+ auto device = mx::default_device();
59
+
60
+ auto a = mx::random::normal({M, N});
61
+ mx::eval(a);
62
+ TIME(mlx::core::abs, a, device);
63
+ TIME(mx::negative, a, device);
64
+ TIME(mx::sign, a, device);
65
+ TIME(mx::square, a, device);
66
+ TIME(mlx::core::sqrt, a, device);
67
+ TIME(mx::rsqrt, a, device);
68
+ TIME(mlx::core::exp, a, device);
69
+
70
+ a = mx::random::uniform({M, N});
71
+ TIME(mlx::core::log, a, device);
72
+ }
73
+
74
+ void time_binary_ops() {
75
+ int M = 1000, N = 100, K = 10;
76
+ auto condition = mx::random::randint(0, 2, {M, N, K});
77
+ auto a = mx::random::uniform({M, N, K});
78
+ auto b = mx::random::uniform({M, N, K});
79
+ auto device = mx::default_device();
80
+ mx::eval(a, b);
81
+
82
+ TIME(mx::add, a, b, device);
83
+ TIME(mx::subtract, a, b, device);
84
+ TIME(mx::multiply, a, b, device);
85
+ TIME(mx::divide, a, b, device);
86
+ TIME(mx::maximum, a, b, device);
87
+ TIME(mx::minimum, a, b, device);
88
+ TIME(mx::where, condition, a, b, device);
89
+
90
+ condition = mx::array({true});
91
+ b = mx::random::uniform({1});
92
+ mx::eval(b);
93
+ TIMEM("scalar", mx::add, a, b, device);
94
+ TIMEM("vector-scalar", mx::subtract, a, b, device);
95
+ TIMEM("scalar-vector", mx::subtract, b, a, device);
96
+ TIMEM("scalar", mx::multiply, a, b, device);
97
+ TIMEM("vector-scalar", mx::divide, a, b, device);
98
+ TIMEM("scalar-vector", mx::divide, b, a, device);
99
+ TIMEM("scalar-vector", mx::where, condition, a, b, device);
100
+
101
+ condition = mx::broadcast_to(mx::array({true}), {1000, 100});
102
+ a = mx::broadcast_to(mx::random::uniform({1}), {1000, 100});
103
+ b = mx::broadcast_to(mx::random::uniform({1}), {1000, 100});
104
+ mx::eval(a, b);
105
+ TIMEM("scalar-scalar broadcast", mx::add, a, b, device);
106
+ TIMEM("scalar-scalar broadcast", mx::subtract, a, b, device);
107
+ TIMEM("scalar-scalar broadcast", mx::multiply, a, b, device);
108
+ TIMEM("scalar-scalar broadcast", mx::divide, a, b, device);
109
+ TIMEM("scalar-scalar broadcast", mx::where, condition, a, b, device);
110
+ }
111
+
112
+ void time_strided_ops() {
113
+ int M = 50, N = 50, O = 50, P = 50;
114
+ auto a = mx::random::uniform({M, N, O, P});
115
+ auto b = mx::random::uniform({M, N, O, P});
116
+ auto device = mx::default_device();
117
+ mx::eval(a, b);
118
+ TIMEM("non-strided", mx::add, a, b, device);
119
+ a = mx::transpose(a, {1, 0, 2, 3});
120
+ b = mx::transpose(b, {3, 2, 0, 1});
121
+ mx::eval(a, b);
122
+ TIMEM("strided", mx::add, a, b, device);
123
+ }
124
+
125
+ void time_comparisons() {
126
+ int M = 1000, N = 100, K = 10;
127
+ auto a = mx::random::uniform({M, N, K});
128
+ auto b = mx::random::uniform({M, N, K});
129
+ auto device = mx::default_device();
130
+ mx::eval(a, b);
131
+ TIME(mx::equal, a, b, device);
132
+ TIME(mx::greater, a, b, device);
133
+ TIME(mx::greater_equal, a, b, device);
134
+ TIME(mx::less, a, b, device);
135
+ TIME(mx::less_equal, a, b, device);
136
+ }
137
+
138
+ void time_matvec() {
139
+ int M = 2000, N = 200;
140
+ auto a = mx::random::uniform({M, N});
141
+ auto b = mx::random::uniform({N});
142
+ auto c = mx::random::uniform({M});
143
+ mx::eval(a, b, c);
144
+ auto matvec = [&]() { return mx::matmul(a, b); };
145
+ TIME(matvec);
146
+
147
+ auto matvec_transpose = [&]() { return mx::matmul(mx::transpose(a), c); };
148
+ TIME(matvec_transpose);
149
+ }
150
+
151
+ void time_matmul() {
152
+ int M = 1000, N = 1000, K = 1000;
153
+ auto a = mx::random::uniform({M, K});
154
+ auto b = mx::random::uniform({K, N});
155
+ auto device = mx::default_device();
156
+ mx::eval(a, b);
157
+ TIME(mx::matmul, a, b, device);
158
+
159
+ auto transpose_matmul = [&]() { return mx::matmul(mx::transpose(a), b); };
160
+ TIME(transpose_matmul);
161
+ }
162
+
163
+ void time_reductions() {
164
+ auto a = mx::random::normal({10000, 1000});
165
+ mx::eval(a);
166
+ auto sum_all = [&a]() { return mx::sum(a, false); };
167
+ TIME(sum_all);
168
+
169
+ auto sum_along_0 = [&a]() { return mx::sum(a, 0, false); };
170
+ TIME(sum_along_0);
171
+
172
+ auto sum_along_1 = [&a]() { return mx::sum(a, 1, false); };
173
+ TIME(sum_along_1);
174
+
175
+ auto prod_all = [&a]() { return mx::prod(a, false); };
176
+ TIME(prod_all);
177
+
178
+ auto all_true = [&a]() { return mx::all(a, false); };
179
+ TIME(all_true);
180
+
181
+ auto all_along_0 = [&a]() { return mx::all(a, 0, false); };
182
+ TIME(all_along_0);
183
+
184
+ auto all_along_1 = [&a]() { return mx::all(a, 1, false); };
185
+ TIME(all_along_1);
186
+
187
+ auto any_true = [&a]() { return mx::any(a, false); };
188
+ TIME(any_true);
189
+
190
+ auto argmin_along_0 = [&a]() { return mx::argmin(a, 0, false); };
191
+ TIME(argmin_along_0);
192
+
193
+ auto argmin_along_1 = [&a]() { return mx::argmin(a, 1, false); };
194
+ TIME(argmin_along_1);
195
+
196
+ auto indices = mx::array({1});
197
+ auto updates = mx::reshape(mx::array({NAN}), {1, 1, 1});
198
+ std::vector<int> axes{0};
199
+ auto b = scatter(a, {indices}, updates, axes);
200
+ mx::eval(b);
201
+
202
+ auto max_along_0 = [&b]() { return mx::max(b, 0, false); };
203
+ TIME(max_along_0);
204
+ auto max_along_1 = [&b]() { return mx::max(b, 1, false); };
205
+ TIME(max_along_1);
206
+
207
+ auto min_along_0 = [&b]() { return mx::min(b, 0, false); };
208
+ TIME(min_along_0);
209
+ auto min_along_1 = [&b]() { return mx::min(b, 1, false); };
210
+ TIME(min_along_1);
211
+ }
212
+
213
+ void time_gather_scatter() {
214
+ auto a = mx::random::normal({1000, 768});
215
+ mx::eval(a);
216
+ auto indices = mx::random::randint(0, 1000, {256});
217
+ mx::eval(indices);
218
+
219
+ auto embedding_lookup = [&a, &indices]() { return mx::take(a, indices, 0); };
220
+ TIME(embedding_lookup);
221
+
222
+ indices = mx::random::randint(0, 768 * 1000, {256 * 768});
223
+ mx::eval(indices);
224
+
225
+ auto single_element_lookup = [&a, &indices]() {
226
+ return mx::take(a, indices);
227
+ };
228
+ TIME(single_element_lookup);
229
+
230
+ indices = mx::random::randint(0, 1000, {256});
231
+ auto updates = mx::random::normal({256, 1, 768});
232
+ mx::eval(indices, updates);
233
+
234
+ auto embedding_update = [&a, &indices, &updates]() {
235
+ return scatter(a, indices, updates, 0);
236
+ };
237
+ TIME(embedding_update);
238
+
239
+ auto embedding_add = [&a, &indices, &updates]() {
240
+ return scatter_add(a, indices, updates, 0);
241
+ };
242
+ TIME(embedding_add);
243
+
244
+ a = mx::reshape(a, {-1});
245
+ indices = mx::random::randint(0, 768 * 1000, {768 * 256});
246
+ updates = mx::random::normal({256 * 768, 1});
247
+ mx::eval(a, indices, updates);
248
+
249
+ auto single_element_update = [&a, &indices, &updates]() {
250
+ return scatter(a, indices, updates, 0);
251
+ };
252
+ TIME(single_element_update);
253
+
254
+ auto single_element_add = [&a, &indices, &updates]() {
255
+ return scatter_add(a, indices, updates, 0);
256
+ };
257
+ TIME(single_element_add);
258
+ }
259
+
260
+ void time_divmod() {
261
+ auto a = mx::random::normal({1000});
262
+ auto b = mx::random::normal({1000});
263
+ mx::eval({a, b});
264
+
265
+ auto divmod_fused = [&a, &b]() { return mx::divmod(a, b); };
266
+ TIME(divmod_fused);
267
+
268
+ auto divmod_separate = [&a, &b]() {
269
+ return std::vector<mx::array>{mx::floor_divide(a, b), mx::remainder(a, b)};
270
+ };
271
+ TIME(divmod_separate);
272
+ }
273
+
274
+ int main() {
275
+ std::cout << "Benchmarks for " << mx::default_device() << std::endl;
276
+ time_creation_ops();
277
+ time_type_conversions();
278
+ time_unary_ops();
279
+ time_binary_ops();
280
+ time_strided_ops();
281
+ time_random_generation();
282
+ time_comparisons();
283
+ time_matvec();
284
+ time_matmul();
285
+ time_reductions();
286
+ time_gather_scatter();
287
+ time_divmod();
288
+ }
mlx-main/mlx-main/benchmarks/cpp/time_utils.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <chrono>
6
+ #include <iomanip>
7
+ #include <iostream>
8
+
9
+ #include "mlx/mlx.h"
10
+
11
+ #define milliseconds(x) \
12
+ (std::chrono::duration_cast<std::chrono::nanoseconds>(x).count() / 1e6)
13
+ #define time_now() std::chrono::high_resolution_clock::now()
14
+
15
+ #define TIME(FUNC, ...) \
16
+ std::cout << "Timing " << #FUNC << " ... " << std::flush \
17
+ << std::setprecision(5) << time_fn(FUNC, ##__VA_ARGS__) << " msec" \
18
+ << std::endl;
19
+
20
+ #define TIMEM(MSG, FUNC, ...) \
21
+ std::cout << "Timing " << "(" << MSG << ") " << #FUNC << " ... " \
22
+ << std::flush << std::setprecision(5) \
23
+ << time_fn(FUNC, ##__VA_ARGS__) << " msec" << std::endl;
24
+
25
+ template <typename F, typename... Args>
26
+ double time_fn(F fn, Args&&... args) {
27
+ // warmup
28
+ for (int i = 0; i < 5; ++i) {
29
+ eval(fn(std::forward<Args>(args)...));
30
+ }
31
+
32
+ int num_iters = 100;
33
+ auto start = time_now();
34
+ for (int i = 0; i < num_iters; i++) {
35
+ eval(fn(std::forward<Args>(args)...));
36
+ }
37
+ auto end = time_now();
38
+ return milliseconds(end - start) / static_cast<double>(num_iters);
39
+ }
mlx-main/mlx-main/benchmarks/numpy/single_ops.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import numpy as np
4
+ from time_utils import time_fn
5
+
6
+
7
+ def time_add():
8
+ a = np.ones((100, 100, 10), dtype=np.float32)
9
+ b = np.ones((100, 100, 10), dtype=np.float32)
10
+ time_fn(np.add, a, b)
11
+
12
+
13
+ def time_matmul():
14
+ a = np.random.rand(1000, 500).astype(np.float32)
15
+ b = np.random.rand(500, 1000).astype(np.float32)
16
+ time_fn(np.matmul, a, b)
17
+
18
+
19
+ def time_exp():
20
+ a = np.random.randn(1000, 100).astype(np.float32)
21
+ time_fn(np.exp, a)
22
+
23
+
24
+ def time_take():
25
+ a = np.random.rand(10000, 500)
26
+ ids = np.random.randint(0, 10000, (20, 10))
27
+ ids = [idx.reshape(-1) for idx in np.split(ids, 20)]
28
+
29
+ def random_take():
30
+ return [np.take(a, idx, 0) for idx in ids]
31
+
32
+ time_fn(random_take)
33
+
34
+
35
+ if __name__ == "__main__":
36
+ time_add()
37
+ time_matmul()
38
+ time_exp()
39
+ time_take()
mlx-main/mlx-main/benchmarks/numpy/time_utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import time
4
+
5
+
6
+ def time_fn(fn, *args):
7
+ print(f"Timing {fn.__name__} ...", end=" ")
8
+
9
+ # warmup
10
+ for _ in range(5):
11
+ fn(*args)
12
+
13
+ num_iters = 100
14
+ tic = time.perf_counter()
15
+ for _ in range(num_iters):
16
+ x = fn(*args)
17
+ toc = time.perf_counter()
18
+
19
+ msec = 1e3 * (toc - tic) / num_iters
20
+ print(f"{msec:.5f} msec")
mlx-main/mlx-main/benchmarks/python/batch_matmul_bench.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import argparse
4
+
5
+ import mlx.core as mx
6
+ from time_utils import time_fn
7
+
8
+ B = 8
9
+ T = 1024
10
+ D = 512
11
+
12
+
13
+ def time_batch_matmul():
14
+ mx.random.seed(3)
15
+ a = mx.random.uniform(shape=(B, T, D))
16
+ b = mx.random.uniform(shape=(D, D))
17
+ c = mx.random.uniform(shape=(B, T, D))
18
+ mx.eval(a, b, c)
19
+
20
+ time_fn(mx.matmul, a, b)
21
+
22
+ def batch_vjp_first():
23
+ return mx.vjp(mx.matmul, [a, b], [c])[1][0]
24
+
25
+ time_fn(batch_vjp_first)
26
+
27
+ def batch_vjp_second():
28
+ return mx.vjp(mx.matmul, [a, b], [c])[1][1]
29
+
30
+ time_fn(batch_vjp_second)
31
+
32
+
33
+ def time_unbatch_matmul():
34
+ mx.random.seed(3)
35
+ a = mx.random.uniform(shape=(B * T, D))
36
+ b = mx.random.uniform(shape=(D, D))
37
+ c = mx.random.uniform(shape=(B * T, D))
38
+ mx.eval(a, b, c)
39
+ time_fn(mx.matmul, a, b)
40
+
41
+ def unbatch_vjp_first():
42
+ return mx.matmul(c, mx.transpose(b))
43
+
44
+ time_fn(unbatch_vjp_first)
45
+
46
+ def unbatch_vjp_second():
47
+ return mx.matmul(mx.transpose(a), c)
48
+
49
+ time_fn(unbatch_vjp_second)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ parser = argparse.ArgumentParser("MLX benchmarks.")
54
+ parser.add_argument("--gpu", action="store_true", help="Use the Metal back-end.")
55
+ args = parser.parse_args()
56
+ if args.gpu:
57
+ mx.set_default_device(mx.gpu)
58
+ else:
59
+ mx.set_default_device(mx.cpu)
60
+
61
+ time_batch_matmul()
62
+ time_unbatch_matmul()
mlx-main/mlx-main/benchmarks/python/blas/bench_gemm.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import argparse
4
+ import math
5
+ import os
6
+ import subprocess
7
+ import time
8
+
9
+ import mlx.core as mx
10
+ import numpy as np
11
+ import torch
12
+
13
+ device_name = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"])
14
+ device_name = device_name.decode("utf-8").strip("\n")
15
+
16
+ N_warmup = 8
17
+ N_iter_bench = 80
18
+ N_iter_func = 5
19
+
20
+
21
+ def bench(f, a, b):
22
+ for i in range(N_warmup):
23
+ f(a, b)
24
+ torch.mps.synchronize()
25
+
26
+ s = time.perf_counter_ns()
27
+ for i in range(N_iter_bench):
28
+ f(a, b)
29
+ e = time.perf_counter_ns()
30
+ return (e - s) * 1e-9
31
+
32
+
33
+ def gemm_nn_mlx(a, b):
34
+ ys = []
35
+ for i in range(N_iter_func):
36
+ y = a @ b
37
+ ys.append(y)
38
+ mx.eval(ys)
39
+ return ys
40
+
41
+
42
+ def gemm_nt_mlx(a, b):
43
+ ys = []
44
+ for i in range(N_iter_func):
45
+ y = a @ b.transpose((0, 2, 1))
46
+ ys.append(y)
47
+ mx.eval(ys)
48
+ return ys
49
+
50
+
51
+ def gemm_tn_mlx(a, b):
52
+ ys = []
53
+ for i in range(N_iter_func):
54
+ y = a.transpose((0, 2, 1)) @ b
55
+ ys.append(y)
56
+ mx.eval(ys)
57
+ return ys
58
+
59
+
60
+ def gemm_tt_mlx(a, b):
61
+ ys = []
62
+ for i in range(N_iter_func):
63
+ y = a.transpose((0, 2, 1)) @ b.transpose((0, 2, 1))
64
+ ys.append(y)
65
+ mx.eval(ys)
66
+ return ys
67
+
68
+
69
+ @torch.no_grad()
70
+ def gemm_nn_torch(a, b):
71
+ ys = []
72
+ for i in range(N_iter_func):
73
+ y = a @ b
74
+ ys.append(y)
75
+ torch.mps.synchronize()
76
+ return ys
77
+
78
+
79
+ @torch.no_grad()
80
+ def gemm_nt_torch(a, b):
81
+ ys = []
82
+ for i in range(N_iter_func):
83
+ y = a @ b.transpose(-1, -2)
84
+ ys.append(y)
85
+ torch.mps.synchronize()
86
+ return ys
87
+
88
+
89
+ @torch.no_grad()
90
+ def gemm_tn_torch(a, b):
91
+ ys = []
92
+ for i in range(N_iter_func):
93
+ y = a.transpose(-1, -2) @ b
94
+ ys.append(y)
95
+ torch.mps.synchronize()
96
+ return ys
97
+
98
+
99
+ @torch.no_grad()
100
+ def gemm_tt_torch(a, b):
101
+ ys = []
102
+ for i in range(N_iter_func):
103
+ y = a.transpose(-1, -2) @ b.transpose(-1, -2)
104
+ ys.append(y)
105
+ torch.mps.synchronize()
106
+ return ys
107
+
108
+
109
+ def bench_shape(B, M, N, K, np_dtype, transpose="nn"):
110
+ shape_a = (B, M, K) if transpose[0] == "n" else (B, K, M)
111
+ shape_b = (B, K, N) if transpose[1] == "n" else (B, N, K)
112
+
113
+ a_np = np.random.normal(0.0, 1.0 / math.sqrt(M + K), shape_a).astype(np_dtype)
114
+ b_np = np.random.normal(0.0, 1.0 / math.sqrt(N + K), shape_b).astype(np_dtype)
115
+
116
+ a_mx = mx.array(a_np)
117
+ b_mx = mx.array(b_np)
118
+
119
+ a_pt = torch.from_numpy(a_np).to("mps")
120
+ b_pt = torch.from_numpy(b_np).to("mps")
121
+
122
+ torch.mps.synchronize()
123
+
124
+ f_mx = {
125
+ "nn": gemm_nn_mlx,
126
+ "nt": gemm_nt_mlx,
127
+ "tn": gemm_tn_mlx,
128
+ "tt": gemm_tt_mlx,
129
+ }[transpose]
130
+
131
+ f_pt = {
132
+ "nn": gemm_nn_torch,
133
+ "nt": gemm_nt_torch,
134
+ "tn": gemm_tn_torch,
135
+ "tt": gemm_tt_torch,
136
+ }[transpose]
137
+
138
+ time_torch = bench(f_pt, a_pt, b_pt)
139
+ time_mlx = bench(f_mx, a_mx, b_mx)
140
+
141
+ t_a = (0, 1, 2) if transpose[0] == "n" else (0, 2, 1)
142
+ t_b = (0, 1, 2) if transpose[1] == "n" else (0, 2, 1)
143
+
144
+ c_mlx = a_mx.transpose(t_a) @ b_mx.transpose(t_b)
145
+ c_npy = a_np.transpose(t_a).astype(np_dtype) @ b_np.transpose(t_b).astype(np_dtype)
146
+
147
+ atol = 1e-5 if np_dtype == np.float32 else 1e-4
148
+
149
+ if not np.allclose(c_mlx, c_npy.astype(np_dtype), atol=atol):
150
+ print(
151
+ f"Failed at {(B, M, N, K)} [transpose = {transpose}] with max(|a - b|) = {np.max(np.abs(c_npy - c_mlx))}"
152
+ )
153
+
154
+ return time_mlx, time_torch
155
+
156
+
157
+ def get_gflop_count(B, M, N, K):
158
+ return float(2.0 * N_iter_bench * N_iter_func * B * M * N * K) / float(1024.0**3)
159
+
160
+
161
+ if __name__ == "__main__":
162
+ parser = argparse.ArgumentParser(description="Run gemm benchmarks")
163
+
164
+ dtypes = ("float32", "float16", "complex64")
165
+ transposes = ("nn", "nt", "tn")
166
+ shapes = (
167
+ (16, 234, 768, 3072),
168
+ (1, 64, 64, 25344),
169
+ (16, 1024, 1024, 1024),
170
+ (1, 1024, 1024, 2048),
171
+ (4, 1024, 1024, 4096),
172
+ (4, 1024, 4096, 1024),
173
+ (1, 4096, 4096, 4096),
174
+ )
175
+
176
+ for dtype in dtypes:
177
+ for transpose in transposes:
178
+ for B, M, N, K in shapes:
179
+ np_dtype = getattr(np, dtype)
180
+ time_mlx, time_torch = bench_shape(B, M, N, K, np_dtype, transpose)
181
+
182
+ gflop_count = get_gflop_count(B, M, N, K)
183
+ gflops_mx = gflop_count / (time_mlx)
184
+ gflops_pt = gflop_count / (time_torch)
185
+ diff = gflops_mx / gflops_pt - 1.0
186
+
187
+ print(
188
+ f"{B:3d}, {M:4d}, {N:4d}, {K:4d}, {dtype}, {transpose}, {gflops_pt:05.3f}, {gflops_mx:05.3f}, {100.0 * diff:+5.2f}%"
189
+ )
190
+ if gflops_pt >= 2.0 * gflops_mx:
191
+ print("ATTENTION ^^^^^^^")
mlx-main/mlx-main/benchmarks/python/blas/bench_gemv.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import os
4
+ import subprocess
5
+ import time
6
+
7
+ import matplotlib.pyplot as plt
8
+ import mlx.core as mx
9
+ import numpy as np
10
+ import torch
11
+
12
+ results_dir = "./results"
13
+
14
+ if not os.path.isdir(results_dir):
15
+ os.mkdir(results_dir)
16
+
17
+ device_name = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"])
18
+ device_name = device_name.decode("utf-8").strip("\n")
19
+
20
+ N_warmup = 5
21
+ N_iter_bench = 50
22
+ N_iter_func = 20
23
+
24
+ out_vec_sizes = [128, 512, 2048, 4096]
25
+ in_vec_sizes = [128, 512, 2048, 4096]
26
+
27
+ benchmark_vector_lens = []
28
+ benchmark_vector_lens += [(i + 1) * 4096 for i in range(8)][::2]
29
+ benchmark_vector_lens += [(i + 1) * 4095 for i in range(8)][::2]
30
+ benchmark_vector_lens += [(i + 1) * 4097 for i in range(8)][::2]
31
+ benchmark_vector_lens += [64, 128, 512, 1024, 2048, 11008, 32000]
32
+
33
+ benchmark_vector_lens.sort()
34
+
35
+
36
+ def bench(f, m, v):
37
+ for i in range(N_warmup):
38
+ f(m, v)
39
+ torch.mps.synchronize()
40
+
41
+ s = time.perf_counter_ns()
42
+ for i in range(N_iter_bench):
43
+ f(m, v)
44
+ e = time.perf_counter_ns()
45
+ return (e - s) * 1e-9
46
+
47
+
48
+ def gemv_mlx(m, v):
49
+ ys = []
50
+ for i in range(N_iter_func):
51
+ y = m @ v
52
+ ys.append(y)
53
+ mx.eval(ys)
54
+ return ys
55
+
56
+
57
+ def gemv_t_mlx(m, v):
58
+ ys = []
59
+ for i in range(N_iter_func):
60
+ y = v @ m
61
+ ys.append(y)
62
+ mx.eval(ys)
63
+ return ys
64
+
65
+
66
+ @torch.no_grad()
67
+ def gemv_torch(m, v):
68
+ ys = []
69
+ for i in range(N_iter_func):
70
+ y = m @ v
71
+ ys.append(y)
72
+ torch.mps.synchronize()
73
+ return ys
74
+
75
+
76
+ @torch.no_grad()
77
+ def gemv_t_torch(m, v):
78
+ ys = []
79
+ for i in range(N_iter_func):
80
+ y = v @ m
81
+ ys.append(y)
82
+ torch.mps.synchronize()
83
+ return ys
84
+
85
+
86
+ def bench_lens(in_vec_len, out_vec_len, np_dtype, transpose=False):
87
+ shape_mat = (in_vec_len, out_vec_len) if transpose else (out_vec_len, in_vec_len)
88
+ shape_vec = (1, in_vec_len) if transpose else (in_vec_len, 1)
89
+
90
+ mat_npy = np.random.normal(0.0, 2.0 / in_vec_len, shape_mat).astype(np_dtype)
91
+ vec_npy = np.random.normal(0.0, 2.0 / in_vec_len, shape_vec).astype(np_dtype)
92
+ mat_mlx = mx.array(mat_npy)
93
+ vec_mlx = mx.array(vec_npy)
94
+ mat_trc = torch.from_numpy(mat_npy).to("mps")
95
+ vec_trc = torch.from_numpy(vec_npy).to("mps")
96
+
97
+ torch.mps.synchronize()
98
+
99
+ time_torch = (
100
+ bench(gemv_t_torch, mat_trc, vec_trc)
101
+ if transpose
102
+ else bench(gemv_torch, mat_trc, vec_trc)
103
+ )
104
+ time_mlx = (
105
+ bench(gemv_t_mlx, mat_mlx, vec_mlx)
106
+ if transpose
107
+ else bench(gemv_mlx, mat_mlx, vec_mlx)
108
+ )
109
+
110
+ c_mlx = (
111
+ np.asarray(vec_mlx @ mat_mlx) if transpose else np.asarray(mat_mlx @ vec_mlx)
112
+ )
113
+ c_npy = (vec_npy @ mat_npy) if transpose else (mat_npy @ vec_npy)
114
+
115
+ if not np.allclose(c_mlx, c_npy, atol=2e-5):
116
+ print(
117
+ f"Failed at {shape_mat} [transpose = {transpose}] with max(|a - b|) = {np.max(np.abs(c_npy - c_mlx))}"
118
+ )
119
+
120
+ return time_mlx, time_torch
121
+
122
+
123
+ def get_gflop_count(in_vec_len, out_vec_len):
124
+ return float(2.0 * N_iter_bench * N_iter_func * in_vec_len * out_vec_len) / float(
125
+ 1024**3
126
+ )
127
+
128
+
129
+ def get_gbyte_size(in_vec_len, out_vec_len, np_dtype):
130
+ n_elem = in_vec_len * out_vec_len + in_vec_len + out_vec_len
131
+ item_size = 4 if np_dtype == np.float32 else 2
132
+ return float(N_iter_bench * N_iter_func * n_elem * item_size) / float(1024**3)
133
+
134
+
135
+ def bench_with_in_len(ax, in_vec_len, out_vector_lens, dtype, transpose):
136
+ np_dtype = getattr(np, dtype)
137
+ mlx_gb_s = []
138
+ mlx_gflops = []
139
+ pyt_gb_s = []
140
+ pyt_gflops = []
141
+
142
+ for out_vec_len in out_vector_lens:
143
+ gflop_count = get_gflop_count(in_vec_len, out_vec_len)
144
+ gbyte_size = get_gbyte_size(in_vec_len, out_vec_len, np_dtype)
145
+
146
+ time_mlx, time_torch = bench_lens(in_vec_len, out_vec_len, np_dtype, transpose)
147
+
148
+ mlx_gb_s.append(gbyte_size / time_mlx)
149
+ pyt_gb_s.append(gbyte_size / time_torch)
150
+
151
+ mlx_gflops.append(gflop_count / time_mlx)
152
+ pyt_gflops.append(gflop_count / time_torch)
153
+
154
+ if transpose:
155
+ title = f"gemv_t ([1, {in_vec_len}] [{in_vec_len}, out_vec_len]) | {dtype}"
156
+ else:
157
+ title = f"gemv ([out_vec_len, {in_vec_len}] X [{in_vec_len}, 1] ) | {dtype}"
158
+
159
+ ax.plot(out_vector_lens, mlx_gb_s, "tab:blue", label="MLX")
160
+ ax.plot(out_vector_lens, pyt_gb_s, "tab:red", label="Torch")
161
+ ax.set_title(title)
162
+ ax.set(xlabel="out_vector_len", ylabel="Performance (GB/s)")
163
+ ax.legend()
164
+
165
+
166
+ def bench_with_out_len(ax, out_vec_len, in_vector_lens, dtype, transpose):
167
+ np_dtype = getattr(np, dtype)
168
+ mlx_gb_s = []
169
+ mlx_gflops = []
170
+ pyt_gb_s = []
171
+ pyt_gflops = []
172
+
173
+ for in_vec_len in in_vector_lens:
174
+ gflop_count = get_gflop_count(in_vec_len, out_vec_len)
175
+ gbyte_size = get_gbyte_size(in_vec_len, out_vec_len, np_dtype)
176
+
177
+ time_mlx, time_torch = bench_lens(in_vec_len, out_vec_len, np_dtype, transpose)
178
+
179
+ mlx_gb_s.append(gbyte_size / time_mlx)
180
+ pyt_gb_s.append(gbyte_size / time_torch)
181
+
182
+ mlx_gflops.append(gflop_count / time_mlx)
183
+ pyt_gflops.append(gflop_count / time_torch)
184
+
185
+ if transpose:
186
+ title = f"([1, in_vec_len] [in_vec_len, {out_vec_len}])"
187
+ else:
188
+ title = f"([{out_vec_len}, in_vec_len] X [in_vec_len, 1] )"
189
+
190
+ ax.plot(in_vector_lens, mlx_gb_s, "tab:blue", label="MLX")
191
+ ax.plot(in_vector_lens, pyt_gb_s, "tab:red", label="Torch")
192
+ ax.set_title(title)
193
+ ax.set(xlabel="in_vector_len", ylabel="Performance (GB/s)")
194
+ ax.legend()
195
+
196
+
197
+ for transpose in (False, True):
198
+ for dtype in ("float32", "float16", "complex64"):
199
+ fig, axs = plt.subplots(
200
+ len(in_vec_sizes), 2, figsize=(8.5, 11), layout="constrained"
201
+ )
202
+
203
+ for i, in_vec_len in enumerate(in_vec_sizes):
204
+ bench_with_in_len(
205
+ axs[i][0], in_vec_len, benchmark_vector_lens, dtype, transpose
206
+ )
207
+
208
+ for i, out_vec_len in enumerate(out_vec_sizes):
209
+ bench_with_out_len(
210
+ axs[i][1], out_vec_len, benchmark_vector_lens, dtype, transpose
211
+ )
212
+
213
+ op_name = "gemv_t" if transpose else "gemv"
214
+ fig.suptitle(f"{device_name}: {dtype} {op_name}")
215
+ fig.savefig(
216
+ os.path.join(
217
+ results_dir, f"{device_name.replace(' ', '_')}_{dtype}_{op_name}.pdf"
218
+ )
219
+ )
220
+ plt.close(fig)
mlx-main/mlx-main/benchmarks/python/block_masked_mm_bench.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2025 Apple Inc.
2
+
3
+ import argparse
4
+ import time
5
+
6
+ import mlx.core as mx
7
+ import numpy as np
8
+
9
+ MLX_DTYPES = {
10
+ "float16": mx.float16,
11
+ "bfloat16": mx.bfloat16,
12
+ "float32": mx.float32,
13
+ }
14
+
15
+
16
+ def parse_cases(cases):
17
+ parsed = []
18
+ for spec in cases.split(","):
19
+ parts = spec.split("x")
20
+ m, n, k, bs = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3])
21
+ sparsity = float(parts[4]) if len(parts) > 4 else 0.5
22
+ parsed.append((m, n, k, bs, sparsity))
23
+ return parsed
24
+
25
+
26
+ def make_masks(m, n, k, block_size, sparsity, rng):
27
+ """Create block masks with given sparsity (fraction of blocks zeroed)."""
28
+ tm = (m + block_size - 1) // block_size
29
+ tn = (n + block_size - 1) // block_size
30
+ tk = (k + block_size - 1) // block_size
31
+
32
+ lhs_mask = (rng.random((tm, tk)) >= sparsity).astype(np.bool_)
33
+ rhs_mask = (rng.random((tk, tn)) >= sparsity).astype(np.bool_)
34
+ out_mask = (rng.random((tm, tn)) >= sparsity).astype(np.bool_)
35
+ return lhs_mask, rhs_mask, out_mask
36
+
37
+
38
+ def mlx_naive_block_masked_mm(a, b, block_size, out_mask, lhs_mask, rhs_mask):
39
+ """MLX naive: expand masks and use regular matmul."""
40
+ M, K = a.shape[-2], a.shape[-1]
41
+ N = b.shape[-1]
42
+
43
+ def expand(mask, rows, cols):
44
+ e = mx.repeat(mx.repeat(mask, block_size, axis=-2), block_size, axis=-1)
45
+ return e[..., :rows, :cols]
46
+
47
+ a_masked = a * expand(lhs_mask, M, K)
48
+ b_masked = b * expand(rhs_mask, K, N)
49
+ c = a_masked @ b_masked
50
+ c = c * expand(out_mask, M, N)
51
+ return c
52
+
53
+
54
+ def bench_mlx(fn, warmup, iters):
55
+ for _ in range(warmup):
56
+ y = fn()
57
+ mx.eval(y)
58
+ mx.synchronize()
59
+
60
+ start = time.perf_counter()
61
+ for _ in range(iters):
62
+ y = fn()
63
+ mx.eval(y)
64
+ mx.synchronize()
65
+ return (time.perf_counter() - start) * 1e3 / iters
66
+
67
+
68
+ def print_table(headers, rows):
69
+ widths = [len(h) for h in headers]
70
+ for row in rows:
71
+ for i, cell in enumerate(row):
72
+ widths[i] = max(widths[i], len(cell))
73
+
74
+ def fmt_row(row):
75
+ return (
76
+ "| "
77
+ + " | ".join(f"{cell:<{widths[i]}}" for i, cell in enumerate(row))
78
+ + " |"
79
+ )
80
+
81
+ sep = "|-" + "-|-".join("-" * w for w in widths) + "-|"
82
+ print(fmt_row(headers))
83
+ print(sep)
84
+ for row in rows:
85
+ print(fmt_row(row))
86
+
87
+
88
+ def main():
89
+ parser = argparse.ArgumentParser(
90
+ description="Benchmark block_masked_mm vs naive expand+matmul"
91
+ )
92
+ parser.add_argument(
93
+ "--cases",
94
+ default=(
95
+ "256x256x256x32x0.5,"
96
+ "512x512x512x32x0.5,"
97
+ "1024x1024x1024x32x0.5,"
98
+ "1024x1024x1024x64x0.5,"
99
+ "2048x2048x2048x64x0.5,"
100
+ "256x256x256x32x0.0,"
101
+ "1024x1024x1024x32x0.0,"
102
+ "1024x1024x1024x32x0.9"
103
+ ),
104
+ help="Comma-separated MxNxKxBSxSparsity list. Sparsity=fraction of blocks zeroed.",
105
+ )
106
+ parser.add_argument(
107
+ "--dtype",
108
+ default="float32",
109
+ choices=["float16", "bfloat16", "float32"],
110
+ )
111
+ parser.add_argument("--warmup", type=int, default=10)
112
+ parser.add_argument("--iters", type=int, default=50)
113
+ parser.add_argument("--seed", type=int, default=42)
114
+ parser.add_argument("--no-check", action="store_true")
115
+ args = parser.parse_args()
116
+
117
+ mlx_dtype = MLX_DTYPES[args.dtype]
118
+
119
+ print(f"dtype={args.dtype} warmup={args.warmup} iters={args.iters}")
120
+
121
+ headers = [
122
+ "Case (MxNxKxBS)",
123
+ "Sparsity",
124
+ "MLX ms",
125
+ "Naive ms",
126
+ "Speedup",
127
+ ]
128
+ if not args.no_check:
129
+ headers.append("Max err")
130
+ rows = []
131
+
132
+ cases = parse_cases(args.cases)
133
+ for idx, (m, n, k, bs, sparsity) in enumerate(cases):
134
+ rng = np.random.default_rng(args.seed + idx)
135
+ a_np = rng.standard_normal((m, k)).astype(np.float32)
136
+ b_np = rng.standard_normal((k, n)).astype(np.float32)
137
+ lhs_mask_np, rhs_mask_np, out_mask_np = make_masks(m, n, k, bs, sparsity, rng)
138
+
139
+ a_mx = mx.array(a_np, dtype=mlx_dtype)
140
+ b_mx = mx.array(b_np, dtype=mlx_dtype)
141
+ lhs_mask_mx = mx.array(lhs_mask_np)
142
+ rhs_mask_mx = mx.array(rhs_mask_np)
143
+ out_mask_mx = mx.array(out_mask_np)
144
+ mx.eval(a_mx, b_mx, lhs_mask_mx, rhs_mask_mx, out_mask_mx)
145
+
146
+ # Correctness check: block_masked_mm vs naive expand+matmul
147
+ err_str = ""
148
+ if not args.no_check:
149
+ y_op = mx.block_masked_mm(
150
+ a_mx, b_mx, bs, out_mask_mx, lhs_mask_mx, rhs_mask_mx
151
+ )
152
+ y_naive = mlx_naive_block_masked_mm(
153
+ a_mx, b_mx, bs, out_mask_mx, lhs_mask_mx, rhs_mask_mx
154
+ )
155
+ mx.eval(y_op, y_naive)
156
+ err = float(mx.max(mx.abs(y_op - y_naive)).item())
157
+ err_str = f"{err:.2e}"
158
+
159
+ # Benchmark
160
+ t_mlx = bench_mlx(
161
+ lambda: mx.block_masked_mm(
162
+ a_mx, b_mx, bs, out_mask_mx, lhs_mask_mx, rhs_mask_mx
163
+ ),
164
+ args.warmup,
165
+ args.iters,
166
+ )
167
+ t_naive = bench_mlx(
168
+ lambda: mlx_naive_block_masked_mm(
169
+ a_mx, b_mx, bs, out_mask_mx, lhs_mask_mx, rhs_mask_mx
170
+ ),
171
+ args.warmup,
172
+ args.iters,
173
+ )
174
+ speedup = f"{t_naive / t_mlx:.2f}x" if t_mlx > 0 else "-"
175
+
176
+ row = [
177
+ f"{m}x{n}x{k}x{bs}",
178
+ f"{sparsity:.0%}",
179
+ f"{t_mlx:.3f}",
180
+ f"{t_naive:.3f}",
181
+ speedup,
182
+ ]
183
+ if not args.no_check:
184
+ row.append(err_str)
185
+ rows.append(row)
186
+
187
+ print_table(headers, rows)
188
+ if not args.no_check:
189
+ print("err: max|block_masked_mm - naive_expand_matmul|")
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
mlx-main/mlx-main/benchmarks/python/comparative/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Microbenchmarks comparing MLX to PyTorch
2
+ ========================================
3
+
4
+ Implement the same microbenchmarks in MLX and PyTorch to compare and make a
5
+ list of the biggest possible performance improvements and/or regressions.
6
+
7
+ Run with `python bench_mlx.py sum_axis --size 8x1024x128 --axis 2 --cpu` for
8
+ instance to measure the times it takes to sum across the 3rd axis of the above
9
+ tensor on the cpu.
10
+
11
+ `compare.py` runs several benchmarks and compares the speed-up or lack thereof
12
+ in comparison to PyTorch.
13
+
14
+ Each bench script can be run with `--print-pid` to print the PID and wait for a
15
+ key in order to ease attaching a debugger.
mlx-main/mlx-main/benchmarks/python/comparative/bench_mlx.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import argparse
4
+ import math
5
+ import os
6
+ import time
7
+ from functools import partial
8
+
9
+ import mlx.core as mx
10
+ import mlx.nn as nn
11
+
12
+
13
+ def int_or_list(x):
14
+ try:
15
+ return int(x)
16
+ except ValueError:
17
+ return [int(xi) for xi in x.split(",")]
18
+
19
+
20
+ def none_or_list(x):
21
+ if x == "":
22
+ return None
23
+ else:
24
+ return [int(xi) for xi in x.split(",")]
25
+
26
+
27
+ def dtype_from_str(x):
28
+ if x == "":
29
+ return mx.float32
30
+ else:
31
+ dt = getattr(mx, x)
32
+ if not isinstance(dt, mx.Dtype):
33
+ raise ValueError(f"{x} is not an mlx dtype")
34
+ return dt
35
+
36
+
37
+ def bench(f, *args):
38
+ for i in range(10):
39
+ f(*args)
40
+
41
+ s = time.perf_counter()
42
+ for i in range(100):
43
+ f(*args)
44
+ e = time.perf_counter()
45
+ return e - s
46
+
47
+
48
+ def matmul_square(x):
49
+ y = x
50
+ for i in range(10):
51
+ y = y @ x
52
+ mx.eval(y)
53
+ return y
54
+
55
+
56
+ def matmul(x, y):
57
+ ys = []
58
+ for i in range(10):
59
+ ys.append(x @ y)
60
+ mx.eval(ys)
61
+
62
+
63
+ def _quant_matmul(x, w, s, b, transpose, group_size, bits):
64
+ ys = []
65
+ for i in range(10):
66
+ ys.append(
67
+ mx.quantized_matmul(
68
+ x, w, s, b, transpose=transpose, group_size=group_size, bits=bits
69
+ )
70
+ )
71
+ mx.eval(ys)
72
+
73
+
74
+ quant_matmul = {
75
+ "quant_matmul_32_2": partial(_quant_matmul, transpose=False, group_size=32, bits=2),
76
+ "quant_matmul_32_4": partial(_quant_matmul, transpose=False, group_size=32, bits=4),
77
+ "quant_matmul_32_8": partial(_quant_matmul, transpose=False, group_size=32, bits=8),
78
+ "quant_matmul_64_2": partial(_quant_matmul, transpose=False, group_size=64, bits=2),
79
+ "quant_matmul_64_4": partial(_quant_matmul, transpose=False, group_size=64, bits=4),
80
+ "quant_matmul_64_8": partial(_quant_matmul, transpose=False, group_size=64, bits=8),
81
+ "quant_matmul_128_2": partial(
82
+ _quant_matmul, transpose=False, group_size=128, bits=2
83
+ ),
84
+ "quant_matmul_128_4": partial(
85
+ _quant_matmul, transpose=False, group_size=128, bits=4
86
+ ),
87
+ "quant_matmul_128_8": partial(
88
+ _quant_matmul, transpose=False, group_size=128, bits=8
89
+ ),
90
+ "quant_matmul_t_32_2": partial(
91
+ _quant_matmul, transpose=True, group_size=32, bits=2
92
+ ),
93
+ "quant_matmul_t_32_4": partial(
94
+ _quant_matmul, transpose=True, group_size=32, bits=4
95
+ ),
96
+ "quant_matmul_t_32_8": partial(
97
+ _quant_matmul, transpose=True, group_size=32, bits=8
98
+ ),
99
+ "quant_matmul_t_64_2": partial(
100
+ _quant_matmul, transpose=True, group_size=64, bits=2
101
+ ),
102
+ "quant_matmul_t_64_4": partial(
103
+ _quant_matmul, transpose=True, group_size=64, bits=4
104
+ ),
105
+ "quant_matmul_t_64_8": partial(
106
+ _quant_matmul, transpose=True, group_size=64, bits=8
107
+ ),
108
+ "quant_matmul_t_128_2": partial(
109
+ _quant_matmul, transpose=True, group_size=128, bits=2
110
+ ),
111
+ "quant_matmul_t_128_4": partial(
112
+ _quant_matmul, transpose=True, group_size=128, bits=4
113
+ ),
114
+ "quant_matmul_t_128_8": partial(
115
+ _quant_matmul, transpose=True, group_size=128, bits=8
116
+ ),
117
+ }
118
+
119
+
120
+ def conv1d(x, y):
121
+ ys = []
122
+ for i in range(10):
123
+ ys.append(mx.conv1d(x, y))
124
+ mx.eval(ys)
125
+
126
+
127
+ def conv2d(x, y):
128
+ ys = []
129
+ for i in range(10):
130
+ ys.append(mx.conv2d(x, y))
131
+ mx.eval(ys)
132
+
133
+
134
+ def binary(op, x, y):
135
+ for i in range(100):
136
+ y = getattr(mx, op)(x, y)
137
+ mx.eval(y)
138
+
139
+
140
+ def reduction(op, axis, x):
141
+ ys = []
142
+ for i in range(100):
143
+ ys.append(getattr(mx, op)(x, axis=axis))
144
+ mx.eval(ys)
145
+
146
+
147
+ def sum_and_add(axis, x, y):
148
+ z = x.sum(axis=axis, keepdims=True)
149
+ for i in range(50):
150
+ z = (z + y).sum(axis=axis, keepdims=True)
151
+ mx.eval(z)
152
+
153
+
154
+ def softmax(axis, x):
155
+ ys = []
156
+ for i in range(100):
157
+ ex = mx.exp(x - mx.max(x, axis=axis, keepdims=True))
158
+ y = ex / mx.sum(ex, axis=axis, keepdims=True)
159
+ ys.append(y)
160
+ mx.eval(ys)
161
+
162
+
163
+ def softmax_fused(axis, x):
164
+ ys = []
165
+ for i in range(100):
166
+ y = mx.softmax(x, axis=axis)
167
+ ys.append(y)
168
+ mx.eval(ys)
169
+
170
+
171
+ def relu(x):
172
+ y = x
173
+ for i in range(100):
174
+ y = nn.relu(y)
175
+ mx.eval(y)
176
+
177
+
178
+ def leaky_relu(x: mx.array):
179
+ y = x
180
+ for i in range(100):
181
+ y = nn.leaky_relu(y)
182
+ mx.eval(y)
183
+
184
+
185
+ def prelu(x: mx.array):
186
+ y = x
187
+ for i in range(100):
188
+ y = nn.prelu(y, mx.ones(1))
189
+ mx.eval(y)
190
+
191
+
192
+ def softplus(x: mx.array):
193
+ y = x
194
+ for i in range(100):
195
+ y = nn.softplus(y)
196
+ mx.eval(y)
197
+
198
+
199
+ def mish(x: mx.array):
200
+ y = x
201
+ for i in range(100):
202
+ y = nn.mish(y)
203
+ mx.eval(y)
204
+
205
+
206
+ def leaky_relu(x):
207
+ y = x
208
+ for i in range(100):
209
+ y = nn.leaky_relu(y)
210
+ mx.eval(y)
211
+
212
+
213
+ def elu(x):
214
+ y = x
215
+ for i in range(100):
216
+ y = nn.elu(y)
217
+ mx.eval(y)
218
+
219
+
220
+ def relu6(x):
221
+ y = x
222
+ for i in range(100):
223
+ y = nn.relu6(y)
224
+ mx.eval(y)
225
+
226
+
227
+ def softplus(x):
228
+ y = x
229
+ for i in range(100):
230
+ y = nn.softplus(y)
231
+ mx.eval(y)
232
+
233
+
234
+ def celu(x):
235
+ y = x
236
+ for i in range(100):
237
+ y = nn.celu(y)
238
+ mx.eval(y)
239
+
240
+
241
+ def log_sigmoid(x):
242
+ y = x
243
+ for i in range(100):
244
+ y = nn.log_sigmoid(y)
245
+ mx.eval(y)
246
+
247
+
248
+ def scalar_mult(x):
249
+ y = x
250
+ for i in range(100):
251
+ y = y * (1.0 / (1 + i))
252
+ mx.eval(y)
253
+
254
+
255
+ def cross_entropy(targets, x):
256
+ ys = []
257
+ for i in range(100):
258
+ y = mx.logsumexp(x, axis=-1, keepdims=True) - mx.take_along_axis(
259
+ x, mx.reshape(targets, (-1, 1)), axis=-1
260
+ )
261
+ ys.append(mx.mean(y))
262
+ mx.eval(ys)
263
+
264
+
265
+ def logsumexp(axis, x):
266
+ ys = []
267
+ for i in range(100):
268
+ ys.append(mx.logsumexp(x, axis=axis))
269
+ mx.eval(ys)
270
+
271
+
272
+ def linear(w, b, x):
273
+ ys = []
274
+ for i in range(10):
275
+ ys.append(x @ mx.transpose(w, (1, 0)) + b)
276
+ mx.eval(ys)
277
+
278
+
279
+ def linear_fused(w, b, x):
280
+ ys = []
281
+ for i in range(10):
282
+ ys.append(mx.addmm(b, x, mx.transpose(w, (1, 0))))
283
+ mx.eval(ys)
284
+
285
+
286
+ def rope(x):
287
+ *_, N, D = x.shape
288
+ ys = []
289
+ for i in range(10):
290
+ shape = x.shape
291
+ x = mx.reshape(x, (-1, N, D))
292
+ positions = mx.arange(N)
293
+ freqs = mx.exp(mx.arange(0.0, D // 2) / math.log(10000 / (D // 2 - 1)))
294
+ theta = mx.reshape(positions, (-1, 1)) * mx.reshape(freqs, (1, -1))
295
+ costheta = mx.cos(theta)
296
+ sintheta = mx.sin(theta)
297
+ x1 = x[..., ::2]
298
+ x2 = x[..., 1::2]
299
+ rx1 = x1 * costheta - x2 * sintheta
300
+ rx2 = x1 * sintheta + x2 * costheta
301
+ y = mx.concatenate([rx1[..., None], rx2[..., None]], axis=-1)
302
+ y = mx.reshape(y, (-1, N, D))
303
+ ys.append(y)
304
+ mx.eval(ys)
305
+
306
+
307
+ def concatenate(axis, x, y):
308
+ ys = []
309
+ for i in range(10):
310
+ ys.append(mx.concatenate([x, y], axis=axis))
311
+ mx.eval(ys)
312
+
313
+
314
+ def cumsum(axis, x):
315
+ ys = []
316
+ for i in range(10):
317
+ ys.append(mx.cumsum(x, axis))
318
+ mx.eval(ys)
319
+
320
+
321
+ def sort(axis, x):
322
+ ys = []
323
+ for i in range(10):
324
+ ys.append(mx.sort(x, axis))
325
+ mx.eval(ys)
326
+
327
+
328
+ def topk(axis, x):
329
+ k = x.shape[axis] // 3
330
+ ys = []
331
+ for i in range(10):
332
+ ys.append(mx.topk(x, k, axis))
333
+ mx.eval(ys)
334
+
335
+
336
+ def step_function(x):
337
+ y = x
338
+ for i in range(100):
339
+ y = nn.step(x)
340
+ mx.eval(y)
341
+
342
+
343
+ def selu(x):
344
+ y = x
345
+ for i in range(100):
346
+ y = nn.selu(x)
347
+ mx.eval(y)
348
+
349
+
350
+ if __name__ == "__main__":
351
+ parser = argparse.ArgumentParser()
352
+ parser.add_argument("benchmark", help="Choose the benchmark to run")
353
+ parser.add_argument(
354
+ "--size",
355
+ default=[(1024, 1024)],
356
+ type=lambda x: list(map(int, x.split("x"))),
357
+ help="Set the matrix size",
358
+ action="append",
359
+ )
360
+ parser.add_argument(
361
+ "--axis",
362
+ default=[1],
363
+ type=int_or_list,
364
+ help="Set a reduction axis",
365
+ action="append",
366
+ )
367
+ parser.add_argument(
368
+ "--transpose",
369
+ type=none_or_list,
370
+ default=[],
371
+ help="Permute the matrix",
372
+ action="append",
373
+ )
374
+ parser.add_argument(
375
+ "--print-pid", action="store_true", help="Print the PID and pause"
376
+ )
377
+ parser.add_argument("--cpu", action="store_true", help="Use the CPU")
378
+ parser.add_argument(
379
+ "--fused", action="store_true", help="Use fused functions where possible"
380
+ )
381
+ parser.add_argument("--dtype", type=dtype_from_str, default=[], action="append")
382
+
383
+ args = parser.parse_args()
384
+
385
+ if len(args.size) > 1:
386
+ args.size.pop(0)
387
+ if len(args.axis) > 1:
388
+ args.axis.pop(0)
389
+
390
+ if args.cpu:
391
+ mx.set_default_device(mx.cpu)
392
+ else:
393
+ mx.set_default_device(mx.gpu)
394
+
395
+ types = args.dtype
396
+ if not types:
397
+ types = [mx.float32]
398
+ if len(types) < len(args.size):
399
+ types = types + [types[0]] * (len(args.size) - len(types))
400
+
401
+ xs = []
402
+ for size, dtype in zip(args.size, types):
403
+ xs.append(mx.random.normal(size).astype(dtype))
404
+ for i, t in enumerate(args.transpose):
405
+ if t is None:
406
+ continue
407
+ xs[i] = mx.transpose(xs[i], t)
408
+ mx.eval(xs)
409
+ x = xs[0]
410
+ axis = args.axis[0]
411
+
412
+ if args.print_pid:
413
+ print(os.getpid())
414
+ input("Press enter to run")
415
+
416
+ if args.benchmark == "matmul_square":
417
+ print(bench(matmul_square, x))
418
+
419
+ elif args.benchmark == "matmul":
420
+ print(bench(matmul, *xs))
421
+
422
+ elif args.benchmark.startswith("quant_matmul"):
423
+ print(bench(quant_matmul[args.benchmark], *xs))
424
+
425
+ elif args.benchmark == "linear":
426
+ if args.fused:
427
+ print(bench(linear_fused, *xs))
428
+ else:
429
+ print(bench(linear, *xs))
430
+
431
+ elif args.benchmark == "sum_axis":
432
+ print(bench(reduction, "sum", axis, x))
433
+
434
+ elif args.benchmark == "sum_all":
435
+ print(bench(reduction, "sum", None, x))
436
+
437
+ elif args.benchmark == "argmax":
438
+ print(bench(reduction, "argmax", axis, x))
439
+
440
+ elif args.benchmark == "add":
441
+ print(bench(binary, "add", *xs))
442
+
443
+ elif args.benchmark == "mul":
444
+ print(bench(binary, "multiply", *xs))
445
+
446
+ elif args.benchmark == "softmax":
447
+ if args.fused:
448
+ print(bench(softmax_fused, axis, x))
449
+ else:
450
+ print(bench(softmax, axis, x))
451
+
452
+ elif args.benchmark == "relu":
453
+ print(bench(relu, x))
454
+
455
+ elif args.benchmark == "elu":
456
+ print(bench(elu, x))
457
+
458
+ elif args.benchmark == "relu6":
459
+ print(bench(relu6, x))
460
+
461
+ elif args.benchmark == "celu":
462
+ print(bench(celu, x))
463
+
464
+ elif args.benchmark == "log_sigmoid":
465
+ print(bench(log_sigmoid, x))
466
+
467
+ elif args.benchmark == "leaky_relu":
468
+ print(bench(leaky_relu, x))
469
+ elif args.benchmark == "prelu":
470
+ print(bench(prelu, x))
471
+ elif args.benchmark == "softplus":
472
+ print(bench(softplus, x))
473
+ elif args.benchmark == "mish":
474
+ print(bench(mish, x))
475
+ elif args.benchmark == "scalar_mul":
476
+ print(bench(scalar_mult, x))
477
+
478
+ elif args.benchmark == "cross_entropy":
479
+ if len(size) != 2:
480
+ raise ValueError("Error: [cross_entropy] benchmark requires a 2 dim size")
481
+
482
+ targets = mx.zeros((len(x),), dtype=mx.uint32)
483
+ print(bench(cross_entropy, targets, x))
484
+
485
+ elif args.benchmark == "logsumexp":
486
+ print(bench(logsumexp, axis, x))
487
+
488
+ elif args.benchmark == "rope":
489
+ print(bench(rope, x))
490
+
491
+ elif args.benchmark == "concatenate":
492
+ print(bench(concatenate, axis, *xs))
493
+
494
+ elif args.benchmark == "cumsum":
495
+ print(bench(cumsum, axis, *xs))
496
+
497
+ elif args.benchmark == "conv1d":
498
+ print(bench(conv1d, *xs))
499
+
500
+ elif args.benchmark == "conv2d":
501
+ print(bench(conv2d, *xs))
502
+
503
+ elif args.benchmark == "sort":
504
+ print(bench(sort, axis, x))
505
+
506
+ elif args.benchmark == "topk":
507
+ print(bench(topk, axis, x))
508
+
509
+ elif args.benchmark == "step":
510
+ print(bench(step_function, x))
511
+
512
+ elif args.benchmark == "selu":
513
+ print(bench(selu, x))
514
+
515
+ elif args.benchmark == "sum_and_add":
516
+ print(bench(sum_and_add, axis, *xs))
517
+
518
+ else:
519
+ raise ValueError("Unknown benchmark")
mlx-main/mlx-main/benchmarks/python/comparative/bench_torch.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ import argparse
4
+ import os
5
+ import time
6
+
7
+ import torch
8
+ import torch.cuda
9
+ import torch.mps
10
+
11
+
12
+ def int_or_list(x):
13
+ try:
14
+ return int(x)
15
+ except ValueError:
16
+ return [int(xi) for xi in x.split(",")]
17
+
18
+
19
+ def none_or_list(x):
20
+ if x == "":
21
+ return None
22
+ else:
23
+ return [int(xi) for xi in x.split(",")]
24
+
25
+
26
+ def dtype_from_str(x):
27
+ if x == "":
28
+ return torch.float32
29
+ else:
30
+ dt = getattr(torch, x)
31
+ if not isinstance(dt, torch.dtype):
32
+ raise ValueError(f"{x} is not a torch dtype")
33
+ return dt
34
+
35
+
36
+ def bench(f, *args):
37
+ for i in range(10):
38
+ f(*args)
39
+
40
+ s = time.perf_counter()
41
+ for i in range(100):
42
+ f(*args)
43
+ e = time.perf_counter()
44
+ return e - s
45
+
46
+
47
+ def sync_if_needed(x):
48
+ if x.device == torch.device("mps"):
49
+ torch.mps.synchronize()
50
+ elif x.device == torch.device("cuda"):
51
+ torch.cuda.synchronize()
52
+
53
+
54
+ @torch.no_grad()
55
+ def matmul_square(x):
56
+ y = x
57
+ for i in range(10):
58
+ y = y @ x
59
+ sync_if_needed(x)
60
+
61
+
62
+ @torch.no_grad()
63
+ def matmul(x, y):
64
+ ys = []
65
+ for i in range(10):
66
+ ys.append(x @ y)
67
+ sync_if_needed(x)
68
+
69
+
70
+ @torch.no_grad()
71
+ def conv1d(x, y):
72
+ x = torch.transpose(x, -1, -2)
73
+ y = torch.transpose(y, -1, -2)
74
+ ys = []
75
+ for i in range(10):
76
+ ys.append(torch.nn.functional.conv1d(x, y))
77
+ sync_if_needed(x)
78
+
79
+
80
+ @torch.no_grad()
81
+ def conv2d(x, y):
82
+ x = torch.permute(x, (0, 3, 1, 2))
83
+ y = torch.permute(y, (0, 3, 1, 2))
84
+ ys = []
85
+ for i in range(10):
86
+ ys.append(torch.nn.functional.conv2d(x, y))
87
+ sync_if_needed(x)
88
+
89
+
90
+ @torch.no_grad()
91
+ def binary(op, x, y):
92
+ for i in range(100):
93
+ y = getattr(torch, op)(x, y)
94
+ sync_if_needed(x)
95
+
96
+
97
+ @torch.no_grad()
98
+ def reduction(op, axis, x):
99
+ ys = []
100
+ for i in range(100):
101
+ ys.append(getattr(x, op)(axis))
102
+ sync_if_needed(x)
103
+
104
+
105
+ @torch.no_grad()
106
+ def sum_and_add(axis, x, y):
107
+ z = x.sum(axis=axis, keepdims=True)
108
+ for i in range(50):
109
+ z = (z + y).sum(axis=axis, keepdims=True)
110
+ sync_if_needed(x)
111
+
112
+
113
+ @torch.no_grad()
114
+ def softmax(axis, x):
115
+ ys = []
116
+ for i in range(100):
117
+ ex = torch.exp(x - torch.max(x, dim=axis, keepdims=True).values)
118
+ y = ex / torch.sum(ex, dim=axis, keepdims=True)
119
+ ys.append(y)
120
+ sync_if_needed(x)
121
+
122
+
123
+ @torch.no_grad()
124
+ def softmax_fused(axis, x):
125
+ ys = []
126
+ for i in range(100):
127
+ ys.append(torch.nn.functional.softmax(x, dim=axis))
128
+ sync_if_needed(x)
129
+
130
+
131
+ @torch.no_grad()
132
+ def relu(x):
133
+ y = x
134
+ for i in range(100):
135
+ y = torch.nn.functional.relu(y)
136
+ sync_if_needed(x)
137
+
138
+
139
+ @torch.no_grad()
140
+ def leaky_relu(x):
141
+ y = x
142
+ for i in range(100):
143
+ y = torch.nn.functional.leaky_relu(y)
144
+ sync_if_needed(x)
145
+
146
+
147
+ @torch.no_grad()
148
+ def elu(x):
149
+ y = x
150
+ for i in range(100):
151
+ y = torch.nn.functional.elu(y)
152
+ sync_if_needed(x)
153
+
154
+
155
+ @torch.no_grad()
156
+ def celu(x):
157
+ y = x
158
+ for i in range(100):
159
+ y = torch.nn.functional.celu(y)
160
+ sync_if_needed(x)
161
+
162
+
163
+ @torch.no_grad()
164
+ def relu6(x):
165
+ y = x
166
+ for i in range(100):
167
+ y = torch.nn.functional.relu6(y)
168
+ sync_if_needed(x)
169
+
170
+
171
+ @torch.no_grad()
172
+ def softplus(x):
173
+ y = x
174
+ for i in range(100):
175
+ y = torch.nn.functional.softplus(y)
176
+ sync_if_needed(x)
177
+
178
+
179
+ @torch.no_grad()
180
+ def log_sigmoid(x):
181
+ y = x
182
+ for i in range(100):
183
+ y = torch.nn.functional.logsigmoid(y)
184
+ sync_if_needed(x)
185
+
186
+
187
+ @torch.no_grad()
188
+ def prelu(x: torch.Tensor) -> torch.Tensor:
189
+ y = x
190
+ for _ in range(100):
191
+ y = torch.nn.functional.prelu(y, torch.ones(1).to(y.device))
192
+ sync_if_needed(x)
193
+
194
+
195
+ @torch.no_grad()
196
+ def mish(x: torch.Tensor) -> torch.Tensor:
197
+ y = x
198
+ for _ in range(100):
199
+ y = torch.nn.functional.mish(y)
200
+ sync_if_needed(x)
201
+
202
+
203
+ @torch.no_grad()
204
+ def scalar_mult(x):
205
+ y = x
206
+ for i in range(100):
207
+ y = y * (1.0 / (1 + i))
208
+ sync_if_needed(x)
209
+
210
+
211
+ @torch.no_grad()
212
+ def cross_entropy(targets, x):
213
+ ys = []
214
+ for i in range(100):
215
+ ys.append(torch.nn.functional.cross_entropy(x, targets))
216
+ sync_if_needed(x)
217
+
218
+
219
+ @torch.no_grad()
220
+ def logsumexp(axis, x):
221
+ ys = []
222
+ for i in range(100):
223
+ ys.append(torch.logsumexp(x, dim=axis))
224
+ sync_if_needed(x)
225
+
226
+
227
+ @torch.no_grad()
228
+ def linear_fused(w, b, x):
229
+ ys = []
230
+ for i in range(10):
231
+ ys.append(torch.nn.functional.linear(x, w, b))
232
+ sync_if_needed(x)
233
+
234
+
235
+ @torch.no_grad()
236
+ def linear(w, b, x):
237
+ ys = []
238
+ for i in range(10):
239
+ ys.append((x @ torch.transpose(w, -2, -1)) + b)
240
+ sync_if_needed(x)
241
+
242
+
243
+ @torch.no_grad()
244
+ def rope(x):
245
+ *_, N, D = x.shape
246
+ ys = []
247
+ for i in range(10):
248
+ x = x.view(-1, N, D)
249
+ positions = torch.arange(N, device=x.device)
250
+ freqs = 10000 ** torch.linspace(0, 1, D // 2, device=x.device)
251
+ theta = positions[:, None] * freqs[None]
252
+ costheta = torch.cos(theta)
253
+ sintheta = torch.sin(theta)
254
+ x1 = x[..., ::2]
255
+ x2 = x[..., 1::2]
256
+ rx1 = x1 * costheta - x2 * sintheta
257
+ rx2 = x1 * sintheta + x2 * costheta
258
+ y = torch.cat([rx1[..., None], rx2[..., None]], dim=-1)
259
+ y = y.reshape(-1, N, D)
260
+ ys.append(y)
261
+ sync_if_needed(x)
262
+
263
+
264
+ @torch.no_grad()
265
+ def concatenate(axis, x, y):
266
+ ys = []
267
+ for i in range(10):
268
+ ys.append(torch.cat([x, y], dim=axis))
269
+ sync_if_needed(x)
270
+
271
+
272
+ @torch.no_grad()
273
+ def cumsum(axis, x):
274
+ ys = []
275
+ for i in range(10):
276
+ ys.append(x.cumsum(axis))
277
+ sync_if_needed(x)
278
+
279
+
280
+ @torch.no_grad()
281
+ def sort(axis, x):
282
+ ys = []
283
+ for i in range(10):
284
+ ys.append(torch.sort(x, dim=axis)[0])
285
+ sync_if_needed(x)
286
+
287
+
288
+ @torch.no_grad()
289
+ def topk(axis, x):
290
+ k = x.shape[axis] // 3
291
+ ys = []
292
+ for i in range(10):
293
+ ys.append(torch.topk(x, k, dim=axis)[0])
294
+ sync_if_needed(x)
295
+
296
+
297
+ @torch.no_grad()
298
+ def step_function(x):
299
+ y = x
300
+ for i in range(100):
301
+ y = torch.where(y < 0, 0, 1)
302
+ sync_if_needed(x)
303
+
304
+
305
+ @torch.no_grad()
306
+ def selu(x):
307
+ y = x
308
+ for i in range(100):
309
+ y = torch.nn.functional.selu(y)
310
+ sync_if_needed(x)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ parser = argparse.ArgumentParser()
315
+ parser.add_argument("benchmark", help="Choose the benchmark to run")
316
+ parser.add_argument(
317
+ "--size",
318
+ default=[(1024, 1024)],
319
+ type=lambda x: list(map(int, x.split("x"))),
320
+ help="Set the matrix size",
321
+ action="append",
322
+ )
323
+ parser.add_argument(
324
+ "--axis",
325
+ default=[1],
326
+ type=int_or_list,
327
+ help="Set a reduction axis",
328
+ action="append",
329
+ )
330
+ parser.add_argument(
331
+ "--transpose",
332
+ type=none_or_list,
333
+ default=[],
334
+ help="Permute the matrix",
335
+ action="append",
336
+ )
337
+ parser.add_argument(
338
+ "--print-pid", action="store_true", help="Print the PID and pause"
339
+ )
340
+ parser.add_argument("--cpu", action="store_true", help="Use the CPU")
341
+ parser.add_argument(
342
+ "--fused", action="store_true", help="Use fused functions where possible"
343
+ )
344
+ parser.add_argument("--dtype", type=dtype_from_str, default=[], action="append")
345
+
346
+ args = parser.parse_args()
347
+
348
+ if len(args.size) > 1:
349
+ args.size.pop(0)
350
+ if len(args.axis) > 1:
351
+ args.axis.pop(0)
352
+
353
+ torch.set_num_threads(1)
354
+ device = "mps"
355
+ if torch.cuda.is_available():
356
+ device = "cuda"
357
+ if args.cpu:
358
+ device = "cpu"
359
+
360
+ types = args.dtype
361
+ if not types:
362
+ types = [torch.float32]
363
+ if len(types) < len(args.size):
364
+ types = types + [types[0]] * (len(args.size) - len(types))
365
+
366
+ xs = []
367
+ for size, dtype in zip(args.size, types):
368
+ xs.append(torch.randn(*size).to(device).to(dtype))
369
+ for i, t in enumerate(args.transpose):
370
+ if t is None:
371
+ continue
372
+ xs[i] = xs[i].permute(*t)
373
+ x = xs[0]
374
+ axis = args.axis[0]
375
+
376
+ if args.print_pid:
377
+ print(os.getpid())
378
+ input("Press enter to run")
379
+
380
+ if args.benchmark == "matmul_square":
381
+ print(bench(matmul_square, x))
382
+
383
+ elif args.benchmark == "matmul":
384
+ print(bench(matmul, *xs))
385
+
386
+ elif args.benchmark == "linear":
387
+ if args.fused:
388
+ print(bench(linear_fused, *xs))
389
+ else:
390
+ print(bench(linear, *xs))
391
+
392
+ elif args.benchmark == "sum_axis":
393
+ print(bench(reduction, "sum", axis, x))
394
+
395
+ elif args.benchmark == "sum_all":
396
+ print(bench(reduction, "sum", None, x))
397
+
398
+ elif args.benchmark == "argmax":
399
+ print(bench(reduction, "argmax", axis, x))
400
+
401
+ elif args.benchmark == "add":
402
+ print(bench(binary, "add", *xs))
403
+
404
+ elif args.benchmark == "mul":
405
+ print(bench(binary, "mul", *xs))
406
+
407
+ elif args.benchmark == "softmax":
408
+ if args.fused:
409
+ print(bench(softmax_fused, axis, x))
410
+ else:
411
+ print(bench(softmax, axis, x))
412
+
413
+ elif args.benchmark == "relu":
414
+ print(bench(relu, x))
415
+
416
+ elif args.benchmark == "leaky_relu":
417
+ print(bench(leaky_relu, x))
418
+
419
+ elif args.benchmark == "elu":
420
+ print(bench(elu, x))
421
+
422
+ elif args.benchmark == "relu6":
423
+ print(bench(relu6, x))
424
+
425
+ elif args.benchmark == "softplus":
426
+ print(bench(softplus, x))
427
+
428
+ elif args.benchmark == "celu":
429
+ print(bench(celu, x))
430
+
431
+ elif args.benchmark == "log_sigmoid":
432
+ print(bench(log_sigmoid, x))
433
+
434
+ elif args.benchmark == "prelu":
435
+ print(bench(prelu, x))
436
+ elif args.benchmark == "mish":
437
+ print(bench(mish, x))
438
+ elif args.benchmark == "scalar_mul":
439
+ print(bench(scalar_mult, x))
440
+
441
+ elif args.benchmark == "cross_entropy":
442
+ if len(size) != 2:
443
+ raise ValueError("Error: [cross_entropy] benchmark requires a 2 dim size")
444
+
445
+ targets = torch.zeros(len(x), dtype=torch.long).to(x.device)
446
+ print(bench(cross_entropy, targets, x))
447
+
448
+ elif args.benchmark == "logsumexp":
449
+ print(bench(logsumexp, axis, x))
450
+
451
+ elif args.benchmark == "rope":
452
+ print(bench(rope, x))
453
+
454
+ elif args.benchmark == "concatenate":
455
+ print(bench(concatenate, axis, *xs))
456
+
457
+ elif args.benchmark == "cumsum":
458
+ print(bench(cumsum, axis, *xs))
459
+
460
+ elif args.benchmark == "conv1d":
461
+ print(bench(conv1d, *xs))
462
+
463
+ elif args.benchmark == "conv2d":
464
+ print(bench(conv2d, *xs))
465
+
466
+ elif args.benchmark == "sort":
467
+ print(bench(sort, axis, x))
468
+
469
+ elif args.benchmark == "topk":
470
+ print(bench(topk, axis, x))
471
+
472
+ elif args.benchmark == "step":
473
+ print(bench(step_function, x))
474
+
475
+ elif args.benchmark == "selu":
476
+ print(bench(selu, x))
477
+
478
+ elif args.benchmark == "sum_and_add":
479
+ print(bench(sum_and_add, axis, *xs))
480
+
481
+ else:
482
+ raise ValueError(f"Unknown benchmark `{args.benchmark}`.")
mlx-main/mlx-main/benchmarks/python/comparative/compare.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023 Apple Inc.
2
+
3
+ #!/usr/bin/env python
4
+
5
+ import argparse
6
+ import re
7
+ from pathlib import Path
8
+ from subprocess import run
9
+
10
+ BENCH_MLX = Path(__file__).parent / "bench_mlx.py"
11
+ BENCH_TORCH = Path(__file__).parent / "bench_torch.py"
12
+
13
+
14
+ def run_or_raise(*args, **kwargs):
15
+ try:
16
+ result = run(*args, capture_output=True, **kwargs)
17
+ return float(result.stdout)
18
+ except ValueError:
19
+ raise ValueError(
20
+ f"stdout: {result.stdout.decode()}\nstderr: {result.stderr.decode()}"
21
+ )
22
+
23
+
24
+ def compare(args):
25
+ t_mlx = run_or_raise(["python", BENCH_MLX] + args)
26
+ t_torch = run_or_raise(["python", BENCH_TORCH] + args)
27
+
28
+ print((t_torch - t_mlx) / t_torch, " ".join(args), sep="\t")
29
+
30
+
31
+ def compare_mlx_dtypes(args, dt1, dt2):
32
+ t_mlx_dt1 = run_or_raise(["python", BENCH_MLX] + args + ["--dtype", dt1])
33
+ t_mlx_dt2 = run_or_raise(["python", BENCH_MLX] + args + ["--dtype", dt2])
34
+
35
+ print((t_mlx_dt2 - t_mlx_dt1) / t_mlx_dt2, " ".join(args), sep="\t")
36
+
37
+
38
+ def make_regex_search(regexes):
39
+ compiled_regexes = list(map(re.compile, regexes))
40
+
41
+ def search(x):
42
+ return (c.search(x) is not None for c in compiled_regexes)
43
+
44
+ return search
45
+
46
+
47
+ def make_predicate(positive_filter, negative_filter):
48
+ if positive_filter is not None:
49
+ positive_filter_search = make_regex_search(positive_filter)
50
+ positive_filter = lambda x: all(positive_filter_search(x))
51
+ else:
52
+ positive_filter = lambda x: True
53
+
54
+ if negative_filter is not None:
55
+ negative_filter_search = make_regex_search(negative_filter)
56
+ negative_filter = lambda x: not any(negative_filter_search(x))
57
+ else:
58
+ negative_filter = lambda x: True
59
+
60
+ def predicate(x):
61
+ return positive_filter(x) and negative_filter(x)
62
+
63
+ return predicate
64
+
65
+
66
+ if __name__ == "__main__":
67
+ parser = argparse.ArgumentParser(description="Run comparisons against PyTorch")
68
+ parser.add_argument(
69
+ "--filter", "-f", help="Regex filter to select benchmarks", nargs="+"
70
+ )
71
+ parser.add_argument(
72
+ "--negative_filter", "-n", help="Regex filter to remove benchmarks", nargs="+"
73
+ )
74
+ parser.add_argument(
75
+ "--mlx_dtypes",
76
+ "-d",
77
+ help="Compare mlx benchmarks between the 2 provided data types",
78
+ nargs=2,
79
+ )
80
+ args, rest = parser.parse_known_args()
81
+
82
+ _filter = make_predicate(args.filter, args.negative_filter)
83
+
84
+ if args.mlx_dtypes:
85
+ compare_filtered = lambda x: (
86
+ compare_mlx_dtypes(x.split() + rest, args.mlx_dtypes[0], args.mlx_dtypes[1])
87
+ if _filter(x)
88
+ else None
89
+ )
90
+ else:
91
+ compare_filtered = lambda x: compare(x.split() + rest) if _filter(x) else None
92
+
93
+ # Binary ops
94
+ compare_filtered("add --size 10x1024x128 --size 1x1024x128 --cpu")
95
+ compare_filtered("add --size 10x1024x128 --size 1x1024x128")
96
+ compare_filtered("add --size 1024x128 --size 1x128 --cpu")
97
+ compare_filtered("add --size 1024x128 --size 1x128")
98
+ compare_filtered("add --size 1024x4096 --size 1x4096 --cpu")
99
+ compare_filtered("add --size 1024x4096 --size 1x4096")
100
+ compare_filtered("add --size 1024x4096 --size 1x1024 --transpose 1,0 --cpu")
101
+ compare_filtered("add --size 1024x4096 --size 1x1024 --transpose 1,0")
102
+ compare_filtered("add --size 1024x1024 --size 1024x1024 --cpu")
103
+ compare_filtered("add --size 1024x1024 --size 1024x1024")
104
+ compare_filtered("add --size 1024x1024 --size 1024x1024 --transpose 1,0 --cpu")
105
+ compare_filtered("add --size 1024x1024 --size 1024x1024 --transpose 1,0")
106
+ compare_filtered(
107
+ "add --size 1024x1024 --size 1024x1024 --transpose 1,0 --transpose 1,0 --cpu"
108
+ )
109
+ compare_filtered(
110
+ "add --size 1024x1024 --size 1024x1024 --transpose 1,0 --transpose 1,0"
111
+ )
112
+
113
+ # Reduction ops
114
+ compare_filtered("sum_all --size 10x1024x128 --cpu")
115
+ compare_filtered("sum_all --size 10x1024x128")
116
+ compare_filtered("sum_axis --size 16x1024x128 --axis 2 --cpu")
117
+ compare_filtered("sum_axis --size 16x1024x128 --axis 2")
118
+ compare_filtered("sum_axis --size 16x128x1024 --axis 2 --cpu")
119
+ compare_filtered("sum_axis --size 16x128x1024 --axis 2")
120
+ compare_filtered("sum_axis --size 1024x1024 --axis 1 --cpu")
121
+ compare_filtered("sum_axis --size 1024x1024 --axis 1")
122
+ compare_filtered("sum_axis --size 1024x1024 --axis 0 --cpu")
123
+ compare_filtered("sum_axis --size 1024x1024 --axis 0")
124
+ compare_filtered("sum_axis --size 16x128x1024 --axis 1 --cpu")
125
+ compare_filtered("sum_axis --size 16x128x1024 --axis 1")
126
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0 --cpu")
127
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0")
128
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,1 --cpu")
129
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,1")
130
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,2 --cpu")
131
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,2")
132
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,1 --transpose 0,2,1 --cpu")
133
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,1 --transpose 0,2,1")
134
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,2 --transpose 0,2,1 --cpu")
135
+ compare_filtered("sum_axis --size 16x128x1024 --axis 0,2 --transpose 0,2,1")
136
+ compare_filtered("argmax --size 10x1024x128 --axis 1 --cpu")
137
+ compare_filtered("argmax --size 10x1024x128 --axis 1")
138
+ compare_filtered("argmax --size 10x1024x128 --axis 2 --cpu")
139
+ compare_filtered("argmax --size 10x1024x128 --axis 2")
140
+ compare_filtered("argmax --size 1024x1024 --axis 1 --cpu")
141
+ compare_filtered("argmax --size 1024x1024 --axis 1")
142
+
143
+ # Matmul ops
144
+ compare_filtered("matmul_square --size 1024x1024")
145
+ compare_filtered("matmul_square --size 1024x1024 --cpu")
146
+ compare_filtered("matmul_square --size 16x1024x1024")
147
+ compare_filtered("matmul_square --size 16x1024x1024 --cpu")
148
+ compare_filtered(
149
+ "matmul --size 16x768x768 --size 16x768x768 --transpose= --transpose 0,2,1"
150
+ )
151
+ compare_filtered(
152
+ "matmul --size 16x768x768 --size 16x768x768 --transpose= --transpose 0,2,1 --cpu"
153
+ )
154
+ compare_filtered(
155
+ "matmul --size 16x768x128 --size 16x768x128 --transpose= --transpose 0,2,1"
156
+ )
157
+ compare_filtered(
158
+ "matmul --size 16x768x128 --size 16x768x128 --transpose= --transpose 0,2,1 --cpu"
159
+ )
160
+ compare_filtered("matmul --size 512x8192 --size 8192x512")
161
+ compare_filtered("matmul --size 512x8192 --size 8192x512 --cpu")
162
+ # compare_filtered("matmul --size 512x131072 --size 131072x512")
163
+ # compare_filtered("matmul --size 512x131072 --size 131072x512 --cpu")
164
+ compare_filtered("matmul --size 8192x512 --size 512x8192")
165
+ compare_filtered("matmul --size 8192x512 --size 512x8192 --cpu")
166
+ # compare_filtered("matmul --size 131072x512 --size 512x512")
167
+ # compare_filtered("matmul --size 131072x512 --size 512x512 --cpu")
168
+ compare_filtered("linear --size 1024x1024 --size 1024 --size 128x1024")
169
+ compare_filtered("linear --size 1024x1024 --size 1024 --size 128x1024 --cpu")
170
+ compare_filtered("linear --size 1024x1024 --size 1024 --size 128x1024 --fused")
171
+ compare_filtered(
172
+ "linear --size 1024x1024 --size 1024 --size 128x1024 --fused --cpu"
173
+ )
174
+
175
+ # Matvec ops
176
+ compare_filtered("matmul --size 1x1x4096 --size 4096x4096 --cpu")
177
+ compare_filtered("matmul --size 1x1x4096 --size 4096x4096")
178
+ compare_filtered(
179
+ "matmul --size 1x1x4096 --size 4096x4096 --transpose= --transpose 1,0 --cpu"
180
+ )
181
+ compare_filtered(
182
+ "matmul --size 1x1x4096 --size 4096x4096 --transpose= --transpose 1,0"
183
+ )
184
+ compare_filtered("matmul --size 32x1x1000 --size 32x1000x128 --cpu")
185
+ compare_filtered("matmul --size 32x1x1000 --size 32x1000x128")
186
+ compare_filtered(
187
+ "matmul --size 32x1x1000 --size 32x128x1000 --transpose= --transpose 0,2,1 --cpu"
188
+ )
189
+ compare_filtered(
190
+ "matmul --size 32x1x1000 --size 32x128x1000 --transpose= --transpose 0,2,1"
191
+ )
192
+
193
+ # Various ops
194
+ compare_filtered("softmax --size 32x16x1024 --axis 2")
195
+ compare_filtered("softmax --size 32x16x1024 --axis 2 --cpu")
196
+ compare_filtered("softmax --size 32x16x1024 --axis 2 --fused")
197
+ compare_filtered("softmax --size 32x16x1024 --axis 2 --fused --cpu")
198
+ compare_filtered("softmax --size 2x1024x1024 --axis 1")
199
+ compare_filtered("softmax --size 2x1024x1024 --axis 1 --cpu")
200
+ compare_filtered("softmax --size 2x1024x1024 --axis 1 --fused")
201
+ compare_filtered("softmax --size 2x1024x1024 --axis 1 --fused --cpu")
202
+ compare_filtered("relu --size 32x16x1024")
203
+ compare_filtered("relu --size 32x16x1024 --cpu")
204
+ compare_filtered("leaky_relu --size 32x16x1024")
205
+ compare_filtered("leaky_relu --size 32x16x1024 --cpu")
206
+ compare_filtered("elu --size 32x16x1024")
207
+ compare_filtered("elu --size 32x16x1024 --cpu")
208
+ compare_filtered("relu6 --size 32x16x1024")
209
+ compare_filtered("relu6 --size 32x16x1024 --cpu")
210
+ compare_filtered("softplus --size 32x16x1024")
211
+ compare_filtered("softplus --size 32x16x1024 --cpu")
212
+ compare_filtered("celu --size 32x16x1024")
213
+ compare_filtered("celu --size 32x16x1024 --cpu")
214
+ compare_filtered("log_sigmoid --size 32x16x1024")
215
+ compare_filtered("log_sigmoid --size 32x16x1024 --cpu")
216
+ compare_filtered("step --size 32x16x1024")
217
+ compare_filtered("step --size 32x16x1024 --cpu")
218
+ compare_filtered("selu --size 32x16x1024")
219
+ compare_filtered("selu --size 32x16x1024 --cpu")
220
+ # compare_filtered("mish --size 32x16x1024") NOTE: Torch does not implement Mish in MPS atm
221
+ compare_filtered("mish --size 32x16x1024 --cpu")
222
+ compare_filtered("prelu --size 32x16x1024")
223
+ compare_filtered("prelu --size 32x16x1024 --cpu")
224
+
225
+ compare_filtered("scalar_mul --size 32x16x1024")
226
+ compare_filtered("scalar_mul --size 32x16x1024 --cpu")
227
+ compare_filtered("cross_entropy --size 256x1024")
228
+ compare_filtered("cross_entropy --size 256x1024 --cpu")
229
+ compare_filtered("logsumexp --size 1024x1024 --axis 1")
230
+ compare_filtered("logsumexp --size 1024x1024 --axis 1 --cpu")
231
+ compare_filtered("logsumexp --size 1024x1024 --axis 0")
232
+ compare_filtered("logsumexp --size 1024x1024 --axis 0 --cpu")
233
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 2")
234
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 2 --cpu")
235
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 1")
236
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 1 --cpu")
237
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 0")
238
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1024x128 --axis 0 --cpu")
239
+ compare_filtered("concatenate --size 32x1024x128 --size 32x16x128 --axis 1")
240
+ compare_filtered("concatenate --size 32x1024x128 --size 32x16x128 --axis 1 --cpu")
241
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1x128 --axis 1")
242
+ compare_filtered("concatenate --size 32x1024x128 --size 32x1x128 --axis 1 --cpu")
243
+ compare_filtered("concatenate --size 1x32x1024x128 --size 1x32x1x128 --axis 2")
244
+ compare_filtered(
245
+ "concatenate --size 1x32x1024x128 --size 1x32x1x128 --axis 2 --cpu"
246
+ )
247
+ compare_filtered("conv1d --size 1x1000x80 --size 128x11x80")
248
+ compare_filtered("conv1d --size 1x1000x80 --size 128x11x80 --cpu")
249
+ compare_filtered("conv1d --size 16x1000x80 --size 128x11x80")
250
+ compare_filtered("conv1d --size 4x1000x80 --size 128x11x80 --cpu")
251
+ compare_filtered("conv2d --size 1x256x256x3 --size 8x3x3x3")
252
+ compare_filtered("conv2d --size 1x256x256x3 --size 8x3x3x3 --cpu")
253
+ compare_filtered("conv2d --size 16x256x256x3 --size 8x3x3x3")
254
+ compare_filtered("conv2d --size 4x256x256x3 --size 8x3x3x3 --cpu")
255
+ compare_filtered("cumsum --size 1024x1024 --axis 1 --cpu")
256
+ compare_filtered("cumsum --size 1024x1024 --axis 0 --cpu")
257
+ compare_filtered("cumsum --size 1024x1024 --axis 1")
258
+ compare_filtered("cumsum --size 1024x1024 --axis 0")
259
+ compare_filtered("cumsum --size 128x1024 --axis 1")
260
+ compare_filtered("cumsum --size 128x1024 --axis 0")
261
+ compare_filtered("cumsum --size 1024x4096 --axis 1")
262
+ compare_filtered("cumsum --size 1024x4096 --axis 0")
263
+ compare_filtered("cumsum --size 128x4096 --axis 1")
264
+ compare_filtered("cumsum --size 128x4096 --axis 0")
265
+ compare_filtered("cumsum --size 1024x7777 --axis 1")
266
+ compare_filtered("cumsum --size 1024x7777 --axis 0")
267
+ compare_filtered("cumsum --size 128x7777 --axis 1")
268
+ compare_filtered("cumsum --size 128x7777 --axis 0")
269
+ compare_filtered("cumsum --size 32768x128 --axis 1")
270
+ compare_filtered("cumsum --size 32768x128 --axis 0")
271
+
272
+ compare_filtered("sort --size 1024x1024 --axis 0")
273
+ compare_filtered("sort --size 1024x1024 --axis 1")
274
+ compare_filtered("sort --size 32768x128 --axis 0")
275
+ compare_filtered("sort --size 32768x128 --axis 1")
276
+ compare_filtered("sort --size 128x128 --axis 0 --cpu")
277
+ compare_filtered("sort --size 128x128 --axis 1 --cpu")
278
+
279
+ compare_filtered("topk --size 1024x1024 --axis 0")
280
+ compare_filtered("topk --size 1024x1024 --axis 1")
281
+ compare_filtered("topk --size 32768x128 --axis 0")
282
+ compare_filtered("topk --size 32768x128 --axis 1")
283
+ compare_filtered("topk --size 128x128 --axis 0 --cpu")
284
+ compare_filtered("topk --size 128x128 --axis 1 --cpu")
mlx-main/mlx-main/benchmarks/python/compile_bench.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright © 2023-2024 Apple Inc.
2
+
3
+ import argparse
4
+ import math
5
+ import random
6
+
7
+ import mlx.core as mx
8
+ from time_utils import time_fn
9
+
10
+
11
+ def bench_gelu():
12
+ def gelu(x):
13
+ return x * (1 + mx.erf(x / math.sqrt(2))) / 2
14
+
15
+ x = mx.random.uniform(shape=(1000, 1024))
16
+
17
+ def gen_fun(fun):
18
+ def bench_fun(x):
19
+ for _ in range(10):
20
+ x = fun(x)
21
+ return x
22
+
23
+ return bench_fun
24
+
25
+ time_fn(gen_fun(gelu), x, msg="fixed gelu")
26
+ time_fn(gen_fun(mx.compile(gelu)), x, msg="compiled fixed gelu")
27
+
28
+ def randint():
29
+ return random.randint(1, x.shape[0])
30
+
31
+ def gen_fun(fun):
32
+ def bench_fun(x, y):
33
+ x = x[: randint()]
34
+ for _ in range(10):
35
+ x = fun(x)
36
+ y = fun(y)
37
+ return x, y
38
+
39
+ return bench_fun
40
+
41
+ y = mx.random.uniform(shape=(1000, 1024))
42
+ time_fn(gen_fun(gelu), x, y, msg="variable gelu")
43
+ time_fn(gen_fun(mx.compile(gelu)), x, y, msg="compiled variable gelu")
44
+ time_fn(
45
+ gen_fun(mx.compile(gelu, shapeless=True)),
46
+ x,
47
+ y,
48
+ msg="shapeless variable gelu",
49
+ )
50
+
51
+
52
+ def bench_layernorm():
53
+ weight = mx.random.uniform(shape=(4096,)).astype(mx.float16)
54
+ bias = mx.random.uniform(shape=(4096,)).astype(mx.float16)
55
+ mx.eval(weight, bias)
56
+
57
+ def layernorm(x):
58
+ x = x.astype(mx.float32)
59
+ means = mx.mean(x, axis=-1, keepdims=True)
60
+ var = mx.var(x, axis=-1, keepdims=True)
61
+ x = (x - means) * mx.rsqrt(var + 1e-4)
62
+ x = x.astype(mx.float16)
63
+ return weight * x + bias
64
+
65
+ x = mx.random.uniform(shape=(1000, 4096)).astype(mx.float16)
66
+
67
+ def gen_fun(fun):
68
+ def bench_fun(x):
69
+ for _ in range(10):
70
+ x = fun(x)
71
+ return x
72
+
73
+ return bench_fun
74
+
75
+ time_fn(gen_fun(layernorm), x, msg="fixed layernorm")
76
+ time_fn(gen_fun(mx.compile(layernorm)), x, msg="compiled fixed layernorm")
77
+
78
+ def randint():
79
+ return random.randint(1, x.shape[0])
80
+
81
+ def gen_fun(fun):
82
+ def bench_fun(x):
83
+ x = x[: randint()]
84
+ for _ in range(10):
85
+ x = fun(x)
86
+ return x
87
+
88
+ return bench_fun
89
+
90
+ random.seed(0)
91
+ time_fn(gen_fun(layernorm), x, msg="variable layernorm")
92
+ random.seed(0)
93
+ time_fn(gen_fun(mx.compile(layernorm)), x, msg="compiled variable layernorm")
94
+ random.seed(0)
95
+ time_fn(
96
+ gen_fun(mx.compile(layernorm, shapeless=True)),
97
+ x,
98
+ msg="shapeless variable layernorm",
99
+ )
100
+
101
+
102
+ if __name__ == "__main__":
103
+ parser = argparse.ArgumentParser("Compile benchmarks.")
104
+ args = parser.parse_args()
105
+
106
+ bench_gelu()
107
+ bench_layernorm()
mlx-main/mlx-main/benchmarks/python/conv1d_bench.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ import subprocess
5
+ import time
6
+
7
+ import mlx.core as mx
8
+ import numpy as np
9
+ import torch
10
+
11
+ device_name = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"])
12
+ device_name = device_name.decode("utf-8").strip("\n")
13
+
14
+ N_warmup = 10
15
+ N_iter_bench = 100
16
+ N_iter_func = 5
17
+
18
+
19
+ def bench(f, a, b):
20
+ for i in range(N_warmup):
21
+ f(a, b)
22
+ torch.mps.synchronize()
23
+
24
+ s = time.perf_counter_ns()
25
+ for i in range(N_iter_bench):
26
+ f(a, b)
27
+ e = time.perf_counter_ns()
28
+ return (e - s) * 1e-9
29
+
30
+
31
+ def make_mx_conv_1D(strides=1, padding=0, groups=1):
32
+ def mx_conv_1D(a, b):
33
+ ys = []
34
+ for _ in range(N_iter_func):
35
+ y = mx.conv1d(a, b, stride=strides, padding=padding, groups=groups)
36
+ ys.append(y)
37
+ mx.eval(ys)
38
+ return ys
39
+
40
+ return mx_conv_1D
41
+
42
+
43
+ def make_pt_conv_1D(strides=1, padding=0, groups=1):
44
+ @torch.no_grad()
45
+ def pt_conv_1D(a, b):
46
+ ys = []
47
+ for _ in range(N_iter_func):
48
+ y = torch.conv1d(a, b, stride=strides, padding=padding, groups=groups)
49
+ ys.append(y)
50
+ torch.mps.synchronize()
51
+ return ys
52
+
53
+ return pt_conv_1D
54
+
55
+
56
+ def bench_shape(N, iH, C, wH, O, strides, padding, np_dtype, groups):
57
+ scale = 1.0 / math.sqrt(wH * C)
58
+ a_np = np.random.uniform(0, 0.5, (N, iH, C)).astype(np_dtype)
59
+ b_np = np.random.uniform(-scale, scale, (O, wH, int(C / groups))).astype(np_dtype)
60
+
61
+ a_mx = mx.array(a_np)
62
+ b_mx = mx.array(b_np)
63
+
64
+ a_pt = torch.from_numpy(a_np.transpose((0, 2, 1))).to("mps")
65
+ b_pt = torch.from_numpy(b_np.transpose((0, 2, 1))).to("mps")
66
+
67
+ torch.mps.synchronize()
68
+
69
+ f_mx = make_mx_conv_1D(strides, padding, groups)
70
+ f_pt = make_pt_conv_1D(strides, padding, groups)
71
+
72
+ time_torch = bench(f_pt, a_pt, b_pt)
73
+ time_mlx = bench(f_mx, a_mx, b_mx)
74
+
75
+ out_mx = mx.conv1d(a_mx, b_mx, stride=strides, padding=padding, groups=groups)
76
+ out_pt = torch.conv1d(
77
+ a_pt.to("cpu"), b_pt.to("cpu"), stride=strides, padding=padding, groups=groups
78
+ )
79
+ out_pt = torch.permute(out_pt, (0, 2, 1))
80
+ out_pt = out_pt.numpy(force=True)
81
+
82
+ atol = 2e-5 if np_dtype == np.float32 else 1e-4
83
+
84
+ if not np.allclose(out_pt, out_mx, atol=atol):
85
+ print(
86
+ f"Failed at {(N, iH, C)}, {(O, wH, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}"
87
+ )
88
+
89
+ return time_mlx, time_torch
90
+
91
+
92
+ if __name__ == "__main__":
93
+ parser = argparse.ArgumentParser(description="Run conv benchmarks")
94
+
95
+ dtypes = ("float32",)
96
+ shapes = (
97
+ (4, 32, 32, 5, 32, 1, 2, 1),
98
+ (4, 32, 32, 5, 32, 1, 2, 2),
99
+ (4, 32, 32, 5, 32, 1, 2, 4),
100
+ (4, 32, 32, 5, 32, 1, 2, 8),
101
+ (4, 32, 32, 5, 32, 1, 2, 8),
102
+ (4, 32, 32, 5, 32, 1, 2, 16),
103
+ (4, 32, 32, 5, 32, 1, 2, 32),
104
+ (4, 32, 256, 5, 512, 1, 2, 2),
105
+ (4, 32, 256, 5, 512, 1, 2, 128),
106
+ (4, 32, 256, 5, 512, 1, 2, 256),
107
+ )
108
+
109
+ for dtype in dtypes:
110
+ print("(N, iH, C), (O, wH, C), dtype, stride, pads, groups, diff%")
111
+ for N, iH, C, wH, O, strides, padding, groups in shapes:
112
+ np_dtype = getattr(np, dtype)
113
+ time_mlx, time_torch = bench_shape(
114
+ N, iH, C, wH, O, strides, padding, np_dtype, groups
115
+ )
116
+ diff = time_torch / time_mlx - 1.0
117
+
118
+ print(
119
+ f"({N}, {iH:3d}, {C:3d}), ({O:3d}, {wH:2d}, {C:3d}), {dtype}, {strides:5d}, {padding:4d}, {groups:6d}, {100. * diff:+5.2f}%"
120
+ )
121
+
122
+ if time_mlx >= 2.0 * time_torch:
123
+ print("ATTENTION ^^^^^^^")