diff --git a/.github/actions/fork-build-cache/action.yml b/.github/actions/fork-build-cache/action.yml new file mode 100644 index 0000000000..9c3cf5bab5 --- /dev/null +++ b/.github/actions/fork-build-cache/action.yml @@ -0,0 +1,164 @@ +name: 'Fork build caches' +description: 'Set up a fork-tests build job with ccache and the Metal kernel cache, and save the caches' + +# phase: restore runs the setup action, restores the ccache files and the +# Metal kernel cache, and points the build at the cache script in +# .github/scripts/fork-tests/metal-cache. phase: save prints the cache +# statistics and saves each cache on pull requests and on pushes to main +# when the build had cache misses. +# +# Cache keys: +# ccache ccache-fork-tests-KIND-FLAGS-clangCLANG-macOS-ARM64-metal-SHA-RUN-ATTEMPT +# Metal metal-METAL-KERNELS-KIND-RUN-ATTEMPT +# CLANG is the clang major.minor version. METAL is the metal compiler +# version. FLAGS is a hash of CFLAGS, CXXFLAGS, the deployment target and +# KIND. KIND sets the CMake arguments of the build. KERNELS is a hash of +# mlx/backend/metal/kernels. A restore takes the newest cache with the same +# prefix. The ccache restore falls back to a cache of another clang version; +# ccache checks the compiler content (compiler_check=content), so the +# objects of another compiler only miss. The Metal restore falls back only to +# a cache of the same metal compiler version, and the cache script puts the +# metal compiler version and the SDK build in each entry key. + +inputs: + phase: + description: 'restore or save' + required: true + kind: + description: 'The build kind: wheel or cpp' + required: true + ccache-save-key: + description: 'phase save: the ccache-save-key output of phase restore' + required: false + default: '' + metal-save-key: + description: 'phase save: the metal-save-key output of phase restore' + required: false + default: '' + +outputs: + cmake-args: + description: 'The args for generating CMake project' + value: ${{ steps.setup.outputs.cmake-args }} + ccache-save-key: + description: 'The key to save the ccache files with' + value: ${{ steps.setup.outputs.ccache-save-key }} + metal-save-key: + description: 'The key to save the Metal kernel cache with' + value: ${{ steps.keys.outputs.metal-save }} + +runs: + using: 'composite' + steps: + - name: Make the cache keys + id: keys + if: inputs.phase == 'restore' + shell: bash + env: + KIND: ${{ inputs.kind }} + KERNELS: ${{ hashFiles('mlx/backend/metal/kernels/**') }} + run: | + # The other lines of --version name the install folder and the OS. + # They change between runner images, so the keys use the first line. + version() { + echo "$1" | head -n 1 | sed -E 's/.* version ([0-9.]+).*/\1/' | tr -c 'A-Za-z0-9.\n' '_' + } + clang_text=$(xcrun clang --version) + metal_text=$(xcrun -sdk macosx metal --version) + sdk=$(xcrun -sdk macosx --show-sdk-build-version) + printf '%s\n' "$clang_text" "$metal_text" "SDK build: $sdk" + clang=$(version "$clang_text" | cut -d . -f 1-2) + metal=$(version "$metal_text") + if [ -z "$clang" ] || [ -z "$metal" ] || [ -z "$sdk" ]; then + echo "::error::Cannot read the clang, metal or SDK version." + exit 1 + fi + flags=$(printf '%s\n' "$CFLAGS" "$CXXFLAGS" "$MACOSX_DEPLOYMENT_TARGET" "$KIND" \ + | shasum -a 256 | cut -c 1-16) + kernels=${KERNELS:0:16} + { + echo "toolchain=$(echo "$metal_text" | head -n 1) SDK $sdk" + echo "ccache-key=fork-tests-$KIND-$flags-clang$clang" + echo "ccache-fallback=ccache-fork-tests-$KIND-$flags-" + echo "metal-restore=metal-$metal-$kernels-" + echo "metal-fallback=metal-$metal-" + echo "metal-save=metal-$metal-$kernels-$KIND-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + } | tee -a "$GITHUB_OUTPUT" + + - uses: ./.github/actions/setup + id: setup + if: inputs.phase == 'restore' + with: + toolkit: metal + ccache-key: ${{ steps.keys.outputs.ccache-key }} + ccache-fallback: ${{ steps.keys.outputs.ccache-fallback }} + # The build and the C++ tests do not use openmpi. Only the + # distributed test in python-gpu shard 0 does. + install-macos-deps: 'false' + + - name: Restore the Metal kernel cache + if: inputs.phase == 'restore' + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.metal-cache + key: ${{ steps.keys.outputs.metal-restore }} + restore-keys: | + ${{ steps.keys.outputs.metal-restore }} + ${{ steps.keys.outputs.metal-fallback }} + + - name: Prepare the caches + if: inputs.phase == 'restore' + shell: bash + env: + TOOLCHAIN: ${{ steps.keys.outputs.toolchain }} + run: | + # The script reads the restored entries from MLX_METAL_CACHE_IN and + # writes each entry that the build uses to MLX_METAL_CACHE_OUT. The + # saved cache then holds no entries that the build does not use. + in="$RUNNER_TEMP/metal-cache-in" + if [ -d .metal-cache ]; then + mv .metal-cache "$in" + else + mkdir -p "$in" + fi + echo "Restored Metal cache entries: $(ls "$in" | wc -l)" + { + echo "MLX_METAL_CACHE_TOOLCHAIN=$TOOLCHAIN" + echo "MLX_METAL_CACHE_IN=$in" + echo "MLX_METAL_CACHE_OUT=$GITHUB_WORKSPACE/.metal-cache" + } >> "$GITHUB_ENV" + ccache -z + + - name: Show the cache statistics + id: stats + if: inputs.phase == 'save' + shell: bash + run: | + ccache -s -v + ccache_misses=$(ccache -s | awk '$1 == "Misses:" { print $2; exit }') + ccache_misses=${ccache_misses:-unknown} + metal_misses=0 + log="$MLX_METAL_CACHE_OUT.log" + if [ -f "$log" ]; then + metal_misses=$(grep -c '^miss ' "$log" || true) + echo "Metal cache: $(grep -c '^hit ' "$log" || true) hits, $metal_misses misses" + grep '^miss ' "$log" || true + fi + du -sh .ccache .metal-cache || true + # A build with no misses adds nothing, so it does not save a copy. + echo "ccache-misses=$ccache_misses" | tee -a "$GITHUB_OUTPUT" + echo "metal-misses=$metal_misses" | tee -a "$GITHUB_OUTPUT" + + - name: Save the ccache files + if: inputs.phase == 'save' && steps.stats.outputs.ccache-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ${{ inputs.ccache-save-key }} + + - name: Save the Metal kernel cache + if: inputs.phase == 'save' && steps.stats.outputs.metal-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ github.workspace }}/.metal-cache + key: ${{ inputs.metal-save-key }} diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 8f15e6128e..4620bf907a 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -26,11 +26,22 @@ inputs: description: 'Use this instead of inputs.toolkit in the ccache key' required: false default: '' + ccache-fallback: + description: 'A second restore-keys prefix for the ccache files' + required: false + default: '' + install-macos-deps: + description: 'Whether to run brew update and install openmpi on macOS' + required: false + default: 'true' outputs: cmake-args: description: 'The args for generating CMake project' value: ${{ steps.cmake-args.outputs.cmakeArgs }} + ccache-save-key: + description: 'The key for actions/cache/save of the ccache files (macOS)' + value: ${{ steps.ccache-keys.outputs.save }} runs: using: 'composite' @@ -46,7 +57,7 @@ runs: openmpi-bin openmpi-common libopenmpi-dev - name: Install macOS dependencies - if: runner.os == 'macOS' + if: runner.os == 'macOS' && inputs.install-macos-deps == 'true' shell: bash run: | brew update @@ -91,8 +102,7 @@ runs: MAX_SIZE: |- ${{ case(inputs.ccache-key == 'release', case(startsWith(inputs.toolkit, 'cuda'), - case(runner.os == 'Linux', '300MB', - '160MB'), + '300MB', '60MB'), case(startsWith(inputs.toolkit, 'cuda'), case(runner.os == 'Linux' && runner.arch == 'x64', '600MB', @@ -109,24 +119,32 @@ runs: ccache --set-config=compiler_check=content ccache -p + - name: Make the ccache keys + id: ccache-keys + if: runner.os == 'macOS' && inputs.use-ccache == 'true' + shell: bash + env: + PREFIX: ccache-${{ inputs.ccache-key }}-${{ runner.os }}-${{ runner.arch }}-${{ inputs.ccache-toolkit || inputs.toolkit }}- + FALLBACK: ${{ inputs.ccache-fallback }} + run: | + { + echo "restore=$PREFIX$GITHUB_SHA" + echo "save=$PREFIX$GITHUB_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + echo "restore-keys</dev/null | + sed -E 's#(MetalToolchain-v[0-9.]*[0-9])\.[A-Za-z0-9]+/#\1/#g' + fi +} > "$out.key" || { + rm -f "$out.key" + exec "$real" "$@" +} +key=$(shasum -a 256 < "$out.key" | cut -d ' ' -f 1) +rm -f "$out.key" + +mkdir -p "$MLX_METAL_CACHE_OUT" +log="$MLX_METAL_CACHE_OUT.log" +if [[ -f "$MLX_METAL_CACHE_IN/$key" ]]; then + cp "$MLX_METAL_CACHE_IN/$key" "$out" + echo "hit $mode $(basename "$out")" >> "$log" +else + "$real" "$@" + echo "miss $mode $(basename "$out")" >> "$log" +fi +tmp="$MLX_METAL_CACHE_OUT/$key.$$" +cp "$out" "$tmp" +mv "$tmp" "$MLX_METAL_CACHE_OUT/$key" diff --git a/.github/scripts/fork-tests/python-shards.json b/.github/scripts/fork-tests/python-shards.json new file mode 100644 index 0000000000..8d181d7fed --- /dev/null +++ b/.github/scripts/fork-tests/python-shards.json @@ -0,0 +1,98 @@ +{ + "gpu": [ + [ + "test_quantized", + "test_ops", + "test_reduce", + "test_nn", + "test_threads", + "test_autograd", + "test_vmap", + "test_conv", + "test_optimizers", + "test_fast", + "test_linalg", + "test_load", + "test_eval", + "test_einsum", + "test_export_import", + "test_upsample", + "test_memory", + "test_init", + "test_random", + "test_losses", + "test_zero_copy", + "test_bf16", + "test_conv_transpose", + "test_double", + "test_constants", + "test_device", + "test_extension", + "test_graph", + "test_metal_threadgroup_bounds", + "test_tree" + ], + [ + "test_fast_sdpa", + "test_fast_gated_delta", + "test_compile", + "test_fft", + "test_array", + "test_blas" + ] + ], + "cpu": [ + [ + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_simdgroup", + "test_fast_sdpa.TestFastSDPA.test_sdpa_vector_gqa_long", + "test_fft", + "test_fast_gated_delta:rest", + "test_ops", + "test_array", + "test_conv", + "test_eval", + "test_autograd", + "test_metal_threadgroup_bounds", + "test_zero_copy", + "test_bf16", + "test_einsum", + "test_double", + "test_memory" + ], + [ + "test_quantized:rest", + "test_reduce", + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_sequential", + "test_compile", + "test_quantized.TestQuantized.test_qmv_wide", + "test_quantized.TestQuantized.test_gather_qmm_sorted", + "test_nn", + "test_quantized.TestQuantized.test_qmv", + "test_fast", + "test_upsample", + "test_threads", + "test_random", + "test_vmap", + "test_conv_transpose", + "test_tree", + "test_graph" + ], + [ + "test_fast_gated_delta.TestGatedDelta.test_gated_delta_nax", + "test_fast_sdpa.TestFastSDPA.test_sdpa", + "test_fast_sdpa:rest", + "test_export_import", + "test_quantized.TestQuantized.test_gather_qmm_sorted_nax_large_m", + "test_blas", + "test_quantized.TestQuantized.test_qmm_large_dims", + "test_optimizers", + "test_load", + "test_extension", + "test_linalg", + "test_init", + "test_constants", + "test_losses", + "test_device" + ] + ] +} diff --git a/.github/scripts/fork-tests/python_shards.py b/.github/scripts/fork-tests/python_shards.py new file mode 100755 index 0000000000..a1fc84736e --- /dev/null +++ b/.github/scripts/fork-tests/python_shards.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +"""Check and run the Python test shards of fork-tests.yml. + +The shard map (python-shards.json) has one list of shards for each pass +("gpu" and "cpu"). A shard is a list of entries. Each entry runs in its own +child process, and the child writes its own log. An entry is one of these: + + test_x all tests in python/tests/test_x.py + test_x.Class.test_y one test (or a class with test_x.Class) + test_x:rest the tests in test_x.py that no other entry names + +Commands: + + check Check the map without importing mlx. Every + python/tests/test*.py file must be in the map of + each pass exactly one time: as one whole-file + entry, or as named entries with at most one rest + entry. The command fails on any other case. + run PASS SHARD COUNT Check the map, expand the split files to test IDs + (this imports them), and fail if the named IDs of + a split file are not a partition of its tests. + Then run the entries of shard SHARD, JOBS at a + time. COUNT is the number of shard jobs in the + workflow, and it must equal the shards in the map. + verify DIR Read the test ID files that the shard jobs wrote + and fail if a test ran in two shards of a pass or + if a shard result is missing. +""" + +import argparse +import json +import os +import re +import subprocess +import sys +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +TESTS = Path("python/tests") +MAP = Path(__file__).with_name("python-shards.json") +PASSES = ("gpu", "cpu") + + +def parse(entry): + """Return (file, kind) for a map entry.""" + if entry.endswith(":rest"): + return entry[: -len(":rest")], "rest" + if "." in entry: + return entry.split(".", 1)[0], "named" + return entry, "whole" + + +def load_map(): + with open(MAP) as f: + data = json.load(f) + if sorted(data) != sorted(PASSES): + sys.exit(f"error: {MAP} must have exactly the keys {PASSES}") + return data + + +def check_static(shards): + """Return a list of errors. Does not import mlx or the test files.""" + errors = [] + files = sorted(p.stem for p in TESTS.glob("test*.py")) + for name in PASSES: + uses = {} + entries = [] + for index, shard in enumerate(shards[name]): + if not shard: + errors.append(f"{name} shard {index} has no entries") + for entry in shard: + file, kind = parse(entry) + uses.setdefault(file, []).append((index, kind, entry)) + entries.append(entry) + for entry in sorted({e for e in entries if entries.count(e) > 1}): + errors.append(f"{name}: the entry {entry} is in the map more than one time") + for file in files: + found = uses.pop(file, []) + kinds = [kind for _, kind, _ in found] + where = ", ".join(f"shard {i}: {e}" for i, _, e in found) + if not found: + errors.append(f"{name}: {TESTS}/{file}.py is in no shard") + elif "whole" in kinds and len(found) > 1: + errors.append( + f"{name}: {TESTS}/{file}.py is in more than one shard " + f"or entry ({where})" + ) + elif kinds.count("rest") > 1: + errors.append( + f"{name}: {TESTS}/{file}.py has more than one rest entry ({where})" + ) + for file, found in sorted(uses.items()): + names = ", ".join(e for _, _, e in found) + errors.append(f"{name}: {names} names no file {TESTS}/{file}.py") + return errors + + +def flatten(suite): + for test in suite: + if isinstance(test, unittest.TestSuite): + yield from flatten(test) + else: + yield test + + +def test_ids(module): + suite = unittest.defaultTestLoader.loadTestsFromName(module) + ids = [test.id() for test in flatten(suite)] + bad = [i for i in ids if not i.startswith(module + ".")] + if bad: + sys.exit(f"error: {module} did not load: {bad}") + return ids + + +def expand(shards, name): + """Expand the entries of one pass to child arguments. + + Returns a list (one item for each shard) of lists of (entry, names), + where names is the list of unittest names for the child. Also returns + a list of errors. + """ + errors = [] + split = {} + for shard in shards[name]: + for entry in shard: + file, kind = parse(entry) + if kind != "whole": + split.setdefault(file, []).append(entry) + sys.path.insert(0, str(TESTS)) + owner = {} + rest_ids = {} + for file, entries in sorted(split.items()): + ids = test_ids(file) + count = {i: 0 for i in ids} + for entry in entries: + if parse(entry)[1] != "named": + continue + matched = [i for i in ids if i == entry or i.startswith(entry + ".")] + if not matched: + errors.append(f"{name}: the entry {entry} matches no test in {file}.py") + for i in matched: + count[i] += 1 + owner[i] = entry + twice = [i for i, c in count.items() if c > 1] + if twice: + errors.append(f"{name}: these tests are in more than one entry: {twice}") + missing = [i for i, c in count.items() if c == 0] + if f"{file}:rest" in entries: + rest_ids[file] = missing + elif missing: + errors.append( + f"{name}: these tests of {file}.py are in no shard: {missing}" + ) + plan = [] + for shard in shards[name]: + units = [] + for entry in shard: + file, kind = parse(entry) + if kind == "whole": + units.append((entry, [entry])) + elif kind == "rest": + units.append((entry, rest_ids.get(file, []))) + else: + units.append((entry, sorted(i for i, e in owner.items() if e == entry))) + plan.append(units) + return plan, errors + + +def child(log_dir, unit, names): + """Run the tests in names in this process. Used by run.""" + # The same settings as python/tests/run.py. + os.environ["MLX_ENABLE_TF32"] = "0" + os.environ["MLX_ENABLE_CACHE_THRASHING_CHECK"] = "0" + sys.path.insert(0, str(TESTS)) + import mlx.core as mx + + exclude = set(os.environ.get("CPU_EXCLUDE", "").split()) + suite = unittest.defaultTestLoader.loadTestsFromNames(names) + tests = [t for t in flatten(suite) if t.id() not in exclude] + ran = [] + + class Result(unittest.TextTestResult): + def startTest(self, test): + ran.append(test.id()) + super().startTest(test) + + runner = unittest.TextTestRunner( + sys.stdout, verbosity=2, durations=0, resultclass=Result + ) + result = runner.run(unittest.TestSuite(tests)) + with open(Path(log_dir) / f"{unit}.ids", "w") as f: + json.dump(ran, f) + mx.clear_streams() + sys.exit(0 if result.wasSuccessful() else 1) + + +def file_name(entry): + return re.sub(r"[^A-Za-z0-9_.-]", "_", entry) + + +def run(args): + shards = load_map() + errors = check_static(shards) + if errors: + report(errors) + if args.count != len(shards[args.name]): + report( + [ + f"the workflow runs {args.count} {args.name} shard jobs, " + f"but {MAP.name} has {len(shards[args.name])} {args.name} shards" + ] + ) + plan, errors = expand(shards, args.name) + if errors: + report(errors) + units = plan[args.shard] + logs = Path(args.logs) + logs.mkdir(parents=True, exist_ok=True) + lock = threading.Lock() + results = {} + + def one(unit): + entry, names = unit + name = file_name(entry) + start = time.monotonic() + with open(logs / f"{name}.log", "w") as log: + code = subprocess.run( + [sys.executable, "-u", __file__, "child", str(logs), name, *names], + stdout=log, + stderr=subprocess.STDOUT, + ).returncode + seconds = time.monotonic() - start + with lock: + results[entry] = (code, seconds) + state = "passed" if code == 0 else f"failed (exit code {code})" + print(f"{entry}: {state} in {seconds:.1f} s", flush=True) + # Print the end of a failed log at once. The full logs print + # after all entries finish, and a killed job never gets there. + if code != 0: + tail = ( + (logs / f"{name}.log") + .read_text(errors="replace") + .splitlines()[-80:] + ) + print("\n".join(f" | {line}" for line in tail), flush=True) + + print( + f"{args.name} shard {args.shard}: {len(units)} entries, {args.jobs} at a time", + flush=True, + ) + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + list(pool.map(one, units)) + + ran = {} + failed = [] + for entry, _ in units: + name = file_name(entry) + print(f"::group::Python tests ({args.name}): {entry}") + print((logs / f"{name}.log").read_text(errors="replace"), end="") + print("::endgroup::") + if results[entry][0] != 0: + failed.append(entry) + ids_file = logs / f"{name}.ids" + ran[entry] = json.loads(ids_file.read_text()) if ids_file.exists() else [] + out = { + "pass": args.name, + "shard": args.shard, + "count": args.count, + "entries": { + e: { + "exit": results[e][0], + "seconds": round(results[e][1], 1), + "tests": ran[e], + } + for e, _ in units + }, + } + with open(logs / f"testids-{args.name}-{args.shard}.json", "w") as f: + json.dump(out, f) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as f: + f.write(f"### Python tests, {args.name} pass, shard {args.shard}\n\n") + f.write("| Entry | Result | Tests | Seconds |\n|---|---|---|---|\n") + for e, _ in sorted(units, key=lambda u: -results[u[0]][1]): + code, seconds = results[e] + state = "passed" if code == 0 else f"failed ({code})" + f.write(f"| `{e}` | {state} | {len(ran[e])} | {seconds:.1f} |\n") + total = sum(len(t) for t in ran.values()) + f.write(f"\nTests started: {total}\n\n") + if failed: + names = " ".join(failed) + print(f"::error::Python test entries that failed ({args.name} pass): {names}") + sys.exit(1) + + +def verify(args): + shards = load_map() + errors = [] + lines = [ + "### Python tests in all shards", + "", + "| Pass | Shards | Tests started |", + "|---|---|---|", + ] + for name in PASSES: + seen = {} + found = 0 + for index in range(len(shards[name])): + path = Path(args.dir) / f"testids-{name}-{index}.json" + if not path.exists(): + errors.append(f"{name} shard {index} wrote no result ({path.name})") + continue + found += 1 + data = json.loads(path.read_text()) + for entry, info in data["entries"].items(): + for test in info["tests"]: + seen.setdefault(test, []).append(f"shard {index} {entry}") + twice = {t: w for t, w in seen.items() if len(w) > 1} + for test, where in sorted(twice.items()): + errors.append(f"{name}: {test} ran more than one time: {where}") + lines.append(f"| {name} | {found} of {len(shards[name])} | {len(seen)} |") + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as f: + f.write("\n".join(lines) + "\n\n") + print("\n".join(lines)) + if errors: + report(errors) + + +def report(errors): + for error in errors: + print(f"::error::{error}") + sys.exit(1) + + +def main(): + if len(sys.argv) > 1 and sys.argv[1] == "child": + child(sys.argv[2], sys.argv[3], sys.argv[4:]) + return + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("check") + p = sub.add_parser("run") + p.add_argument("name", choices=PASSES) + p.add_argument("shard", type=int) + p.add_argument("count", type=int) + p.add_argument("--jobs", type=int, default=1) + p.add_argument("--logs", required=True) + p = sub.add_parser("verify") + p.add_argument("dir") + args = parser.parse_args() + if args.command == "check": + errors = check_static(load_map()) + if errors: + report(errors) + print(f"{MAP.name}: every test file is in exactly one place in each pass.") + elif args.command == "run": + if not 0 <= args.shard < args.count: + report([f"shard {args.shard} is not in 0..{args.count - 1}"]) + run(args) + else: + verify(args) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index ab963d2cec..6b36622c56 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -1,7 +1,26 @@ name: Fork Tests -# Build the fork with Metal and run its C++ and Python tests on a -# GitHub-hosted macOS runner. The steps use the actions in .github/actions. +# Build the fork with Metal and run its C++ and Python tests on GitHub-hosted +# macOS runners. The steps use the actions in .github/actions. +# +# The jobs: +# build-wheel builds the Python wheel and uploads it. +# build-cpp builds the C++ library and tests, and runs the C++ tests +# with the GPU and then with the CPU as the default device. +# python-gpu runs the Python tests with the GPU as the default device. +# python-cpu runs the Python tests with the CPU as the default device. +# metal-build-and-test +# merges the coverage profiles of all jobs, writes the +# coverage report, and fails if one of the other jobs failed. +# The two build jobs run in parallel. The Python test jobs start when the +# wheel is ready. Each Python test job runs one shard of +# .github/scripts/fork-tests/python-shards.json, and +# .github/scripts/fork-tests/python_shards.py fails a job if a test file is +# in no shard or in two shards. +# +# The hosted macOS runners are a shared pool. A run uses 8 macOS jobs, and +# at most 6 of them run at the same time. A new push to a pull request +# cancels the older run and frees its runners. on: pull_request: @@ -10,148 +29,392 @@ on: - main workflow_dispatch: +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Cancel an older run of the same pull request. Let runs on main finish. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # Instrument the C and C++ code for line coverage. cmake reads these + # variables in the build jobs and in the extension examples. The Metal + # shaders are not instrumented. + CFLAGS: -fprofile-instr-generate -fcoverage-mapping + CXXFLAGS: -fprofile-instr-generate -fcoverage-mapping + jobs: - metal-build-and-test: + build-wheel: + runs-on: macos-26 + timeout-minutes: 45 + env: + # The runner has macOS 26. Version 26.2 is the lowest target that + # builds all Metal kernels. + MACOSX_DEPLOYMENT_TARGET: '26.2' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Check the Python shard map + run: python3 .github/scripts/fork-tests/python_shards.py check + + - uses: ./.github/actions/fork-build-cache + id: cache + with: + phase: restore + kind: wheel + + - name: Build the wheel + env: + DEBUG: 1 + CMAKE_ARGS: ${{ steps.cache.outputs.cmake-args }} + run: | + uv pip install build setuptools + export PATH="$GITHUB_WORKSPACE/.github/scripts/fork-tests/metal-cache:$PATH" + python -m build -w + + - uses: ./.github/actions/fork-build-cache + with: + phase: save + kind: wheel + ccache-save-key: ${{ steps.cache.outputs.ccache-save-key }} + metal-save-key: ${{ steps.cache.outputs.metal-save-key }} + + - name: Upload the wheel + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: fork-tests-wheel + path: dist/*.whl + if-no-files-found: error + # A wheel is a zip file already. + compression-level: 0 + retention-days: 3 + overwrite: true + + build-cpp: + runs-on: macos-26 + timeout-minutes: 45 + env: + MACOSX_DEPLOYMENT_TARGET: '26.2' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/fork-build-cache + id: cache + with: + phase: restore + kind: cpp + + - name: Build the C++ library and tests + id: build + env: + CMAKE_ARGS: ${{ steps.cache.outputs.cmake-args }} + run: | + export PATH="$GITHUB_WORKSPACE/.github/scripts/fork-tests/metal-cache:$PATH" + # The same commands as the "Build CPP only" step of + # .github/actions/build-macos. + cmake . -B build $CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug + cmake --build build -j $(sysctl -n hw.physicalcpu) + + - uses: ./.github/actions/fork-build-cache + with: + phase: save + kind: cpp + ccache-save-key: ${{ steps.cache.outputs.ccache-save-key }} + metal-save-key: ${{ steps.cache.outputs.metal-save-key }} + + - name: Run the C++ tests on the GPU + env: + METAL_DEBUG_ERROR_MODE: 0 + METAL_DEVICE_WRAPPER_TYPE: 1 + # Each test process writes one profile for each instrumented binary. + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + run: ./build/tests/tests + + - name: Run the C++ tests on the CPU + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + DEVICE: cpu + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/cpu-%p-%m.profraw + run: ./build/tests/tests + + - name: Merge the coverage profiles + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/cpp.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: profdata-cpp + path: ${{ runner.temp }}/profdata/cpp.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Upload the C++ test binary + # The coverage report reads the coverage mapping in this binary. + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: fork-tests-cpp-binary + path: build/tests/tests + if-no-files-found: error + compression-level: 1 + retention-days: 3 + overwrite: true + + python-gpu: + needs: build-wheel runs-on: macos-26 - timeout-minutes: 60 - permissions: - contents: read - concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - # Cancel an older run of the same pull request. Let runs on main finish. - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # One job for each "gpu" shard in python-shards.json. The script + # fails if the two counts are not equal. + shard: [0, 1] env: - # Instrument the C and C++ code for line coverage. Both builds in - # build-macos run cmake from scratch, and cmake reads these variables. - # The Metal shaders are not instrumented. - CFLAGS: -fprofile-instr-generate -fcoverage-mapping - CXXFLAGS: -fprofile-instr-generate -fcoverage-mapping + METAL_DEBUG_ERROR_MODE: 0 + METAL_DEVICE_WRAPPER_TYPE: 1 + # The job-level env cannot read the runner context, so the steps set + # LLVM_PROFILE_FILE. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: ./.github/actions/setup - id: setup with: toolkit: metal - # This cache key is not an upstream key. The setup action saves - # the cache on pushes to main only, never on pull requests. - ccache-key: fork-tests + use-ccache: 'false' + # Shard 0 runs the distributed test. It gets the same Homebrew + # packages (openmpi) as the build jobs. + install-macos-deps: ${{ matrix.shard == 0 }} - - uses: ./.github/actions/build-macos + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - cmake-args: ${{ steps.setup.outputs.cmake-args }} - # The runner has macOS 26. Version 26.2 is the lowest target that - # builds all Metal kernels. - macos-target: '26.2' + name: fork-tests-wheel + path: dist + + - name: Install the wheel and the test dependencies + run: | + uv pip install build setuptools tensorflow + uv pip install dist/*.whl - - uses: ./.github/actions/test-macos + - name: Run the Python tests id: tests env: - # Each test process writes one profile for each instrumented binary. - # The job-level env cannot read the runner context, so this step - # sets the path. The build steps then write no profiles here. LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + run: | + python .github/scripts/fork-tests/python_shards.py run gpu \ + ${{ matrix.shard }} ${{ strategy.job-total }} \ + --jobs 1 --logs "$RUNNER_TEMP/logs" + + - name: Run the distributed tests + if: ${{ !cancelled() && matrix.shard == 0 }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + # The same commands as the "Run distributed tests" group of + # .github/actions/test-macos for the metal toolkit. + run: | + # TODO: Re-enable for GPU after openmpi updating their libprrte + # dependency: https://github.com/openpmix/prrte/issues/2416 + mlx.launch --verbose -n 8 uv run python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2) + if $(grep "\[WARN\]" stderr.log); then + echo "Distributed ring test failed" + exit 1 + fi + + - name: Build and test the extension examples + if: ${{ !cancelled() && matrix.shard == 0 }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/%p-%m.profraw + # The same commands as the extension groups of + # .github/actions/test-macos for the metal toolkit. + run: | + echo "::group::Build example extension" + pushd examples/cmake_extension + uv pip install -r requirements.txt + uv run setup.py build_ext --inplace + uv run test.py + popd + echo "::endgroup::" + + echo "::group::Build Metal extension example" + pushd examples/metal_extension + uv pip install -r requirements.txt + uv run setup.py build_ext --inplace + uv run test.py + popd + echo "::endgroup::" + + - name: Merge the coverage profiles + if: ${{ !cancelled() }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/gpu-${{ matrix.shard }}.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - toolkit: metal + name: profdata-gpu-${{ matrix.shard }} + path: ${{ runner.temp }}/profdata/gpu-${{ matrix.shard }}.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true - - name: Run the tests on the CPU - id: cpu-tests - # Run the CPU code of ops that also have a Metal implementation. - # The profiles go to the same folder, so the report merges both runs. + - name: Upload the list of tests that ran if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: testids-gpu-${{ matrix.shard }} + path: ${{ runner.temp }}/logs/testids-gpu-${{ matrix.shard }}.json + if-no-files-found: error + retention-days: 3 + overwrite: true + + python-cpu: + # Run the CPU code of ops that also have a Metal implementation. + needs: build-wheel + runs-on: macos-26 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # One job for each "cpu" shard in python-shards.json. + shard: [0, 1, 2] + env: + DEVICE: cpu + # Tests that take more than 5 minutes on the CPU. The GPU pass + # still runs them. + # test_sdpa_long_masked_sequence: 21 min 36 s on the CPU. + # test_sdpa_full_head_dim_256: 6 min 46 s on the CPU. + CPU_EXCLUDE: >- + test_fast_sdpa.TestFastSDPA.test_sdpa_long_masked_sequence + test_fast_sdpa.TestFastSDPA.test_sdpa_full_head_dim_256 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup + with: + toolkit: metal + use-ccache: 'false' + install-macos-deps: 'false' + + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-wheel + path: dist + + - name: Install the wheel and the test dependencies + run: | + uv pip install build setuptools tensorflow + uv pip install dist/*.whl + + - name: Run the Python tests on the CPU + id: tests env: - DEVICE: cpu LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/cpu-%p-%m.profraw - # Tests that take more than 5 minutes on the CPU. The GPU pass - # still runs them. - # test_sdpa_long_masked_sequence: 21 min 36 s on the CPU. - # test_sdpa_full_head_dim_256: 6 min 46 s on the CPU. - CPU_EXCLUDE: >- - test_fast_sdpa.TestFastSDPA.test_sdpa_long_masked_sequence - test_fast_sdpa.TestFastSDPA.test_sdpa_full_head_dim_256 + # Each entry runs in a child process that writes its own log, so a + # crash stops only that entry. Three entries run at a time. run: | - status=0 - echo "::group::Run C++ tests on the CPU" - ./build/tests/tests || status=1 - echo "::endgroup::" + python .github/scripts/fork-tests/python_shards.py run cpu \ + ${{ matrix.shard }} ${{ strategy.job-total }} \ + --jobs 3 --logs "$RUNNER_TEMP/logs" - # Run one process for each Python test file, three at a time. Each - # file runs in a child process that writes its own log, so a crash - # stops only that file. - logs="$RUNNER_TEMP/cpu-logs" - mkdir -p "$logs" - cat > "$RUNNER_TEMP/run_cpu.py" <<'EOF' - import os - import subprocess - import sys - import unittest - - if len(sys.argv) == 2: - name = os.path.basename(sys.argv[1])[: -len(".py")] - with open(os.path.join(os.environ["LOGS"], name + ".log"), "w") as log: - code = subprocess.run( - [sys.executable, "-u", __file__, name, "child"], - stdout=log, - stderr=subprocess.STDOUT, - ).returncode - result = "passed" if code == 0 else f"failed (exit code {code})" - print(f"{name}: {result}", flush=True) - sys.exit(0) - - os.environ["MLX_ENABLE_TF32"] = "0" - os.environ["MLX_ENABLE_CACHE_THRASHING_CHECK"] = "0" - sys.path.insert(0, "python/tests") - import mlx.core as mx - - exclude = set(os.environ["CPU_EXCLUDE"].split()) - - def flatten(suite): - for test in suite: - if isinstance(test, unittest.TestSuite): - yield from flatten(test) - elif test.id() not in exclude: - yield test - - suite = unittest.defaultTestLoader.loadTestsFromName(sys.argv[1]) - suite = unittest.TestSuite(flatten(suite)) - result = unittest.TextTestRunner(sys.stdout, verbosity=2).run(suite) - mx.clear_streams() - sys.exit(0 if result.wasSuccessful() else 1) - EOF - export LOGS="$logs" - printf '%s\n' python/tests/test_*.py \ - | xargs -P 3 -n 1 python "$RUNNER_TEMP/run_cpu.py" \ - | tee "$logs/results.txt" || true - failed=() - for file in python/tests/test_*.py; do - name=$(basename "$file" .py) - echo "::group::Python tests on the CPU: $name" - cat "$logs/$name.log" || true - echo "::endgroup::" - grep -qx "$name: passed" "$logs/results.txt" || failed+=("$name") - done - if [ ${#failed[@]} -gt 0 ]; then - echo "::error::Python test files that failed on the CPU: ${failed[*]}" - status=1 - fi - exit $status + - name: Merge the coverage profiles + if: ${{ !cancelled() }} + run: | + mkdir -p "$RUNNER_TEMP/profdata" + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + -o "$RUNNER_TEMP/profdata/cpu-${{ matrix.shard }}.profdata" + + - name: Upload the coverage profile + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: profdata-cpu-${{ matrix.shard }} + path: ${{ runner.temp }}/profdata/cpu-${{ matrix.shard }}.profdata + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: Upload the list of tests that ran + if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: testids-cpu-${{ matrix.shard }} + path: ${{ runner.temp }}/logs/testids-cpu-${{ matrix.shard }}.json + if-no-files-found: error + retention-days: 3 + overwrite: true + + metal-build-and-test: + needs: [build-wheel, build-cpp, python-gpu, python-cpu] + if: ${{ !cancelled() }} + runs-on: macos-26 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Download the lists of tests that ran + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: testids-* + path: ${{ runner.temp }}/testids + merge-multiple: true + + - name: Check that each Python test ran in one shard only + run: python3 .github/scripts/fork-tests/python_shards.py verify "$RUNNER_TEMP/testids" + + - name: Download the coverage profiles + id: profiles + if: ${{ !cancelled() && needs.build-wheel.result == 'success' && needs.build-cpp.result == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: profdata-* + path: ${{ runner.temp }}/profdata + merge-multiple: true + + - name: Download the wheel + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-wheel + path: ${{ runner.temp }}/wheel + + - name: Download the C++ test binary + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: fork-tests-cpp-binary + path: build/tests - name: Report C++ line coverage + id: coverage # Report also after a test failure, so that a red run shows the # coverage of the tests that ran. - if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + if: ${{ !cancelled() && steps.profiles.outcome == 'success' }} env: - TESTS_OUTCOME: ${{ steps.tests.outcome }} - CPU_TESTS_OUTCOME: ${{ steps.cpu-tests.outcome }} + CPP_RESULT: ${{ needs.build-cpp.result }} + GPU_RESULT: ${{ needs.python-gpu.result }} + CPU_RESULT: ${{ needs.python-cpu.result }} run: | shopt -s nullglob out="$RUNNER_TEMP/coverage" mkdir -p "$out" - xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profiles/*.profraw \ + # Each test job merged its raw profiles into one .profdata file. + xcrun llvm-profdata merge -sparse "$RUNNER_TEMP"/profdata/*.profdata \ -o "$out/coverage.profdata" # The Python tests run the code in the installed wheel: the - # extension module and the libraries in mlx/lib. - core=$(python -c 'import mlx.core as c; print(c.__file__)') + # extension module and the libraries in mlx/lib. The test jobs + # installed this same wheel. + unzip -q "$RUNNER_TEMP"/wheel/*.whl -d "$RUNNER_TEMP/wheel-files" + core=$(echo "$RUNNER_TEMP"/wheel-files/mlx/core.*.so) objects=(./build/tests/tests -object "$core") for lib in "$(dirname "$core")"/lib/*.dylib; do objects+=(-object "$lib") @@ -232,23 +495,39 @@ jobs: { echo "### C++ line coverage" echo - echo "Test step (GPU default device): $TESTS_OUTCOME" + echo "C++ build and C++ tests (GPU and CPU default device): $CPP_RESULT" echo - echo "Test step (CPU default device): $CPU_TESTS_OUTCOME" + echo "Python tests (GPU default device): $GPU_RESULT" + echo + echo "Python tests (CPU default device): $CPU_RESULT" echo echo "| Component | Lines | Branches | Functions | Target |" echo "|---|---|---|---|---|" cat "$out/rows.md" echo echo "The denominator is the host C++ code under \`mlx/\` and the Python bindings in \`python/src\`, which the C++ tests and the Python wheel link: $lines_total lines. It leaves out the tests, the build folders with their dependencies and generated files, the vendored \`mlx/3rdparty/pocketfft.h\`, and the CUDA backend in \`mlx/backend/cuda/\`, which macOS builds only as a stub." - echo "The C++ and Python tests run two times, first with the GPU and then with the CPU as the default device. The report merges the two runs." + echo "The C++ and Python tests run two times: one pass with the GPU and one pass with the CPU as the default device. The passes run in parallel jobs. The report merges the profiles of all jobs." echo "The Metal shader source in \`mlx/backend/metal/kernels/\` is not in the denominator: the kernels run on the GPU and are outside every coverage tool. The host code that encodes and dispatches them is counted, and so are the few headers in that folder that host C++ includes." echo "The Branches column is real C++ branch coverage. The 80% target is reported only. The job does not fail below it." } >> "$GITHUB_STEP_SUMMARY" + - name: Upload the coverage report - if: ${{ !cancelled() && steps.tests.outcome != 'skipped' }} + if: ${{ !cancelled() && steps.coverage.outcome != 'skipped' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: coverage-report path: ${{ runner.temp }}/coverage/report.txt + overwrite: true + + - name: Check the results of the other jobs + if: ${{ !cancelled() }} + env: + RESULTS: ${{ toJSON(needs) }} + run: | + echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' + bad=$(echo "$RESULTS" | jq -r '[to_entries[] | select(.value.result != "success") | .key] | join(" ")') + if [ -n "$bad" ]; then + echo "::error::Jobs that did not succeed: $bad" + exit 1 + fi diff --git a/.gitignore b/.gitignore index f5d859ff38..015940e753 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ __pycache__/ # Distribution / packaging /build/ +/examples/**/build/ python/mlx/core python/mlx/share python/mlx/include @@ -79,4 +80,5 @@ uv.lock .cache/ # vim *.swp -wip \ No newline at end of file +.idea +wip diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 859d0f660e..bff933ce14 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,19 +10,15 @@ repos: hooks: - id: clang-format files: \.(h|cpp)$ -# Using this mirror lets us use mypyc-compiled black, which is about 2x faster -- repo: https://github.com/psf/black-pre-commit-mirror - rev: 26.1.0 - hooks: - - id: black - -- repo: https://github.com/pycqa/isort - rev: 7.0.0 - hooks: - - id: isort - args: - - --profile=black - repo: https://github.com/cheshirekow/cmake-format-precommit rev: v0.6.13 hooks: - id: cmake-format +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.16.10 + hooks: + - id: ruff-check + types_or: [python, pyi] + args: [--fix] + - id: ruff-format + types_or: [python, pyi] diff --git a/ACKNOWLEDGMENTS.md b/ACKNOWLEDGMENTS.md index 7005396e71..e8cb16af5a 100644 --- a/ACKNOWLEDGMENTS.md +++ b/ACKNOWLEDGMENTS.md @@ -12,6 +12,7 @@ MLX was developed with contributions from the following individuals: - Justin Deschenaux: Sine, Cosine, arange, randint, truncated normal, bernoulli, lion optimizer, Dropout2d, linear and logistic regression python example. - Diogo Da Cruz: Added `tri`, `tril`, `triu`, `tensordot`, `inner`, `outer`, `tile`, `StreamContext`, `stream`, safetensors support, `einsum`, and `einsum_path`. - Gabrijel Boduljak: Added `mlx.core.linalg`, implemented `norm` method and `InstanceNorm` layer. Implemented pooling layers and ``Upsample``. +- Aditya Dhulipala: Added `mlx.core.linalg.pinv`. - Hinrik Snær Guðmundsson: Added `atleast_1d`, `atleast_2d`, `atleast_3d` ops. - Luca Arnaboldi: Added `Ceil` and `Floor` ops; implemented pickling, copy and deepcopy for mlx arrays. - Brian Keene & Atila Orhon, with Argmax Inc.: Added `fast.scaled_dot_product_attention` @@ -22,6 +23,7 @@ MLX was developed with contributions from the following individuals: - Gökdeniz Gülmez: Added the `Muon (MomentUm Orthogonalized by Newton-schulz)` optimizer, and the `ReLU²` activation function. - katlun-lgtm: Added `reflect` and `symmetric` padding modes. - Erwin Zhang: Added `searchsorted`. Fixed the ring backend hanging when a peer disconnects. Improved JACCL error reporting. +- Oleksandr Zakharchuk: Added the cuSOLVER `cholesky` for the CUDA backend. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 120000 index 47dc3e3d86..0000000000 --- a/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -AGENTS.md \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index feb7ce5ebb..3f2330483d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,6 +43,7 @@ option(MLX_BUILD_SAFETENSORS "Include support for safetensors format" ON) option(MLX_BUILD_PYTHON_STUBS "Build stub files for python bindings" ON) option(MLX_METAL_JIT "Use JIT compilation for Metal kernels" OFF) option(MLX_USE_CCACHE "Use CCache for compilation cache when available" ON) +option(MLX_EXPORT_ALL_SYMBOLS "Export all symbols in the library" OFF) option(BUILD_SHARED_LIBS "Build mlx as a shared library" OFF) option(USE_SYSTEM_FMT "Use system's provided fmt library" OFF) option(USE_ASAN "Enable AddressSanitizer (ASan)" OFF) @@ -395,7 +396,7 @@ if(MLX_BUILD_PYTHON_BINDINGS) FetchContent_Declare( nanobind GIT_REPOSITORY https://github.com/wjakob/nanobind.git - GIT_TAG v2.15.0 + GIT_TAG v3.1.0 GIT_SHALLOW TRUE EXCLUDE_FROM_ALL) FetchContent_MakeAvailable(nanobind) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index e8d213c7b2..0000000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,132 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -[opensource-conduct@group.apple.com](mailto:opensource-conduct@group.apple.com). -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eaccfec88f..d3a4f444cd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,39 +1,97 @@ -# Contributing to MLX +# Welcome to the MLX community! -We want to make contributing to this project as easy and transparent as -possible. +We welcome contributors of all backgrounds and experience levels. A community with diverse perspectives builds software with lasting impact. -## AI Usage Policy +[🤝 How you can help](#how-you-can-help) · [⚙️ Setting up your environment](#setting-up-your-environment) · [📝 Submitting issues and pull requests](#submitting-issues-and-pull-requests) · [🔀 Pull requests](#pull-requests) · [❤️ Code of conduct](#code-of-conduct) -AI-generated code is allowed. What is not allowed is submitting code you do not -understand. You are 100% responsible for every line, however it was produced, -and must explicitly disclose the manner in which AI was employed. +## How you can help -It is strictly prohibited to use AI to write your posts for you (bug reports, -feature requests, pull request descriptions, Github discussions, responding to -humans, ...). +- Report bugs with clear, reproducible steps +- Improve documentation to make the project more accessible +- Triage issues by providing feedback, testing, and validation +- Propose and implement enhancements of all sizes +- Share your experience by speaking about MLX at conferences or meetups -## Pull Requests +## Setting up your environment -- Make sure new code is covered by tests. Add new tests if not, and confirm - the new tests fail in the main branch. -- If performance may be impacted, run benchmarks for both the main branch and - the pull request. +See [Build and Install](https://ml-explore.github.io/mlx/build/html/install.html) for setup instructions. + +## Submitting issues and pull requests + +We maintain high standards to ensure quality across the project. + +Your contributions are evaluated on: + +- Technical quality and correctness +- Adherence to existing conventions and architectural patterns +- Demonstrated understanding of the implementation and its implications +- Clarity of communication +- Maintainability + +You may use productivity tools, including AI-assisted coding, to help you work more efficiently. +However, you remain fully accountable for all submitted code, issues, pull requests, and comments. +AI-generated content must meet the same standards as human-written contributions. Review, validate, and, as needed, +refine or rearrange AI-assisted work so the final contribution reflects your human creativity, understanding, and +control. Use your voice and expression when producing written materials. Misuse of AI tools in your contributions +and conversations may be considered a violation of our [Code of Conduct](#code-of-conduct). + +### Issues + +Before submitting an issue: + +- Search [existing issues](../../issues) to avoid duplicates. +- Write a clear, concise title and a detailed description. Ensure all information is accurate and fully understood by you. +- Include precise steps to reproduce the issue, expected behavior, and actual behavior. Verify these steps yourself. +- Specify your environment, MLX version, and any relevant configurations. +- Explain the severity and impact of the problem. +- For security issues, please see the [MLX security advisories](https://github.com/ml-explore/mlx?tab=security-ov-file). Do **not** open a public GitHub issue. + +#### Proposing features + +We welcome feature requests. Describe the proposed changes needed and why they matter. Please do not start with a pull request. Use the issue template that best matches your needs. + +### Pull requests + +⚠️ **Important:** We recommend an issue for larger changes to the codebase. + +Pull requests represent proposed solutions or enhancements. When submitting a pull request, verify it meets these expectations: + +- They should match an open issue but may not always. +- Address the stated problem or feature request completely and effectively. You must fully understand and validate your proposed solution. +- Solutions must be thorough, handle edge cases, and integrate cleanly. +- Include comprehensive tests that validate your changes and prevent regressions. +- If performance may be impacted, run benchmarks for both the main branch and the pull request. - When providing benchmarking results, include scripts and reproduction steps. -- Format the code with `uvx pre-commit run --all` before submitting a pull - request. You can also install git hooks to run it automatically: + +#### Pull request style guide and format + +Follow our coding style and formatting to maintain a consistent, readable codebase. + +- Write comprehensive and clear documentation. Concisely explain the 'why' behind complex decisions. +- Write clear, concise, and descriptive commit messages. +- Format the code with `pre-commit run --all` before submitting a pull request. You can also install git hooks to run it automatically: ```shell pip install pre-commit pre-commit install ``` -## Issues +#### Testing + +All contributions require thorough testing. + +**Local Testing:** Ensure all existing tests pass before submitting: + +```bash +python3 python/tests/run.py +``` + +**Automated Tests:** New features and bug fixes require corresponding automated tests that validate the intended behavior and prevent regressions. + +#### Running CI -We use GitHub issues to track public bugs. Please ensure your description is -clear and has sufficient instructions to be able to reproduce the issue. +CI runs automatically on every pull request and needs to be approved by a maintainer before it will run. -## License +## Code of conduct -By contributing to MLX, you agree that your contributions will be licensed -under the LICENSE file in the root directory of this source tree. +We are committed to fostering a community where different experiences and perspectives come together to create and collaborate. Good collaboration depends on honest feedback and respect for the time and effort every contributor brings to this project. [Please review our Code of Conduct](https://github.com/ml-explore/.github/blob/main/CODE_OF_CONDUCT.md); all community members are expected to adhere to it. diff --git a/FORKDIFF.md b/FORKDIFF.md index 5047d49e80..8f7c9e18c2 100644 --- a/FORKDIFF.md +++ b/FORKDIFF.md @@ -26,7 +26,7 @@ to `main` (`.github/workflows/forkdiff-check.yml`) and fails on both: | Drift | Check | Why it matters | |-------|-------|----------------| -| **Rebase onto newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a rebase the old base makes upstream's own commits look like fork changes: thousands of files, none of them ours. | +| **Merge of newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a merge the old base makes upstream's own commits look like fork changes: thousands of files, none of them ours. | | **New fork change nobody described** | every path in `git diff --name-only base.hash HEAD` must match a section glob or a global `ignore` | An undescribed file is a change the page can't explain. | | **Section describing code we no longer carry** | every glob must match at least one changed path | Stale sections are as misleading as missing ones. | @@ -42,10 +42,19 @@ section with a short description). Files that are not code go under the top-level `ignore`. Keep globs specific: a `mlx/**` catch-all would swallow upstream's changes after a bad rebase and defeat the gate. -**Upstream sync policy (2026-09-25).** This fork does not merge or rebase onto -upstream. `base.hash` stays fixed. An upstream fix the fork needs is ported as -its own commit and described in its own `fork.yaml` section. The check keeps -comparing the fork against the fixed base: +**Upstream sync policy (2026-10-22).** The fork merges upstream `main` when +David directs it. Use a merge commit. Do not rebase. Each merge does these steps: + +1. Set `base.hash` to the new merge-base, `git merge-base HEAD upstream/main`. +2. Read each `fork.yaml` section again. Remove a section when upstream now has + the same change. Change a section when the merge changed the fork code. +3. Delete again the upstream workflows and actions that the fork removes. The + "Fork tooling" section lists them. +4. Run the check below until it passes. + +Between merges, port an upstream fix that the fork needs as its own commit. +Describe the port in its own `fork.yaml` section. The check compares the fork +with `base.hash`: ``` python3 -m pip install pyyaml diff --git a/benchmarks/numpy/time_utils.py b/benchmarks/numpy/time_utils.py index 163f007dce..738bd04d5e 100644 --- a/benchmarks/numpy/time_utils.py +++ b/benchmarks/numpy/time_utils.py @@ -13,7 +13,7 @@ def time_fn(fn, *args): num_iters = 100 tic = time.perf_counter() for _ in range(num_iters): - x = fn(*args) + _x = fn(*args) toc = time.perf_counter() msec = 1e3 * (toc - tic) / num_iters diff --git a/benchmarks/python/blas/bench_gemm.py b/benchmarks/python/blas/bench_gemm.py index ee358a95d8..bdf6c46ff5 100644 --- a/benchmarks/python/blas/bench_gemm.py +++ b/benchmarks/python/blas/bench_gemm.py @@ -2,7 +2,6 @@ import argparse import math -import os import subprocess import time @@ -148,7 +147,8 @@ def bench_shape(B, M, N, K, np_dtype, transpose="nn"): if not np.allclose(c_mlx, c_npy.astype(np_dtype), atol=atol): print( - f"Failed at {(B, M, N, K)} [transpose = {transpose}] with max(|a - b|) = {np.max(np.abs(c_npy - c_mlx))}" + f"Failed at {(B, M, N, K)} [transpose = {transpose}] with max(|a - b|) = " + f"{np.max(np.abs(c_npy - c_mlx))}" ) return time_mlx, time_torch @@ -185,7 +185,8 @@ def get_gflop_count(B, M, N, K): diff = gflops_mx / gflops_pt - 1.0 print( - f"{B:3d}, {M:4d}, {N:4d}, {K:4d}, {dtype}, {transpose}, {gflops_pt:05.3f}, {gflops_mx:05.3f}, {100.0 * diff:+5.2f}%" + f"{B:3d}, {M:4d}, {N:4d}, {K:4d}, {dtype}, {transpose}, " + f"{gflops_pt:05.3f}, {gflops_mx:05.3f}, {100.0 * diff:+5.2f}%" ) if gflops_pt >= 2.0 * gflops_mx: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/blas/bench_gemv.py b/benchmarks/python/blas/bench_gemv.py index 3cfc5eba41..94b5d169c1 100644 --- a/benchmarks/python/blas/bench_gemv.py +++ b/benchmarks/python/blas/bench_gemv.py @@ -114,7 +114,8 @@ def bench_lens(in_vec_len, out_vec_len, np_dtype, transpose=False): if not np.allclose(c_mlx, c_npy, atol=2e-5): print( - f"Failed at {shape_mat} [transpose = {transpose}] with max(|a - b|) = {np.max(np.abs(c_npy - c_mlx))}" + f"Failed at {shape_mat} [transpose = {transpose}] with max(|a - b|) = " + f"{np.max(np.abs(c_npy - c_mlx))}" ) return time_mlx, time_torch diff --git a/benchmarks/python/block_masked_mm_bench.py b/benchmarks/python/block_masked_mm_bench.py index bcfeb1c4f8..58abd3fc3a 100644 --- a/benchmarks/python/block_masked_mm_bench.py +++ b/benchmarks/python/block_masked_mm_bench.py @@ -101,7 +101,10 @@ def main(): "1024x1024x1024x32x0.0," "1024x1024x1024x32x0.9" ), - help="Comma-separated MxNxKxBSxSparsity list. Sparsity=fraction of blocks zeroed.", + help=( + "Comma-separated MxNxKxBSxSparsity list. " + "Sparsity=fraction of blocks zeroed." + ), ) parser.add_argument( "--dtype", diff --git a/benchmarks/python/comparative/bench_mlx.py b/benchmarks/python/comparative/bench_mlx.py index 4e6ba04f8e..dff9271864 100644 --- a/benchmarks/python/comparative/bench_mlx.py +++ b/benchmarks/python/comparative/bench_mlx.py @@ -72,12 +72,17 @@ def _quant_matmul(x, w, s, b, transpose, group_size, bits): quant_matmul = { + "quant_matmul_32_1": partial(_quant_matmul, transpose=False, group_size=32, bits=1), "quant_matmul_32_2": partial(_quant_matmul, transpose=False, group_size=32, bits=2), "quant_matmul_32_4": partial(_quant_matmul, transpose=False, group_size=32, bits=4), "quant_matmul_32_8": partial(_quant_matmul, transpose=False, group_size=32, bits=8), + "quant_matmul_64_1": partial(_quant_matmul, transpose=False, group_size=64, bits=1), "quant_matmul_64_2": partial(_quant_matmul, transpose=False, group_size=64, bits=2), "quant_matmul_64_4": partial(_quant_matmul, transpose=False, group_size=64, bits=4), "quant_matmul_64_8": partial(_quant_matmul, transpose=False, group_size=64, bits=8), + "quant_matmul_128_1": partial( + _quant_matmul, transpose=False, group_size=128, bits=1 + ), "quant_matmul_128_2": partial( _quant_matmul, transpose=False, group_size=128, bits=2 ), @@ -87,6 +92,9 @@ def _quant_matmul(x, w, s, b, transpose, group_size, bits): "quant_matmul_128_8": partial( _quant_matmul, transpose=False, group_size=128, bits=8 ), + "quant_matmul_t_32_1": partial( + _quant_matmul, transpose=True, group_size=32, bits=1 + ), "quant_matmul_t_32_2": partial( _quant_matmul, transpose=True, group_size=32, bits=2 ), @@ -96,6 +104,9 @@ def _quant_matmul(x, w, s, b, transpose, group_size, bits): "quant_matmul_t_32_8": partial( _quant_matmul, transpose=True, group_size=32, bits=8 ), + "quant_matmul_t_64_1": partial( + _quant_matmul, transpose=True, group_size=64, bits=1 + ), "quant_matmul_t_64_2": partial( _quant_matmul, transpose=True, group_size=64, bits=2 ), @@ -105,6 +116,9 @@ def _quant_matmul(x, w, s, b, transpose, group_size, bits): "quant_matmul_t_64_8": partial( _quant_matmul, transpose=True, group_size=64, bits=8 ), + "quant_matmul_t_128_1": partial( + _quant_matmul, transpose=True, group_size=128, bits=1 + ), "quant_matmul_t_128_2": partial( _quant_matmul, transpose=True, group_size=128, bits=2 ), @@ -175,13 +189,6 @@ def relu(x): mx.eval(y) -def leaky_relu(x: mx.array): - y = x - for i in range(100): - y = nn.leaky_relu(y) - mx.eval(y) - - def prelu(x: mx.array): y = x for i in range(100): @@ -189,13 +196,6 @@ def prelu(x: mx.array): mx.eval(y) -def softplus(x: mx.array): - y = x - for i in range(100): - y = nn.softplus(y) - mx.eval(y) - - def mish(x: mx.array): y = x for i in range(100): @@ -287,7 +287,6 @@ def rope(x): *_, N, D = x.shape ys = [] for i in range(10): - shape = x.shape x = mx.reshape(x, (-1, N, D)) positions = mx.arange(N) freqs = mx.exp(mx.arange(0.0, D // 2) / math.log(10000 / (D // 2 - 1))) diff --git a/benchmarks/python/comparative/compare.py b/benchmarks/python/comparative/compare.py index aa81369fe2..8fde177459 100644 --- a/benchmarks/python/comparative/compare.py +++ b/benchmarks/python/comparative/compare.py @@ -48,15 +48,23 @@ def search(x): def make_predicate(positive_filter, negative_filter): if positive_filter is not None: positive_filter_search = make_regex_search(positive_filter) - positive_filter = lambda x: all(positive_filter_search(x)) + + def positive_filter(x): + return all(positive_filter_search(x)) else: - positive_filter = lambda x: True + + def positive_filter(x): + return True if negative_filter is not None: negative_filter_search = make_regex_search(negative_filter) - negative_filter = lambda x: not any(negative_filter_search(x)) + + def negative_filter(x): + return not any(negative_filter_search(x)) else: - negative_filter = lambda x: True + + def negative_filter(x): + return True def predicate(x): return positive_filter(x) and negative_filter(x) @@ -83,13 +91,19 @@ def predicate(x): _filter = make_predicate(args.filter, args.negative_filter) if args.mlx_dtypes: - compare_filtered = lambda x: ( - compare_mlx_dtypes(x.split() + rest, args.mlx_dtypes[0], args.mlx_dtypes[1]) - if _filter(x) - else None - ) + + def compare_filtered(x): + return ( + compare_mlx_dtypes( + x.split() + rest, args.mlx_dtypes[0], args.mlx_dtypes[1] + ) + if _filter(x) + else None + ) else: - compare_filtered = lambda x: compare(x.split() + rest) if _filter(x) else None + + def compare_filtered(x): + return compare(x.split() + rest) if _filter(x) else None # Binary ops compare_filtered("add --size 10x1024x128 --size 1x1024x128 --cpu") @@ -150,13 +164,15 @@ def predicate(x): "matmul --size 16x768x768 --size 16x768x768 --transpose= --transpose 0,2,1" ) compare_filtered( - "matmul --size 16x768x768 --size 16x768x768 --transpose= --transpose 0,2,1 --cpu" + "matmul --size 16x768x768 --size 16x768x768 --transpose= --transpose 0,2,1 " + "--cpu" ) compare_filtered( "matmul --size 16x768x128 --size 16x768x128 --transpose= --transpose 0,2,1" ) compare_filtered( - "matmul --size 16x768x128 --size 16x768x128 --transpose= --transpose 0,2,1 --cpu" + "matmul --size 16x768x128 --size 16x768x128 --transpose= --transpose 0,2,1 " + "--cpu" ) compare_filtered("matmul --size 512x8192 --size 8192x512") compare_filtered("matmul --size 512x8192 --size 8192x512 --cpu") @@ -185,7 +201,8 @@ def predicate(x): compare_filtered("matmul --size 32x1x1000 --size 32x1000x128 --cpu") compare_filtered("matmul --size 32x1x1000 --size 32x1000x128") compare_filtered( - "matmul --size 32x1x1000 --size 32x128x1000 --transpose= --transpose 0,2,1 --cpu" + "matmul --size 32x1x1000 --size 32x128x1000 --transpose= --transpose 0,2,1 " + "--cpu" ) compare_filtered( "matmul --size 32x1x1000 --size 32x128x1000 --transpose= --transpose 0,2,1" @@ -218,7 +235,8 @@ def predicate(x): compare_filtered("step --size 32x16x1024 --cpu") compare_filtered("selu --size 32x16x1024") compare_filtered("selu --size 32x16x1024 --cpu") - # compare_filtered("mish --size 32x16x1024") NOTE: Torch does not implement Mish in MPS atm + # NOTE: Torch does not implement Mish in MPS atm + # compare_filtered("mish --size 32x16x1024") compare_filtered("mish --size 32x16x1024 --cpu") compare_filtered("prelu --size 32x16x1024") compare_filtered("prelu --size 32x16x1024 --cpu") diff --git a/benchmarks/python/conv1d_bench.py b/benchmarks/python/conv1d_bench.py index 0306a3e086..e1e15302fa 100644 --- a/benchmarks/python/conv1d_bench.py +++ b/benchmarks/python/conv1d_bench.py @@ -1,6 +1,5 @@ import argparse import math -import os import subprocess import time @@ -53,10 +52,10 @@ def pt_conv_1D(a, b): return pt_conv_1D -def bench_shape(N, iH, C, wH, O, strides, padding, np_dtype, groups): +def bench_shape(N, iH, C, wH, OC, strides, padding, np_dtype, groups): scale = 1.0 / math.sqrt(wH * C) a_np = np.random.uniform(0, 0.5, (N, iH, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, wH, int(C / groups))).astype(np_dtype) + b_np = np.random.uniform(-scale, scale, (OC, wH, int(C / groups))).astype(np_dtype) a_mx = mx.array(a_np) b_mx = mx.array(b_np) @@ -83,7 +82,9 @@ def bench_shape(N, iH, C, wH, O, strides, padding, np_dtype, groups): if not np.allclose(out_pt, out_mx, atol=atol): print( - 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))}" + f"Failed at {(N, iH, C)}, {(OC, wH, C)} [strides = {strides}, padding = " + f"{padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -108,15 +109,16 @@ def bench_shape(N, iH, C, wH, O, strides, padding, np_dtype, groups): for dtype in dtypes: print("(N, iH, C), (O, wH, C), dtype, stride, pads, groups, diff%") - for N, iH, C, wH, O, strides, padding, groups in shapes: + for N, iH, C, wH, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, iH, C, wH, O, strides, padding, np_dtype, groups + N, iH, C, wH, OC, strides, padding, np_dtype, groups ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {iH:3d}, {C:3d}), ({O:3d}, {wH:2d}, {C:3d}), {dtype}, {strides:5d}, {padding:4d}, {groups:6d}, {100. * diff:+5.2f}%" + f"({N}, {iH:3d}, {C:3d}), ({OC:3d}, {wH:2d}, {C:3d}), {dtype}, " + f"{strides:5d}, {padding:4d}, {groups:6d}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: diff --git a/benchmarks/python/conv2d_bench_cpu.py b/benchmarks/python/conv2d_bench_cpu.py index d560ae1b3a..46575f440c 100644 --- a/benchmarks/python/conv2d_bench_cpu.py +++ b/benchmarks/python/conv2d_bench_cpu.py @@ -47,10 +47,10 @@ def pt_conv_2D(a, b): return pt_conv_2D -def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kH * kH * C) a_np = np.random.uniform(0, 0.5, (N, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kH, kW, int(C / groups))).astype( np_dtype ) @@ -77,7 +77,9 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, H, W, C)}, {(O, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, H, W, C)}, {(OC, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -111,17 +113,19 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): for dtype in dtypes: print( - "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, " + "diff%" ) - for N, H, W, C, kH, kW, O, strides, padding, groups in shapes: + for N, H, W, C, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype + N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kH:2d}, {kW:2d}, {C:3d}), " + f"{dtype}, {strides}, {padding}, {groups:7d}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv2d_train_bench_cpu.py b/benchmarks/python/conv2d_train_bench_cpu.py index d85587909d..c572226ad3 100644 --- a/benchmarks/python/conv2d_train_bench_cpu.py +++ b/benchmarks/python/conv2d_train_bench_cpu.py @@ -64,7 +64,7 @@ def step(params, image): mx.eval(state) end_time = time.perf_counter() - print(f"{i:3d}, time={(end_time-start_time) * 1000:7.2f} ms") + print(f"{i:3d}, time={(end_time - start_time) * 1000:7.2f} ms") total_time += (end_time - start_time) * 1000 return total_time @@ -119,7 +119,7 @@ def loss_fn(pred_image, image): end_time = time.perf_counter() - print(f"{i:3d}, time={(end_time-start_time) * 1000:7.2f} ms") + print(f"{i:3d}, time={(end_time - start_time) * 1000:7.2f} ms") total_time += (end_time - start_time) * 1000 return total_time @@ -130,13 +130,13 @@ def main(): time_mlx = bench_mlx(steps) time_torch = bench_torch(steps) - print(f"average time of MLX: {time_mlx/steps:9.2f} ms") + print(f"average time of MLX: {time_mlx / steps:9.2f} ms") print(f"total time of MLX: {time_mlx:9.2f} ms") - print(f"average time of PyTorch: {time_torch/steps:9.2f} ms") + print(f"average time of PyTorch: {time_torch / steps:9.2f} ms") print(f"total time of PyTorch: {time_torch:9.2f} ms") diff = time_torch / time_mlx - 1.0 - print(f"torch/mlx diff: {100. * diff:+5.2f}%") + print(f"torch/mlx diff: {100.0 * diff:+5.2f}%") if __name__ == "__main__": diff --git a/benchmarks/python/conv2d_transpose_bench_cpu.py b/benchmarks/python/conv2d_transpose_bench_cpu.py index 28f31f66a8..fcade3f9a1 100644 --- a/benchmarks/python/conv2d_transpose_bench_cpu.py +++ b/benchmarks/python/conv2d_transpose_bench_cpu.py @@ -50,10 +50,10 @@ def pt_conv_transpose_2D(a, b): return pt_conv_transpose_2D -def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kH * kH * C) a_np = np.random.uniform(0, 0.5, (N, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (int(O / groups), kH, kW, C)).astype( + b_np = np.random.uniform(-scale, scale, (int(OC / groups), kH, kW, C)).astype( np_dtype ) @@ -82,7 +82,9 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, H, W, C)}, {(O, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, H, W, C)}, {(OC, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -113,17 +115,19 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): for dtype in dtypes: print( - "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, " + "diff%" ) - for N, H, W, C, kH, kW, O, strides, padding, groups in shapes: + for N, H, W, C, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype + N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kH:2d}, {kW:2d}, {C:3d}), " + f"{dtype}, {strides}, {padding}, {groups:7d}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv3d_bench.py b/benchmarks/python/conv3d_bench.py index 91c62dfc3e..5d44d0bd15 100644 --- a/benchmarks/python/conv3d_bench.py +++ b/benchmarks/python/conv3d_bench.py @@ -47,11 +47,11 @@ def pt_conv_3D(a, b, b_prime): return pt_conv_3D -def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kD * kH * kW * C) a_np = np.random.uniform(0, 0.5, (N, D, H, W, C)) - b_np = np.random.uniform(-scale, scale, (O, kD, kH, kW, int(C / groups))) - b_prime_np = np.random.uniform(-scale, scale, (C, kD, kH, kW, int(O / groups))) + b_np = np.random.uniform(-scale, scale, (OC, kD, kH, kW, int(C / groups))) + b_prime_np = np.random.uniform(-scale, scale, (C, kD, kH, kW, int(OC / groups))) a_np, b_np, b_prime_np = map(lambda x: x.astype(np_dtype), (a_np, b_np, b_prime_np)) a_mx, b_mx, b_prime_mx = map(lambda x: mx.array(x), (a_np, b_np, b_prime_np)) @@ -97,7 +97,7 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, D, H, W, C)}, {(O, kD, kH, kW, C)} " + f"Failed at {(N, D, H, W, C)}, {(OC, kD, kH, kW, C)} " f"[strides = {strides}, padding = {padding}, groups = {groups}] " f"with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" ) @@ -130,23 +130,24 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype ) for dtype in dtypes: - print(f"\n{'=' * 120}" f"\n dtype: {dtype}" f"\n{'=' * 120}") + print(f"\n{'=' * 120}\n dtype: {dtype}\n{'=' * 120}") print( f"{'(N, D, H, W, C)':<26s} {'( O, kD, kH, kW, C)':<24s} " f"{'stride':<12s} {'pads':<12s} {'groups':>6s} " f"{'diff%':>7s} " f"{'MLX peak':>9s} {'MLX act':>8s} {'PT cur':>8s} {'PT drv':>8s}" ) - for N, D, H, W, C, kD, kH, kW, O, strides, padding, groups in shapes: + for N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch, mlx_peak, mlx_act, pt_cur, pt_drv = bench_shape( - N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype + N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kD:2d}, {kH:2d}, {kW:2d}, {C:3d}), " + f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kD:2d}, {kH:2d}, " + f"{kW:2d}, {C:3d}), " f"{strides}, {padding}, {groups:6d}, " - f"{100. * diff:+6.1f}% " + f"{100.0 * diff:+6.1f}% " f"{mlx_peak:8.1f} {mlx_act:7.1f} {pt_cur:7.1f} {pt_drv:7.1f}" ) diff --git a/benchmarks/python/conv3d_bench_cpu.py b/benchmarks/python/conv3d_bench_cpu.py index d3b263da85..39d0042941 100644 --- a/benchmarks/python/conv3d_bench_cpu.py +++ b/benchmarks/python/conv3d_bench_cpu.py @@ -47,10 +47,10 @@ def pt_conv_3D(a, b): return pt_conv_3D -def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kD * kH * kW * C) a_np = np.random.uniform(0, 0.5, (N, D, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kD, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kD, kH, kW, int(C / groups))).astype( np_dtype ) @@ -77,7 +77,9 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, D, H, W, C)}, {(O, kD, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, D, H, W, C)}, {(OC, kD, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -94,17 +96,20 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype for dtype in dtypes: print( - "(N, D, H, W, C), ( O, kD, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, D, H, W, C), ( O, kD, kH, kW, C), dtype, stride, " + "pads, groups, diff%" ) - for N, D, H, W, C, kD, kH, kW, O, strides, padding, groups in shapes: + for N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype + N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kD:2d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kD:2d}, {kH:2d}, " + f"{kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, " + f"{100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv3d_train_bench_cpu.py b/benchmarks/python/conv3d_train_bench_cpu.py index fee99ee76e..c25926746e 100644 --- a/benchmarks/python/conv3d_train_bench_cpu.py +++ b/benchmarks/python/conv3d_train_bench_cpu.py @@ -64,7 +64,7 @@ def step(params, image): mx.eval(state) end_time = time.perf_counter() - print(f"{i:3d}, time={(end_time-start_time) * 1000:7.2f} ms") + print(f"{i:3d}, time={(end_time - start_time) * 1000:7.2f} ms") total_time += (end_time - start_time) * 1000 return total_time @@ -119,7 +119,7 @@ def loss_fn(pred_image, image): end_time = time.perf_counter() - print(f"{i:3d}, time={(end_time-start_time) * 1000:7.2f} ms") + print(f"{i:3d}, time={(end_time - start_time) * 1000:7.2f} ms") total_time += (end_time - start_time) * 1000 return total_time @@ -130,13 +130,13 @@ def main(): time_mlx = bench_mlx(steps) time_torch = bench_torch(steps) - print(f"average time of MLX: {time_mlx/steps:9.2f} ms") + print(f"average time of MLX: {time_mlx / steps:9.2f} ms") print(f"total time of MLX: {time_mlx:9.2f} ms") - print(f"average time of PyTorch: {time_torch/steps:9.2f} ms") + print(f"average time of PyTorch: {time_torch / steps:9.2f} ms") print(f"total time of PyTorch: {time_torch:9.2f} ms") diff = time_torch / time_mlx - 1.0 - print(f"torch/mlx diff: {100. * diff:+5.2f}%") + print(f"torch/mlx diff: {100.0 * diff:+5.2f}%") if __name__ == "__main__": diff --git a/benchmarks/python/conv3d_transpose_bench_cpu.py b/benchmarks/python/conv3d_transpose_bench_cpu.py index 742d9d46b1..b23da4d320 100644 --- a/benchmarks/python/conv3d_transpose_bench_cpu.py +++ b/benchmarks/python/conv3d_transpose_bench_cpu.py @@ -51,10 +51,10 @@ def pt_conv_3D(a, b): return pt_conv_3D -def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kD * kH * kW * C) a_np = np.random.uniform(0, 0.5, (N, D, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kD, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kD, kH, kW, int(C / groups))).astype( np_dtype ) @@ -83,7 +83,9 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, D, H, W, C)}, {(O, kD, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, D, H, W, C)}, {(OC, kD, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -100,17 +102,20 @@ def bench_shape(N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype for dtype in dtypes: print( - "(N, D, H, W, C), ( O, kD, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, D, H, W, C), ( O, kD, kH, kW, C), dtype, stride, " + "pads, groups, diff%" ) - for N, D, H, W, C, kD, kH, kW, O, strides, padding, groups in shapes: + for N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, D, H, W, C, kD, kH, kW, O, strides, padding, groups, np_dtype + N, D, H, W, C, kD, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kD:2d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {D:3d}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kD:2d}, {kH:2d}, " + f"{kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, " + f"{100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv_bench.py b/benchmarks/python/conv_bench.py index f421963add..ca94263646 100644 --- a/benchmarks/python/conv_bench.py +++ b/benchmarks/python/conv_bench.py @@ -1,6 +1,5 @@ import argparse import math -import os import subprocess import time @@ -53,10 +52,10 @@ def pt_conv_2D(a, b): return pt_conv_2D -def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kH * kH * C) a_np = np.random.uniform(0, 0.5, (N, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kH, kW, int(C / groups))).astype( np_dtype ) @@ -85,7 +84,9 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, H, W, C)}, {(O, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, H, W, C)}, {(OC, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -119,17 +120,19 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): for dtype in dtypes: print( - "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, " + "diff%" ) - for N, H, W, C, kH, kW, O, strides, padding, groups in shapes: + for N, H, W, C, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype + N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kH:2d}, {kW:2d}, {C:3d}), " + f"{dtype}, {strides}, {padding}, {groups:7d}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv_transpose_bench.py b/benchmarks/python/conv_transpose_bench.py index 22522d8edf..938dd81df0 100644 --- a/benchmarks/python/conv_transpose_bench.py +++ b/benchmarks/python/conv_transpose_bench.py @@ -1,7 +1,5 @@ import argparse import math -import os -import subprocess import time import mlx.core as mx @@ -54,10 +52,10 @@ def pt_conv_transpose_2D(a, b): return pt_conv_transpose_2D -def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kH * kH * C) a_np = np.random.uniform(0, 0.5, (N, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kH, kW, int(C / groups))).astype( np_dtype ) @@ -88,7 +86,9 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, H, W, C)}, {(O, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, H, W, C)}, {(OC, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -119,17 +119,19 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): for dtype in dtypes: print( - "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, diff%" + "(N, H, W, C), ( O, kH, kW, C), dtype, stride, pads, groups, " + "diff%" ) - for N, H, W, C, kH, kW, O, strides, padding, groups in shapes: + for N, H, W, C, kH, kW, OC, strides, padding, groups in shapes: np_dtype = getattr(np, dtype) time_mlx, time_torch = bench_shape( - N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype + N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kH:2d}, {kW:2d}, {C:3d}), {dtype}, {strides}, {padding}, {groups:7d}, {100. * diff:+5.2f}%" + f"({N}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kH:2d}, {kW:2d}, {C:3d}), " + f"{dtype}, {strides}, {padding}, {groups:7d}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/conv_unaligned_bench.py b/benchmarks/python/conv_unaligned_bench.py index 981d7b48bf..f95e43da60 100644 --- a/benchmarks/python/conv_unaligned_bench.py +++ b/benchmarks/python/conv_unaligned_bench.py @@ -47,10 +47,10 @@ def pt_conv_2D(a, b): return pt_conv_2D -def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): +def bench_shape(N, H, W, C, kH, kW, OC, strides, padding, groups, np_dtype): scale = 1.0 / math.sqrt(kH * kH * C) a_np = np.random.uniform(0, 0.5, (N, H, W, C)).astype(np_dtype) - b_np = np.random.uniform(-scale, scale, (O, kH, kW, int(C / groups))).astype( + b_np = np.random.uniform(-scale, scale, (OC, kH, kW, int(C / groups))).astype( np_dtype ) @@ -79,7 +79,9 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): if not np.allclose(out_pt, out_mx, atol=atol): print( - f"Failed at {(N, H, W, C)}, {(O, kH, kW, C)} [strides = {strides}, padding = {padding}, groups = {groups}] with max(|a - b|) = {np.max(np.abs(out_pt - out_mx))}" + f"Failed at {(N, H, W, C)}, {(OC, kH, kW, C)} [strides = {strides}, " + f"padding = {padding}, groups = {groups}] with max(|a - b|) = " + f"{np.max(np.abs(out_pt - out_mx))}" ) return time_mlx, time_torch @@ -94,14 +96,15 @@ def bench_shape(N, H, W, C, kH, kW, O, strides, padding, groups, np_dtype): (4, 32, 32, 370, 7, 7, 128), (2, 320, 640, 21, 7, 7, 21), ) - for N, H, W, C, kh, kw, O in shapes: + for N, H, W, C, kh, kw, OC in shapes: time_mlx, time_torch = bench_shape( - N, H, W, C, kh, kw, O, (1, 1), (0, 0), 1, dtype + N, H, W, C, kh, kw, OC, (1, 1), (0, 0), 1, dtype ) diff = time_torch / time_mlx - 1.0 print( - f"({N}, {H:3d}, {W:3d}, {C:3d}), ({O:3d}, {kh:2d}, {kw:2d}, {C:3d}), {dtype}, {100. * diff:+5.2f}%" + f"({N}, {H:3d}, {W:3d}, {C:3d}), ({OC:3d}, {kh:2d}, {kw:2d}, {C:3d}), " + f"{dtype}, {100.0 * diff:+5.2f}%" ) if time_mlx >= 2.0 * time_torch: print("ATTENTION ^^^^^^^") diff --git a/benchmarks/python/distributed_bench.py b/benchmarks/python/distributed_bench.py index b6fcef19ea..0b59360417 100644 --- a/benchmarks/python/distributed_bench.py +++ b/benchmarks/python/distributed_bench.py @@ -26,7 +26,7 @@ def time_fn(fn, *args, **kwargs): num_iters = 100 tic = time.perf_counter() for _ in range(num_iters): - x = mx.eval(fn(*args, **kwargs)) + _x = mx.eval(fn(*args, **kwargs)) toc = time.perf_counter() msec = 1e3 * (toc - tic) / num_iters diff --git a/benchmarks/python/gated_delta_bench.py b/benchmarks/python/gated_delta_bench.py new file mode 100644 index 0000000000..1e0dfcef97 --- /dev/null +++ b/benchmarks/python/gated_delta_bench.py @@ -0,0 +1,237 @@ +import argparse +import csv +import itertools +import os +import time + +import mlx.core as mx + +RESET = "\033[0m" + +N_warmup = 8 +N_iter_bench = 80 +N_iter_func = 5 + + +def bench(f, *args): + for _ in range(N_warmup): + f(*args) + mx.synchronize() + + s = time.perf_counter_ns() + for _ in range(N_iter_bench): + f(*args) + mx.synchronize() + e = time.perf_counter_ns() + return (e - s) * 1e-9 + + +def do_kernel_bench(f, *args): + ys = [] + for _ in range(N_iter_func): + out, hf = f(*args) + ys.append(out) + ys.append(hf) + mx.eval(ys) + return ys + + +def do_grad_bench(f, *args): + ys = [] + for _ in range(N_iter_func): + ys.extend(f(*args)) + mx.eval(ys) + return ys + + +def make_grad_fn(): + def f(q, k, v, g, b, h0): + out, state = mx.fast.gated_delta_update(q, k, v, g, b, h0) + return out.sum() + state.sum() + + return mx.grad(f, argnums=(0, 1, 2, 3, 4, 5)) + + +def make_inputs(B, T, Hk, Hv, Dk, Dv): + mx.random.seed(42) + q = mx.random.normal(shape=(B, T, Hk, Dk)) + k = mx.random.normal(shape=(B, T, Hk, Dk)) + k = k / (mx.linalg.norm(k, axis=-1, keepdims=True) + 1e-6) + v = mx.random.normal(shape=(B, T, Hv, Dv)) + g = mx.random.normal(shape=(B, T, Hv)) * 0.1 - 1.0 + b = mx.sigmoid(mx.random.normal(shape=(B, T, Hv))) + h0 = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32) + mx.eval(q, k, v, g, b, h0) + return q, k, v, g, b, h0 + + +def benchmark_shape(B, T, Hk, Hv, Dk, Dv, chunk_sizes): + q, k, v, g, b, h0 = make_inputs(B, T, Hk, Hv, Dk, Dv) + + shape_str = f"B={B} T={T} Hk={Hk} Hv={Hv} Dk={Dk} Dv={Dv}" + denom = N_iter_bench * N_iter_func + + os.environ["GATED_DELTA_CHUNK"] = "0" + mx.eval(*mx.fast.gated_delta_update(q, k, v, g, b, initial_state=h0)) + ms_seq = ( + bench(do_kernel_bench, mx.fast.gated_delta_update, q, k, v, g, b, h0) + / denom + * 1e3 + ) + + speedups = [] + for C in (c for c in chunk_sizes if c != 0): + try: + os.environ["GATED_DELTA_CHUNK"] = str(C) + mx.eval(*mx.fast.gated_delta_update(q, k, v, g, b, initial_state=h0)) + ms_c = ( + bench(do_kernel_bench, mx.fast.gated_delta_update, q, k, v, g, b, h0) + / denom + * 1e3 + ) + speedups.append(ms_seq / ms_c if ms_c > 0 else float("nan")) + except Exception as ex: + print(f" chunk {C} failed: {ex}") + speedups.append(float("nan")) + + return shape_str, f"{ms_seq:.3f}", speedups, ms_seq + + +def run_benchmark(run_full, to_csv=False, csv_path="benchmark_results.csv"): + if run_full: + Bs = [1, 4, 8, 16] + Ts = [8, 64, 256, 512, 1024, 2048] + else: + Bs = [1, 8, 16] + Ts = [8, 512, 1024, 2048] + Hks, Hvs, Dks, Dvs = [16], [32], [128], [128] + + chunk_sizes = [0, 8, 16] + non_zero_Cs = [C for C in chunk_sizes if C != 0] + + headers = ["B", "T", "Hk", "Hv", "Dk", "Dv", "time_seq (ms)"] + [ + f"C={C} (speedup)" for C in non_zero_Cs + ] + + col_widths = [6, 6, 6, 6, 6, 6, 15] + [25] * len(non_zero_Cs) + fmt = "".join(f"{{:<{w}}}" for w in col_widths) + + rows = [] + + print(fmt.format(*headers)) + print("-" * sum(col_widths)) + + for B, T, Hk, Hv, Dk, Dv in itertools.product(Bs, Ts, Hks, Hvs, Dks, Dvs): + shapes_s, base_time_s, speedups, base_time = benchmark_shape( + B, T, Hk, Hv, Dk, Dv, chunk_sizes + ) + row = [f"{B}", f"{T}", f"{Hk}", f"{Hv}", f"{Dk}", f"{Dv}", base_time_s] + for speed in speedups: + row.append(f"{(base_time / speed):<8.2f} ({speed:<5.2f}x)") + + print(fmt.format(*row), end="") + print(f"{RESET}") + + rows.append(row) + + if to_csv: + with open(csv_path, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(headers) + writer.writerows(rows) + print(f"\nResults also written to {csv_path}") + + +def benchmark_variants_shape(B, T, Hk, Hv, Dk, Dv, do_backward, variants): + q, k, v, g, b, h0 = make_inputs(B, T, Hk, Hv, Dk, Dv) + denom = N_iter_bench * N_iter_func + + if do_backward: + fn = make_grad_fn() + runner = do_grad_bench + else: + fn = mx.fast.gated_delta_update + runner = do_kernel_bench + + def time_one(variant): + os.environ["GATED_DELTA_VJP_FALLBACK"] = "1" if variant == "fallback" else "0" + C = "16" if variant == "nax" else "0" + if do_backward: + os.environ["GATED_DELTA_CHUNK"] = "16" + os.environ["GATED_DELTA_CHUNK_VJP"] = C + else: + os.environ["GATED_DELTA_CHUNK"] = C + mx.eval(*fn(q, k, v, g, b, h0)) + return bench(runner, fn, q, k, v, g, b, h0) / denom * 1e3 + + times = [] + for variant in variants: + try: + times.append(time_one(variant)) + except Exception as ex: + print(f" {variant} failed: {ex}") + times.append(float("nan")) + mx.clear_cache() + return times + + +def run_variants_benchmark(run_full, do_backward=False, do_fallback=False): + if run_full: + Bs = [1, 4, 8, 16] + Ts = [8, 32, 64, 128, 256, 512, 1024, 2048, 4096] + else: + Bs = [1, 8] + Ts = [8, 512, 1024] + if do_fallback: + Ts = [8, 32, 64, 128, 256, 512] + Hks, Hvs, Dks, Dvs = [16], [32], [128], [128] + + variants = ["seq", "nax"] + if do_fallback: + variants = ["fallback"] + variants + + headers = ["B", "T", "Hk", "Hv", "Dk", "Dv"] + headers += [f"{v} (ms)" for v in variants] + headers += [f"{v} (speedup)" for v in variants[1:]] + + col_widths = [6, 6, 6, 6, 6, 6] + [16] * len(variants) + [16] * (len(variants) - 1) + fmt = "".join(f"{{:<{w}}}" for w in col_widths) + + mode = "BACKWARD" if do_backward else "FORWARD" + print(f"\n=== {mode}: {' vs '.join(variants)} ===") + print(fmt.format(*headers)) + print("-" * sum(col_widths)) + + for B, T, Hk, Hv, Dk, Dv in itertools.product(Bs, Ts, Hks, Hvs, Dks, Dvs): + try: + times = benchmark_variants_shape( + B, T, Hk, Hv, Dk, Dv, do_backward, variants + ) + except Exception as ex: + print(f" B={B} T={T} failed: {ex}") + mx.clear_cache() + continue + + base = times[0] + row = [f"{B}", f"{T}", f"{Hk}", f"{Hv}", f"{Dk}", f"{Dv}"] + row += [f"{t:.3f}" for t in times] + row += [f"{base / t:.2f}x" if t > 0 else "nan" for t in times[1:]] + print(fmt.format(*row)) + print(RESET, end="") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Gated delta benchmark") + parser.add_argument("--full", "-f", action="store_true") + parser.add_argument("--csv", "-c", action="store_true") + parser.add_argument("--csv_out", "-co", default="benchmark_results.csv") + parser.add_argument("--fallback", "-fb", action="store_true") + parser.add_argument("--backward", "-bw", action="store_true") + args = parser.parse_args() + + if args.backward or args.fallback: + run_variants_benchmark( + args.full, do_backward=args.backward, do_fallback=args.fallback + ) + else: + run_benchmark(args.full, to_csv=args.csv, csv_path=args.csv_out) diff --git a/benchmarks/python/gather_mm_bench.py b/benchmarks/python/gather_mm_bench.py index ffeb734879..6783b841c9 100644 --- a/benchmarks/python/gather_mm_bench.py +++ b/benchmarks/python/gather_mm_bench.py @@ -7,7 +7,7 @@ D = 1024 M = 1024 E = 32 -I = 4 +num_indices = 4 def gather_sort(x, indices): @@ -38,8 +38,8 @@ def time_gather_mm(): x = mx.random.normal((N, 1, 1, D)) / 1024**0.5 w1 = mx.random.normal((E, M, D)) / 1024**0.5 w2 = mx.random.normal((E, D, M)) / 1024**0.5 - indices = (mx.random.uniform(shape=(N, I)) * E).astype(mx.uint32) - sorted_indices = mx.sort(indices.flatten()).reshape(N, I) + indices = (mx.random.uniform(shape=(N, num_indices)) * E).astype(mx.uint32) + sorted_indices = mx.sort(indices.flatten()).reshape(N, num_indices) mx.eval(x, w1, w2, indices, sorted_indices) def gather_mm(x, w1, w2, indices, sort): @@ -57,7 +57,7 @@ def gather_mm(x, w1, w2, indices, sort): time_fn(gather_mm, x, w1, w2, sorted_indices, False) time_fn(gather_mm, x, w1, w2, indices, True) - x = mx.random.normal((N * I, D)) / 1024**0.5 + x = mx.random.normal((N * num_indices, D)) / 1024**0.5 w1 = mx.random.normal((M, D)) / 1024**0.5 w2 = mx.random.normal((D, M)) / 1024**0.5 mx.eval(x, w1, w2) diff --git a/benchmarks/python/gather_qmm_bench.py b/benchmarks/python/gather_qmm_bench.py index c05db91992..713878a83a 100644 --- a/benchmarks/python/gather_qmm_bench.py +++ b/benchmarks/python/gather_qmm_bench.py @@ -7,7 +7,7 @@ D = 1024 M = 1024 E = 32 -I = 4 +num_indices = 4 def gather_sort(x, indices): @@ -46,8 +46,8 @@ def time_gather_qmm(): w2 = mx.random.normal((E, D, M)) / 1024**0.5 w1 = mx.quantize(w1) w2 = mx.quantize(w2) - indices = (mx.random.uniform(shape=(N, I)) * E).astype(mx.uint32) - sorted_indices = mx.sort(indices.flatten()).reshape(N, I) + indices = (mx.random.uniform(shape=(N, num_indices)) * E).astype(mx.uint32) + sorted_indices = mx.sort(indices.flatten()).reshape(N, num_indices) mx.eval(x, w1, w2, indices, sorted_indices) def gather_mm(x, w1, w2, indices, sort): @@ -65,7 +65,7 @@ def gather_mm(x, w1, w2, indices, sort): time_fn(gather_mm, x, w1, w2, sorted_indices, False) time_fn(gather_mm, x, w1, w2, indices, True) - x = mx.random.normal((N * I, D)) / 1024**0.5 + x = mx.random.normal((N * num_indices, D)) / 1024**0.5 w1 = mx.random.normal((M, D)) / 1024**0.5 w2 = mx.random.normal((D, M)) / 1024**0.5 w1 = mx.quantize(w1) @@ -82,13 +82,13 @@ def equivalent_matmul(x, w1, w2): def time_gather_qmm_short_runs(): # Many experts and few tokens, so each expert gets N * I / E = 16 rows. - N, E, I = 512, 256, 8 + N, E, num_indices = 512, 256, 8 x = mx.random.normal((N, 1, 1, D)) / 1024**0.5 w1 = mx.random.normal((E, M, D)) / 1024**0.5 w2 = mx.random.normal((E, D, M)) / 1024**0.5 w1 = mx.quantize(w1) w2 = mx.quantize(w2) - indices = (mx.random.uniform(shape=(N, I)) * E).astype(mx.uint32) + indices = (mx.random.uniform(shape=(N, num_indices)) * E).astype(mx.uint32) mx.eval(x, w1, w2, indices) def gather_mm(x, w1, w2, indices): diff --git a/benchmarks/python/gather_qqmm_bench.py b/benchmarks/python/gather_qqmm_bench.py new file mode 100644 index 0000000000..fddbf05bf5 --- /dev/null +++ b/benchmarks/python/gather_qqmm_bench.py @@ -0,0 +1,106 @@ +# Copyright © 2026 Apple Inc. + +import argparse + +import mlx.core as mx +from time_utils import time_fn + +SHAPES = { + "qwen3.6-35b-a3b-up": { + "experts": 256, + "top_k": 8, + "input": 2048, + "output": 512, + }, + "qwen3.6-35b-a3b-down": { + "experts": 256, + "top_k": 8, + "input": 512, + "output": 2048, + }, +} + + +def make_weights(shape): + weight = mx.random.uniform( + low=-0.5, + high=0.5, + shape=(shape["experts"], shape["output"], shape["input"]), + ).astype(mx.bfloat16) + quantized, scales = mx.quantize( + weight, + mode="nvfp4", + global_scale=mx.array(1.0, dtype=mx.float32), + ) + global_scale = mx.ones((shape["experts"],), dtype=mx.float32) + mx.eval(quantized, scales, global_scale) + return quantized, scales, global_scale + + +def gather_qqmm(x, weight, scales, global_scale_x, global_scale_w, rhs, sorted_): + return mx.gather_qqmm( + x, + weight, + scales, + rhs_indices=rhs, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + sorted_indices=sorted_, + ) + + +def benchmark(shape, workload, tokens): + weight, scales, global_scale_w = make_weights(shape) + global_scale_x = mx.array(1.0, dtype=mx.float32) + + if workload == "prompt": + routes = tokens * shape["top_k"] + x = mx.random.uniform( + low=-0.5, high=0.5, shape=(routes, 1, shape["input"]) + ).astype(mx.bfloat16) + rhs = mx.repeat( + mx.arange(shape["experts"], dtype=mx.uint32), + (routes + shape["experts"] - 1) // shape["experts"], + )[:routes] + sorted_ = True + elif workload == "matrix": + x = mx.random.uniform( + low=-0.5, + high=0.5, + shape=(shape["top_k"], tokens, shape["input"]), + ).astype(mx.bfloat16) + rhs = (mx.arange(shape["top_k"], dtype=mx.uint32) * 17) % shape["experts"] + sorted_ = False + else: + x = mx.random.uniform( + low=-0.5, high=0.5, shape=(1, 1, 1, shape["input"]) + ).astype(mx.bfloat16) + rhs = ( + (mx.arange(shape["top_k"], dtype=mx.uint32) * 17) % shape["experts"] + ).reshape(1, shape["top_k"]) + sorted_ = False + + mx.eval(x, rhs) + time_fn( + gather_qqmm, + x, + weight, + scales, + global_scale_x, + global_scale_w, + rhs, + sorted_, + msg=(f"{workload} routes={rhs.size} N={shape['output']} K={shape['input']}"), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--shape", choices=SHAPES, default="qwen3.6-35b-a3b-up") + parser.add_argument( + "--workload", choices=("prompt", "matrix", "decode"), default="prompt" + ) + parser.add_argument("--tokens", type=int, default=2048) + args = parser.parse_args() + benchmark(SHAPES[args.shape], args.workload, args.tokens) diff --git a/benchmarks/python/large_gemm_bench.py b/benchmarks/python/large_gemm_bench.py index 6f3b248658..9f084aae21 100644 --- a/benchmarks/python/large_gemm_bench.py +++ b/benchmarks/python/large_gemm_bench.py @@ -113,7 +113,7 @@ def bench_gemm(M, N, K, dtype, rtol): print( f"{M:5d} {N:5d} {K:6d} " - f"{mlx_mean*1000:7.2f}±{mlx_std*1000:5.2f} " - f"{torch_mean*1000:7.2f}±{torch_std*1000:5.2f} " + f"{mlx_mean * 1000:7.2f}±{mlx_std * 1000:5.2f} " + f"{torch_mean * 1000:7.2f}±{torch_std * 1000:5.2f} " f"{speedup:8.2f}x" ) diff --git a/benchmarks/python/layer_norm_bench.py b/benchmarks/python/layer_norm_bench.py index 29925de0b5..61e9bb8c52 100644 --- a/benchmarks/python/layer_norm_bench.py +++ b/benchmarks/python/layer_norm_bench.py @@ -3,12 +3,10 @@ from functools import partial import mlx.core as mx -import mlx.nn as nn from time_utils import time_fn def layer_norm(x, w, b, eps): - ot = x.dtype x = x.astype(mx.float32) mu = mx.mean(x, -1, keepdims=True) v = mx.var(x, -1, keepdims=True) @@ -22,8 +20,13 @@ def layer_norm(x, w, b, eps): def time_layer_norm(N, dt): L = 1024 - f1 = lambda x, w, b, y: (layer_norm(x, w, b, 1e-5) * y).sum() - f2 = lambda x, w, b, y: (mx.fast.layer_norm(x, w, b, 1e-5) * y).sum() + + def f1(x, w, b, y): + return (layer_norm(x, w, b, 1e-5) * y).sum() + + def f2(x, w, b, y): + return (mx.fast.layer_norm(x, w, b, 1e-5) * y).sum() + g1 = mx.grad(f1, argnums=(0, 1, 2)) g2 = mx.grad(f2, argnums=(0, 1, 2)) @@ -52,8 +55,12 @@ def layer_norm_grad_loop(g, x, w, b): time_fn(layer_norm_grad_loop, mx.compile(g1), x, w, b) time_fn(layer_norm_grad_loop, mx.compile(g2), x, w, b) - f1 = lambda x, y: (layer_norm(x, None, None, 1e-5) * y).sum() - f2 = lambda x, y: (mx.fast.layer_norm(x, None, None, 1e-5) * y).sum() + def f1(x, y): + return (layer_norm(x, None, None, 1e-5) * y).sum() + + def f2(x, y): + return (mx.fast.layer_norm(x, None, None, 1e-5) * y).sum() + g1 = mx.grad(f1, argnums=(0,)) g2 = mx.grad(f2, argnums=(0,)) diff --git a/benchmarks/python/qqmm_bench.py b/benchmarks/python/qqmm_bench.py new file mode 100644 index 0000000000..a0fd75d94d --- /dev/null +++ b/benchmarks/python/qqmm_bench.py @@ -0,0 +1,61 @@ +# Copyright © 2026 Apple Inc. + +import argparse + +import mlx.core as mx +from time_utils import time_fn + +SHAPES = { + "qwen3.6-35b-a3b-up": (512, 2048), + "qwen3.6-35b-a3b-down": (2048, 512), +} + + +def qqmm(x, weight, scales, global_scale_x, global_scale_w): + return mx.qqmm( + x, + weight, + scales, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + + +def benchmark(shape, tokens): + output_dims, input_dims = shape + mx.random.seed(0) + global_scale_x = mx.array(1.0, dtype=mx.float32) + global_scale_w = mx.array(1.0, dtype=mx.float32) + x = mx.random.uniform(low=-0.5, high=0.5, shape=(tokens, input_dims)).astype( + mx.bfloat16 + ) + weight = mx.random.uniform( + low=-0.5, high=0.5, shape=(output_dims, input_dims) + ).astype(mx.bfloat16) + weight, scales = mx.quantize( + weight, + mode="nvfp4", + global_scale=global_scale_w, + ) + mx.eval(x, weight, scales) + + time_fn( + qqmm, + x, + weight, + scales, + global_scale_x, + global_scale_w, + msg=( + f"mode=nvfp4 dtype=bfloat16 tokens={tokens} N={output_dims} K={input_dims}" + ), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--shape", choices=SHAPES, default="qwen3.6-35b-a3b-up") + parser.add_argument("--tokens", type=int, default=2048) + args = parser.parse_args() + benchmark(SHAPES[args.shape], args.tokens) diff --git a/benchmarks/python/rms_norm_bench.py b/benchmarks/python/rms_norm_bench.py index 50f3a40b08..85ab8fba9c 100644 --- a/benchmarks/python/rms_norm_bench.py +++ b/benchmarks/python/rms_norm_bench.py @@ -1,7 +1,6 @@ # Copyright © 2023-2024 Apple Inc. import mlx.core as mx -import mlx.nn as nn from time_utils import time_fn @@ -16,8 +15,12 @@ def rms_norm(x, w, eps): def time_rms_norm(): - f1 = lambda x, w, y: (rms_norm(x, w, 1e-5) * y).sum() - f2 = lambda x, w, y: (mx.fast.rms_norm(x, w, 1e-5) * y).sum() + def f1(x, w, y): + return (rms_norm(x, w, 1e-5) * y).sum() + + def f2(x, w, y): + return (mx.fast.rms_norm(x, w, 1e-5) * y).sum() + g1 = mx.grad(f1, argnums=(0, 1)) g2 = mx.grad(f2, argnums=(0, 1)) @@ -37,8 +40,12 @@ def rms_norm_loop(g, x, w): time_fn(rms_norm_loop, mx.compile(g1), x, w) time_fn(rms_norm_loop, mx.compile(g2), x, w) - f1 = lambda x, y: (rms_norm(x, None, 1e-5) * y).sum() - f2 = lambda x, y: (mx.fast.rms_norm(x, None, 1e-5) * y).sum() + def f1(x, y): + return (rms_norm(x, None, 1e-5) * y).sum() + + def f2(x, y): + return (mx.fast.rms_norm(x, None, 1e-5) * y).sum() + g1 = mx.grad(f1, argnums=(0,)) g2 = mx.grad(f2, argnums=(0,)) diff --git a/benchmarks/python/sdpa_bench.py b/benchmarks/python/sdpa_bench.py index 7dfc7e0d1d..1d1c7b979e 100644 --- a/benchmarks/python/sdpa_bench.py +++ b/benchmarks/python/sdpa_bench.py @@ -74,7 +74,6 @@ def mlx_ref_attn(q, k, v, scale=1.0, mask=None): scores = q @ mx.swapaxes(k, -1, -2) if mask is not None: - if mask == "causal": q_offset = max(0, kL - L) q_indices = mx.arange(q_offset, q_offset + L) @@ -149,19 +148,110 @@ def bench_shape( if not mx.allclose(o_mlx_fused, o_mlx_unfused, atol=atol, rtol=atol): print( - f"Failed at (B: {B}, qsl: {qsl}, ksl: {ksl}, head_dim: {head_dim}, n_qh: {n_q_heads}, n_kvh: {n_kv_heads}, mask: {mask_in}) [tpose = {transpose}] with max(|a - b|) = {mx.max(mx.abs(o_mlx_unfused - o_mlx_fused)):3.2e}" + f"Failed at (B: {B}, qsl: {qsl}, ksl: {ksl}, head_dim: {head_dim}, n_qh: " + f"{n_q_heads}, n_kvh: {n_kv_heads}, mask: {mask_in}) [tpose = {transpose}] " + f"with max(|a - b|) = {mx.max(mx.abs(o_mlx_unfused - o_mlx_fused)):3.2e}" ) return time_mlx_fused, time_mlx_unfused +def set_vjp_fallback(enabled): + os.environ["MLX_SDPA_VJP_FALLBACK"] = "1" if enabled else "0" + + +def mlx_fused_attn_grads(q, k, v, scale, cotan, mask=None, transpose=False): + def f(q_, k_, v_): + return do_attention(mlx_fused_attn, q_, k_, v_, scale, mask, transpose) + + _, grads = mx.vjp(f, [q, k, v], [cotan]) + return grads + + +def do_attention_vjp_bench(q, k, v, scale, cotan, mask=None, transpose=False): + def f(q_, k_, v_): + return do_attention(mlx_fused_attn, q_, k_, v_, scale, mask, transpose) + + dq = q + + for i in range(N_iter_func): + _, (dq, dk, dv) = mx.vjp(f, [dq, k, v], [cotan]) + + mx.eval([dq, dk, dv]) + return dq + + +def peak_mem_vjp(q, k, v, scale, cotan, mask=None, transpose=False): + mx.clear_cache() + mx.reset_peak_memory() + grads = mlx_fused_attn_grads(q, k, v, scale, cotan, mask, transpose) + mx.eval(grads) + peak = mx.get_peak_memory() / float(1024.0**3) + del grads + mx.clear_cache() + return peak + + +def max_rel_diff(a_list, b_list): + rel = 0.0 + for a, b in zip(a_list, b_list): + denom = mx.maximum(mx.max(mx.abs(a)), mx.array(1e-6, mx.float32)) + rel = max(rel, (mx.max(mx.abs(a - b)) / denom).item()) + return rel + + +def bench_shape_vjp( + B, qsl, ksl, head_dim, n_q_heads, n_kv_heads, dtype, transpose=True, mask_in=None +): + q_mx, k_mx, v_mx, scale, mask = prepare_inputs( + B, qsl, ksl, head_dim, n_q_heads, n_kv_heads, mask_in, transpose, dtype + ) + cotan = mx.array(np.random.normal(0.0, 1.0, q_mx.shape).astype(getattr(np, dtype))) + mx.eval(cotan) + + set_vjp_fallback(True) + time_fallback = bench( + do_attention_vjp_bench, q_mx, k_mx, v_mx, scale, cotan, mask, transpose + ) + mem_fallback = peak_mem_vjp(q_mx, k_mx, v_mx, scale, cotan, mask, transpose) + g_fallback = mlx_fused_attn_grads(q_mx, k_mx, v_mx, scale, cotan, mask, transpose) + mx.eval(g_fallback) + + set_vjp_fallback(False) + time_vjp = bench( + do_attention_vjp_bench, q_mx, k_mx, v_mx, scale, cotan, mask, transpose + ) + mem_vjp = peak_mem_vjp(q_mx, k_mx, v_mx, scale, cotan, mask, transpose) + g_vjp = mlx_fused_attn_grads(q_mx, k_mx, v_mx, scale, cotan, mask, transpose) + mx.eval(g_vjp) + + rel = max_rel_diff(g_fallback, g_vjp) + # nax truncates so the accuracy is not full fp32 + atol = 5e-3 + + if rel > atol: + print( + f"Failed at (B: {B}, qsl: {qsl}, ksl: {ksl}, head_dim: {head_dim}, n_qh: " + f"{n_q_heads}, n_kvh: {n_kv_heads}, mask: {mask_in}) [tpose = {transpose}] " + f"with max rel = {rel:3.2e}" + ) + + return time_vjp, time_fallback, mem_vjp, mem_fallback, rel + + def get_gflop_count(B, M, N, K): return float(2.0 * N_iter_bench * N_iter_func * B * M * N * K) / float(1024.0**3) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run gemm benchmarks") - + parser.add_argument( + "-bw", + "--backward", + action="store_true", + help="benchmark the vjp against the fallback", + ) + args = parser.parse_args() dtypes = ("float16", "float32")[:1] transposes = (False,) @@ -228,10 +318,46 @@ def get_gflop_count(B, M, N, K): shapes = shapes_64 + shapes_72 + shapes_80 + shapes_96 + shapes_128 + shapes_256 + if args.backward: + masks = [None, "causal"] + + print( + " B, qsl, ksl, hdim, n_qh, n_kvh, t, dtype, mask, t_fall, " + "t_vjp, speedup, m_fall, m_vjp, mem_x, rel" + ) + + for dtype in ["float32"]: + for transpose in transposes: + for B, qsl, ksl, head_dim, n_q_heads, n_kv_heads in shapes: + for mask_in in masks: + t_vjp, t_fall, m_vjp, m_fall, rel = bench_shape_vjp( + B, + qsl, + ksl, + head_dim, + n_q_heads, + n_kv_heads, + dtype, + transpose, + mask_in, + ) + speedup = t_fall / t_vjp + mem_x = m_fall / max(m_vjp, 1e-9) + t_str = 1 if transpose else 0 + print( + f"{B:3d}, {qsl:5d}, {ksl:5d}, {head_dim:4d}, " + f"{n_q_heads:4d}, {n_kv_heads:5d}, {t_str:1d}, {dtype}, " + f"{str(mask_in):>8}, {t_fall: 2.3f}, {t_vjp: 2.3f}, " + f"{speedup:6.2f}x, {m_fall:6.2f}, {m_vjp:6.2f}, " + f"{mem_x:5.2f}x, {rel:3.1e}" + ) + exit(0) + masks = [None, "bool", "causal"] print( - " B, qsl, ksl, hdim, n_qh, n_kvh, t, dtype, mask, t_unfs, t_fuse, diff%" + " B, qsl, ksl, hdim, n_qh, n_kvh, t, dtype, mask, t_unfs, t_fuse, " + "diff%" ) for dtype in dtypes: @@ -252,5 +378,8 @@ def get_gflop_count(B, M, N, K): diff = time_mlx_unfused / time_mlx_fused - 1.0 t_str = 1 if transpose else 0 print( - f"{B:3d}, {qsl:5d}, {ksl:5d}, {head_dim:4d}, {n_q_heads:4d}, {n_kv_heads:5d}, {t_str:1d}, {dtype}, {str(mask_in):>8}, {time_mlx_unfused: 2.3f}, {time_mlx_fused: 2.3f}, {100. * diff:+5.2f}%" + f"{B:3d}, {qsl:5d}, {ksl:5d}, {head_dim:4d}, {n_q_heads:4d}, " + f"{n_kv_heads:5d}, {t_str:1d}, {dtype}, {str(mask_in):>8}, " + f"{time_mlx_unfused: 2.3f}, {time_mlx_fused: 2.3f}, " + f"{100.0 * diff:+5.2f}%" ) diff --git a/benchmarks/python/sdpa_vector_bench.py b/benchmarks/python/sdpa_vector_bench.py index 546bff84c2..983093029c 100644 --- a/benchmarks/python/sdpa_vector_bench.py +++ b/benchmarks/python/sdpa_vector_bench.py @@ -1,95 +1,209 @@ +"""Benchmark single-token decode through the Metal SDPA vector kernels. + +Run the same command after building the PR parent and head revisions: + + python benchmarks/python/sdpa_vector_bench.py + +The default shapes select the generic ``sdpa_vector_2pass_1`` kernel changed +by this PR. Use ``--shape QH,KVH,CTX,D`` to benchmark additional shapes. +""" + import argparse import math +import statistics +import time import mlx.core as mx -from time_utils import time_fn - -L = 16384 -H = 32 -H_k = H // 4 -D = 128 -V = 128 -dtype = mx.float16 -loops = 10 - - -def upproject(x, w): - if w is None: - return x - else: - return x @ w.T - - -def attention(q, k, v, mask=None, w=None): - def _sdpa(q, k, v): - B, Hq, L, D = q.shape - _, Hk, S, _ = k.shape - _, _, _, V = v.shape - q = q.reshape(B, Hk, Hq // Hk, L, D) - k = k[:, :, None, :, :] - v = v[:, :, None, :, :] - s = q @ k.transpose(0, 1, 2, 4, 3) - if mask is not None: - m = mx.broadcast_to(mask, (B, Hq, L, S)).reshape(B, Hk, Hq // Hk, L, S) - s = mx.where(m, s, mx.finfo(s.dtype).min) - p = mx.softmax(s.astype(mx.float32), axis=-1).astype(s.dtype) - o = p @ v - return o.reshape(B, Hq, L, V) - - for i in range(loops): - q = _sdpa(q, k, v) - q = upproject(q, w) - return q - - -def sdpa(q, k, v, mask=None, w=None): - for i in range(loops): - q = mx.fast.scaled_dot_product_attention(q, k, v, scale=1.0, mask=mask) - q = upproject(q, w) - return q - - -def time_self_attention_primitives(): - mx.random.seed(3) - q = mx.random.uniform(shape=(1, H, 1, D)).astype(dtype) - k = mx.random.uniform(shape=(1, H_k, L, D)).astype(dtype) - v = mx.random.uniform(shape=(1, H_k, L, V)).astype(dtype) - w = mx.random.uniform(shape=(D, V)).astype(dtype) if V != D else None - mx.eval(q, k, v, w) - time_fn(attention, q, k, v, w=w) - - -def time_self_attention_sdpa(): - mx.random.seed(3) - q = mx.random.uniform(shape=(1, H, 1, D)).astype(dtype) - k = mx.random.uniform(shape=(1, H_k, L, D)).astype(dtype) - v = mx.random.uniform(shape=(1, H_k, L, V)).astype(dtype) - w = mx.random.uniform(shape=(D, V)).astype(dtype) if V != D else None - mx.eval(q, k, v, w) - time_fn(sdpa, q, k, v, w=w) - - -def time_self_attention_sdpa_with_mask(): - mx.random.seed(3) - q = mx.random.uniform(shape=(1, H, 1, D)).astype(dtype) - k = mx.random.uniform(shape=(1, H_k, L, D)).astype(dtype) - v = mx.random.uniform(shape=(1, H_k, L, V)).astype(dtype) - w = mx.random.uniform(shape=(D, V)).astype(dtype) if V != D else None - mask = mx.full((L,), True) - mask[L // 2 :] = False - mx.eval(q, k, v, mask, w) - - def sdpa_mask(*args): - return sdpa(*args, mask=mask, w=w) - - def attention_mask(*args): - return attention(*args, mask=mask, w=w) - - time_fn(attention_mask, q, k, v) - time_fn(sdpa_mask, q, k, v) + +DEFAULT_SHAPES = ( + # q_heads, kv_heads, context, head_dim + (32, 32, 4096, 128), + (32, 32, 32768, 128), + (4, 4, 65536, 128), + (8, 4, 4096, 128), + (8, 4, 32768, 128), + (16, 4, 4096, 128), + (16, 4, 32768, 128), + # GQA=8 selects the generic 2-pass kernel below context 8192. + (32, 4, 4096, 128), +) + + +def parse_shape(value): + try: + shape = tuple(int(x) for x in value.split(",")) + except ValueError as error: + raise argparse.ArgumentTypeError( + "shape must be q_heads,kv_heads,context,head_dim" + ) from error + if len(shape) != 4: + raise argparse.ArgumentTypeError( + "shape must be q_heads,kv_heads,context,head_dim" + ) + q_heads, kv_heads, context, head_dim = shape + if min(shape) <= 0 or q_heads % kv_heads != 0: + raise argparse.ArgumentTypeError( + "shape values must be positive and q_heads divisible by kv_heads" + ) + return shape + + +def kernel_path(q_heads, kv_heads, context, head_dim, architecture): + gqa = q_heads // kv_heads + device_class = architecture[-1] if architecture else "" + uses_two_pass = (device_class in ("d", "s") and context >= 1024) or ( + kv_heads < q_heads and context >= 4096 + ) + if not uses_two_pass: + return "vector-1pass" + + specialized_gqa = (gqa == 8 and head_dim in (64, 128)) or ( + gqa in (12, 16) and head_dim == 128 + ) + if specialized_gqa and context >= 8192: + return "gqa-specialized" + return "generic-2pass" + + +def reference_sdpa(q, k, v, scale): + n_repeats = q.shape[1] // k.shape[1] + if n_repeats > 1: + k = mx.repeat(k, n_repeats, axis=1) + v = mx.repeat(v, n_repeats, axis=1) + scores = (q @ mx.swapaxes(k, -1, -2)) * scale + probabilities = mx.softmax(scores.astype(mx.float32), axis=-1).astype(q.dtype) + return probabilities @ v + + +def run_chain(q, k, v, scale, chain): + out = q + for _ in range(chain): + out = mx.fast.scaled_dot_product_attention(out, k, v, scale=scale) + mx.eval(out) + + +def measure(q, k, v, scale, chain, warmup, iterations, rounds): + for _ in range(warmup): + run_chain(q, k, v, scale, chain) + + round_medians = [] + best = math.inf + for _ in range(rounds): + samples = [] + for _ in range(iterations): + start = time.perf_counter_ns() + run_chain(q, k, v, scale, chain) + elapsed = (time.perf_counter_ns() - start) * 1e-9 / chain + samples.append(elapsed) + best = min(best, min(samples)) + round_medians.append(statistics.median(samples)) + + return ( + best, + statistics.median(round_medians), + min(round_medians), + max(round_medians), + ) + + +def benchmark_shape(shape, args, architecture): + q_heads, kv_heads, context, head_dim = shape + scale = 1.0 / math.sqrt(head_dim) + + mx.random.seed(args.seed) + q = mx.random.normal((1, q_heads, 1, head_dim)).astype(mx.float16) + k = mx.random.normal((1, kv_heads, context, head_dim)).astype(mx.float16) + v = mx.random.normal((1, kv_heads, context, head_dim)).astype(mx.float16) + mx.eval(q, k, v) + + actual = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale) + expected = reference_sdpa(q, k, v, scale) + mx.eval(actual, expected) + error = mx.abs(actual.astype(mx.float32) - expected.astype(mx.float32)) + max_abs_error = error.max().item() + relative_linf_error = max_abs_error / max(mx.abs(expected).max().item(), 1e-9) + + best, median, median_low, median_high = measure( + q, + k, + v, + scale, + args.chain, + args.warmup, + args.iterations, + args.rounds, + ) + + # Logical traffic of the generic kernel: every query head streams one K + # and one V head. This is intentionally called logical bandwidth because + # shared KV heads can be served from cache on GQA shapes. + itemsize = 2 + logical_bytes = q_heads * context * head_dim * itemsize * 2 + logical_gbps = logical_bytes / median / 1e9 + + return { + "gqa": q_heads // kv_heads, + "path": kernel_path(*shape, architecture), + "best_us": best * 1e6, + "median_us": median * 1e6, + "median_low_us": median_low * 1e6, + "median_high_us": median_high * 1e6, + "logical_gbps": logical_gbps, + "max_abs_error": max_abs_error, + "relative_linf_error": relative_linf_error, + } + + +def main(): + parser = argparse.ArgumentParser( + description=( + "Benchmark single-token decode through the Metal sdpa_vector_2pass kernels." + ) + ) + parser.add_argument( + "--shape", + action="append", + type=parse_shape, + metavar="QH,KVH,CTX,D", + help="shape to benchmark; may be repeated", + ) + parser.add_argument("--chain", type=int, default=8) + parser.add_argument("--warmup", type=int, default=10) + parser.add_argument("--iterations", type=int, default=30) + parser.add_argument("--rounds", type=int, default=5) + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args() + + shapes = args.shape or DEFAULT_SHAPES + device_info = mx.device_info(mx.gpu) + architecture = device_info.get("architecture", "") + print( + f"device={device_info.get('device_name', 'unknown')} " + f"architecture={architecture}" + ) + print( + f"chain={args.chain} warmup={args.warmup} " + f"iterations={args.iterations} rounds={args.rounds}" + ) + print( + f"{'QH':>3} {'KVH':>3} {'GQA':>3} {'CTX':>6} {'D':>3} " + f"{'path':>15} {'best us':>9} {'median us [range]':>27} " + f"{'logical GB/s':>12} {'rel L-inf':>9}" + ) + for shape in shapes: + result = benchmark_shape(shape, args, architecture) + q_heads, kv_heads, context, head_dim = shape + print( + f"{q_heads:>3} {kv_heads:>3} {result['gqa']:>3} " + f"{context:>6} {head_dim:>3} {result['path']:>15} " + f"{result['best_us']:>9.1f} " + f"{result['median_us']:>9.1f} " + f"[{result['median_low_us']:>6.1f}," + f"{result['median_high_us']:>6.1f}] " + f"{result['logical_gbps']:>12.1f} " + f"{result['relative_linf_error']:>9.2e}" + ) if __name__ == "__main__": - time_self_attention_sdpa() - time_self_attention_primitives() - time_self_attention_sdpa_with_mask() + main() diff --git a/benchmarks/python/segmented_mm_bench.py b/benchmarks/python/segmented_mm_bench.py index 0823c2e041..9977a0b397 100644 --- a/benchmarks/python/segmented_mm_bench.py +++ b/benchmarks/python/segmented_mm_bench.py @@ -133,7 +133,8 @@ def main(): mlx_dtype = MLX_DTYPES[args.dtype] print( - f"dtype={args.dtype} warmup={args.warmup} iters={args.iters} segments={args.segments}" + f"dtype={args.dtype} warmup={args.warmup} iters={args.iters} " + f"segments={args.segments}" ) headers = [ diff --git a/benchmarks/python/slice_update_bench.py b/benchmarks/python/slice_update_bench.py index 60f12b9814..a1a78ac290 100644 --- a/benchmarks/python/slice_update_bench.py +++ b/benchmarks/python/slice_update_bench.py @@ -105,5 +105,6 @@ def slice_update(dst, updates, slice_range): ) print( f"{dtype:<12} {str(dst_shape):<25} {str(update_shape):<20} " - f"{mlx_time:<12.3f} {mlx_bw:<12.2f} {torch_time:<12.3f} {torch_bw:<12.2f}" + f"{mlx_time:<12.3f} {mlx_bw:<12.2f} {torch_time:<12.3f} " + f"{torch_bw:<12.2f}" ) diff --git a/benchmarks/python/swiglu_bench.py b/benchmarks/python/swiglu_bench.py index 805bc7c1d1..01904698b7 100644 --- a/benchmarks/python/swiglu_bench.py +++ b/benchmarks/python/swiglu_bench.py @@ -36,7 +36,7 @@ def scatter_unsort(x, inv_order, shape=None): return x -def time_gather_mm(name, D, M, E, I): +def time_gather_mm(name, D, M, E, num_indices): w1 = mx.random.normal((E, M, D), dtype=mx.bfloat16, scale=D**-0.5) w2 = mx.random.normal((E, M, D), dtype=mx.bfloat16, scale=D**-0.5) w3 = mx.random.normal((E, D, M), dtype=mx.bfloat16, scale=M**-0.5) @@ -64,8 +64,10 @@ def gather_mm(x, w1, w2, w3, indices, sort): for N in SEQ_LENS: x = mx.random.normal((N, 1, 1, D), dtype=mx.bfloat16) scores = mx.random.uniform(shape=(N, E)) - indices = mx.argpartition(scores, E - I, axis=-1)[:, -I:].astype(mx.uint32) - sorted_indices = mx.sort(indices.flatten()).reshape(N, I) + indices = mx.argpartition(scores, E - num_indices, axis=-1)[ + :, -num_indices: + ].astype(mx.uint32) + sorted_indices = mx.sort(indices.flatten()).reshape(N, num_indices) mx.eval(x, indices, sorted_indices) label = f"{name} N={N}" diff --git a/benchmarks/python/swiglu_qmm_bench.py b/benchmarks/python/swiglu_qmm_bench.py index 2e80ec2fa7..7ff8ab2159 100644 --- a/benchmarks/python/swiglu_qmm_bench.py +++ b/benchmarks/python/swiglu_qmm_bench.py @@ -36,7 +36,7 @@ def scatter_unsort(x, inv_order, shape=None): return x -def time_gather_qmm(name, D, M, E, I, mode): +def time_gather_qmm(name, D, M, E, num_indices, mode): w1 = mx.random.normal((E, M, D), dtype=mx.bfloat16, scale=D**-0.5) w2 = mx.random.normal((E, M, D), dtype=mx.bfloat16, scale=D**-0.5) w3 = mx.random.normal((E, D, M), dtype=mx.bfloat16, scale=M**-0.5) @@ -59,7 +59,9 @@ def gather_qmm(x, w1, w2, w3, indices, sort): for N in SEQ_LENS: x = mx.random.normal((N, 1, 1, D), dtype=mx.bfloat16) scores = mx.random.uniform(shape=(N, E)) - indices = mx.argpartition(scores, E - I, axis=-1)[:, -I:].astype(mx.uint32) + indices = mx.argpartition(scores, E - num_indices, axis=-1)[ + :, -num_indices: + ].astype(mx.uint32) mx.eval(x, indices) label = f"{name} {mode} N={N}" diff --git a/benchmarks/python/time_utils.py b/benchmarks/python/time_utils.py index 181f7d3fe2..e03b7fca5b 100644 --- a/benchmarks/python/time_utils.py +++ b/benchmarks/python/time_utils.py @@ -19,7 +19,7 @@ def time_fn(fn, *args, **kwargs): num_iters = 100 tic = time.perf_counter() for _ in range(num_iters): - x = mx.eval(fn(*args, **kwargs)) + _x = mx.eval(fn(*args, **kwargs)) toc = time.perf_counter() msec = 1e3 * (toc - tic) / num_iters diff --git a/cmake/extension.cmake b/cmake/extension.cmake index 2f244a14f2..1318eb6568 100644 --- a/cmake/extension.cmake +++ b/cmake/extension.cmake @@ -1,47 +1,119 @@ include(CMakeParseArguments) +function(_mlx_metal_supports_logging OUTPUT_VARIABLE) + execute_process( + COMMAND xcrun -sdk macosx metal --help + RESULT_VARIABLE _MLX_METAL_HELP_RESULT + OUTPUT_VARIABLE _MLX_METAL_HELP_OUTPUT + ERROR_VARIABLE _MLX_METAL_HELP_ERROR + TIMEOUT 10) + set(_MLX_METAL_HELP "${_MLX_METAL_HELP_OUTPUT}\n${_MLX_METAL_HELP_ERROR}") + string(FIND "${_MLX_METAL_HELP}" "-fmetal-enable-logging" + _MLX_METAL_LOGGING_OPTION_INDEX) + if(_MLX_METAL_HELP_RESULT STREQUAL "0" + AND NOT _MLX_METAL_LOGGING_OPTION_INDEX EQUAL -1) + set(${OUTPUT_VARIABLE} + TRUE + PARENT_SCOPE) + else() + set(${OUTPUT_VARIABLE} + FALSE + PARENT_SCOPE) + endif() +endfunction() + # clang format off # # ############################################################################## # Build metal library # -# Adds a custom target ${TARGET} to build ${OUTPUT_DIRECTORY}/{TITLE}.metallib -# from list ${SOURCES}, including list ${INCLUDE_DIRS}, depends on list ${DEPS} +# Adds a custom target ${TARGET} to build ${OUTPUT_DIRECTORY}/{TITLE}.metallib. +# Each source in ${SOURCES} is compiled to an AIR file before the AIR files are +# linked into the metallib, including list ${INCLUDE_DIRS}, depends on list +# ${DEPS}, and passes ${COMPILE_OPTIONS} to the Metal compiler. # # Args: TARGET: Custom target to be added for the metal library TITLE: Name of # the .metallib OUTPUT_DIRECTORY: Where to place ${TITLE}.metallib SOURCES: List # of source files INCLUDE_DIRS: List of include dirs DEPS: List of dependency -# files (like headers) DEBUG: Boolean, if true, enables debug compile options -# for this specific library. If not provided, uses global MLX_METAL_DEBUG. +# files (like headers) COMPILE_OPTIONS: Additional Metal compiler options +# DEPLOYMENT_TARGET: Optional macOS deployment target for this library DEBUG: +# Boolean, if true, enables debug compile options for this specific library. If +# not provided, uses global MLX_METAL_DEBUG. # # clang format on macro(mlx_build_metallib) # Parse args - set(oneValueArgs TARGET TITLE OUTPUT_DIRECTORY DEBUG) - set(multiValueArgs SOURCES INCLUDE_DIRS DEPS) + set(oneValueArgs TARGET TITLE OUTPUT_DIRECTORY DEBUG DEPLOYMENT_TARGET) + set(multiValueArgs SOURCES INCLUDE_DIRS DEPS COMPILE_OPTIONS) cmake_parse_arguments(MTLLIB "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) # Set output set(MTLLIB_BUILD_TARGET "${MTLLIB_OUTPUT_DIRECTORY}/${MTLLIB_TITLE}.metallib") # Collect compile options - set(MTLLIB_COMPILE_OPTIONS -Wall -Wextra -fno-fast-math -Wno-c++17-extensions - -Wmetal-addr-spaces) - if(MLX_METAL_DEBUG OR MTLLIB_DEBUG) - set(MTLLIB_COMPILE_OPTIONS ${MTLLIB_COMPILE_OPTIONS} -gline-tables-only - -frecord-sources) + set(_MTLLIB_COMPILE_OPTIONS + -Wall -Wextra -fno-fast-math -Wno-c++17-extensions -Wno-c++20-extensions + -Wmetal-addr-spaces) + if(MLX_METAL_DEBUG + OR MTLLIB_DEBUG + OR CMAKE_BUILD_TYPE STREQUAL "Debug") + set(_MTLLIB_COMPILE_OPTIONS ${_MTLLIB_COMPILE_OPTIONS} -gline-tables-only + -frecord-sources) + endif() + if(CMAKE_BUILD_TYPE STREQUAL "Debug") + _mlx_metal_supports_logging(_MTLLIB_SUPPORTS_LOGGING) + if(_MTLLIB_SUPPORTS_LOGGING) + list(APPEND _MTLLIB_COMPILE_OPTIONS -fmetal-enable-logging) + endif() endif() - # Prepare metallib build command + set(_MTLLIB_LINK_OPTIONS) + if(MTLLIB_DEPLOYMENT_TARGET) + set(_MTLLIB_DEPLOYMENT_OPTION + "-mmacosx-version-min=${MTLLIB_DEPLOYMENT_TARGET}") + list(APPEND _MTLLIB_COMPILE_OPTIONS ${_MTLLIB_DEPLOYMENT_OPTION}) + list(APPEND _MTLLIB_LINK_OPTIONS ${_MTLLIB_DEPLOYMENT_OPTION}) + elseif(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "") + set(_MTLLIB_DEPLOYMENT_OPTION + "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") + list(APPEND _MTLLIB_COMPILE_OPTIONS ${_MTLLIB_DEPLOYMENT_OPTION}) + list(APPEND _MTLLIB_LINK_OPTIONS ${_MTLLIB_DEPLOYMENT_OPTION}) + endif() + + # Compile each Metal source separately for incremental builds + set(_MTLLIB_AIR_TARGETS) + set(_MTLLIB_INCLUDE_OPTIONS ${MTLLIB_INCLUDE_DIRS}) + list(TRANSFORM _MTLLIB_INCLUDE_OPTIONS PREPEND "-I") + set(_MTLLIB_SOURCE_INDEX 0) + foreach(_MTLLIB_SOURCE IN LISTS MTLLIB_SOURCES) + get_filename_component(_MTLLIB_SOURCE_STEM "${_MTLLIB_SOURCE}" NAME_WE) + set(_MTLLIB_AIR_NAME + "${MTLLIB_TARGET}_${_MTLLIB_SOURCE_INDEX}_${_MTLLIB_SOURCE_STEM}.air") + set(_MTLLIB_AIR_TARGET "${CMAKE_CURRENT_BINARY_DIR}/${_MTLLIB_AIR_NAME}") + set(_MTLLIB_DEPFILE "${_MTLLIB_AIR_TARGET}.d") + add_custom_command( + OUTPUT ${_MTLLIB_AIR_TARGET} + COMMAND + xcrun -sdk macosx metal ${_MTLLIB_INCLUDE_OPTIONS} + ${_MTLLIB_COMPILE_OPTIONS} ${MTLLIB_COMPILE_OPTIONS} -MMD -MF + ${_MTLLIB_DEPFILE} -MT ${_MTLLIB_AIR_TARGET} -c ${_MTLLIB_SOURCE} -o + ${_MTLLIB_AIR_TARGET} + DEPENDS ${MTLLIB_DEPS} ${_MTLLIB_SOURCE} + DEPFILE ${_MTLLIB_DEPFILE} + COMMAND_EXPAND_LISTS + COMMENT "Building ${_MTLLIB_AIR_NAME}" + VERBATIM) + list(APPEND _MTLLIB_AIR_TARGETS ${_MTLLIB_AIR_TARGET}) + math(EXPR _MTLLIB_SOURCE_INDEX "${_MTLLIB_SOURCE_INDEX} + 1") + endforeach() + + # Link the AIR files into a metallib add_custom_command( OUTPUT ${MTLLIB_BUILD_TARGET} - COMMAND - xcrun -sdk macosx metal - "$" - ${MTLLIB_COMPILE_OPTIONS} ${MTLLIB_SOURCES} -o ${MTLLIB_BUILD_TARGET} - DEPENDS ${MTLLIB_DEPS} ${MTLLIB_SOURCES} - COMMAND_EXPAND_LISTS + COMMAND xcrun -sdk macosx metal ${_MTLLIB_LINK_OPTIONS} + ${_MTLLIB_AIR_TARGETS} -o ${MTLLIB_BUILD_TARGET} + DEPENDS ${_MTLLIB_AIR_TARGETS} COMMENT "Building ${MTLLIB_TITLE}.metallib" VERBATIM) diff --git a/docs/src/conf.py b/docs/src/conf.py index b95a3fe74c..62c7d7e0b8 100644 --- a/docs/src/conf.py +++ b/docs/src/conf.py @@ -2,8 +2,6 @@ # -*- coding: utf-8 -*- -import os -import subprocess import mlx.core as mx diff --git a/docs/src/dev/extensions.rst b/docs/src/dev/extensions.rst index 89c8991e56..bcfcc78db8 100644 --- a/docs/src/dev/extensions.rst +++ b/docs/src/dev/extensions.rst @@ -549,24 +549,20 @@ Building and Binding Let's look at the overall directory structure first. -| extensions +| cmake_extension | ├── axpby | │ ├── axpby.cpp | │ ├── axpby.h | │ └── axpby.metal -| ├── mlx_sample_extensions -| │ └── __init__.py | ├── bindings.cpp | ├── CMakeLists.txt | └── setup.py -* ``extensions/axpby/`` defines the C++ extension library -* ``extensions/mlx_sample_extensions`` sets out the structure for the - associated Python package -* ``extensions/bindings.cpp`` provides Python bindings for our operation -* ``extensions/CMakeLists.txt`` holds CMake rules to build the library and +* ``cmake_extension/axpby/`` defines the C++ extension library +* ``cmake_extension/bindings.cpp`` provides Python bindings for our operation +* ``cmake_extension/CMakeLists.txt`` holds CMake rules to build the library and Python bindings -* ``extensions/setup.py`` holds the ``setuptools`` rules to build and install +* ``cmake_extension/setup.py`` holds the ``setuptools`` rules to build and install the Python package Binding to Python @@ -578,7 +574,7 @@ already provided, adding our :meth:`axpby` is simple. .. code-block:: C++ - NB_MODULE(_ext, m) { + NB_MODULE(mlx_sample_extensions, m) { m.doc() = "Sample extension for MLX"; m.def( @@ -611,13 +607,6 @@ already provided, adding our :meth:`axpby` is simple. Most of the complexity in the above example comes from additional bells and whistles such as the literal names and doc-strings. -.. warning:: - - :mod:`mlx.core` must be imported before importing - :mod:`mlx_sample_extensions` as defined by the nanobind module above to - ensure that the casters for :mod:`mlx.core` components like - :class:`mlx.core.array` are available. - .. _Building with CMake: Building with CMake @@ -678,20 +667,19 @@ Finally, we build the nanobind_ bindings .. code-block:: cmake nanobind_add_module( - _ext - NB_STATIC STABLE_ABI LTO NOMINSIZE + mlx_sample_extensions + NB_STATIC FREE_THREADED LTO NOMINSIZE NB_DOMAIN mlx ${CMAKE_CURRENT_LIST_DIR}/bindings.cpp ) - target_link_libraries(_ext PRIVATE mlx_ext) - - if(BUILD_SHARED_LIBS) - target_link_options(_ext PRIVATE -Wl,-rpath,@loader_path) - endif() + target_link_libraries(mlx_sample_extensions PRIVATE mlx_ext) Building with ``setuptools`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Building with a ``CMakeLists.txt`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Once we have set out the CMake build rules as described above, we can use the build utilities defined in :mod:`mlx.extension`: @@ -705,42 +693,167 @@ build utilities defined in :mod:`mlx.extension`: name="mlx_sample_extensions", version="0.0.0", description="Sample C++ and Metal extensions for MLX primitives.", - ext_modules=[extension.CMakeExtension("mlx_sample_extensions._ext")], + ext_modules=[extension.CMakeExtension("mlx_sample_extensions")], cmdclass={"build_ext": extension.CMakeBuild}, - packages=["mlx_sample_extensions"], - package_data={"mlx_sample_extensions": ["*.so", "*.dylib", "*.metallib"]}, + packages=[], extras_require={"dev":[]}, zip_safe=False, - python_requires=">=3.8", + python_requires=">=3.10", ) -.. note:: - We treat ``extensions/mlx_sample_extensions`` as the package directory - even though it only contains a ``__init__.py`` to ensure the following: +On macOS and Linux, ``CMakeBuild`` configures a relocatable runtime search path +for all targets. It locates colocated libraries through ``@loader_path`` on +macOS or ``$ORIGIN`` on Linux, and locates the MLX library under ``mlx/lib`` in +the same ``site-packages`` directory. The extension module can therefore load +without importing ``mlx.core`` first. Values provided through ``CMAKE_ARGS`` +can override this default. - * :mod:`mlx.core` must be imported before importing :mod:`_ext` - * The C++ extension library and the metal library are co-located with the python - bindings and copied together if the package is installed +The extension name is the Python import name. This example builds the top-level +module ``mlx_sample_extensions`` without a Python wrapper package. A suffix such +as ``._ext`` is optional: use a dotted name such as ``my_package._ext`` only when +placing the extension inside a Python package. For ``CMakeExtension``, the +nanobind module name must match the final component of the extension name. To build the package, first install the build dependencies with ``pip install -r requirements.txt``. You can then build inplace for development using -``python setup.py build_ext -j8 --inplace`` (in ``extensions/``) +``python setup.py build_ext -j8 --inplace`` (in ``cmake_extension/``) This results in the directory structure: -| extensions -| ├── mlx_sample_extensions -| │ ├── __init__.py -| │ ├── libmlx_ext.dylib # C++ extension library -| │ ├── mlx_ext.metallib # Metal library -| │ └── _ext.cpython-3x-darwin.so # Python Binding +| cmake_extension +| ├── libmlx_ext.dylib # C++ extension library +| ├── mlx_ext.metallib # Metal library +| ├── mlx_sample_extensions.cpython-3x-darwin.so # Python binding | ... When you try to install using the command ``python -m pip install .`` (in -``extensions/``), the package will be installed with the same structure as -``extensions/mlx_sample_extensions`` and the C++ and Metal library will be -copied along with the Python binding since they are specified as -``package_data``. +``cmake_extension/``), the Python module and its C++ and Metal libraries are +installed together directly under ``site-packages``. + +Building without a ``CMakeLists.txt`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For a source-list based build, use ``mlx.extension.MetalExtension`` with +``mlx.extension.BuildExtension``. The helper builds the C++/nanobind module and +a colocated Metal library without requiring a ``CMakeLists.txt`` in the +extension project. + +.. code-block:: python + + from importlib.metadata import version as package_version + + from mlx import extension + from setuptools import setup + + setup( + name="mlx_sample_metal_extension", + ext_modules=[ + extension.MetalExtension( + "mlx_sample_metal_extension", + sources=[ + "activation.cpp", + "silu_and_mul.metal", + ], + extra_compile_args={ + "cxx": ["-O3"], + "metal": ["-O3"], + }, + ) + ], + cmdclass={"build_ext": extension.BuildExtension}, + install_requires=[f"mlx=={package_version('mlx')}"], + packages=[], + ) + +As with ``CMakeExtension``, a ``._ext`` suffix is not required. The final component +of the extension name is also the default Metal library name. This example +builds the top-level module ``mlx_sample_metal_extension``, with +``mlx_sample_metal_extension.metallib`` and +``mlx_sample_metal_extension.pyi`` beside it. These files are included in the +wheel and installed together under ``site-packages``. + +A list passed as ``extra_compile_args`` applies to C++; a dictionary can provide +separate ``cxx`` and ``metal`` options. To disable nanobind stub generation, +configure the command class with +``BuildExtension.with_options(generate_stubs=False)``. + +Pin the ``mlx`` install requirement to the version used for the build because +MLX does not provide a stable C++ ABI across releases. Reading the version from +the installed package metadata avoids importing ``mlx.core`` during setup. + +The generated extension uses a relocatable runtime search path to locate +``libmlx.dylib`` under ``mlx/lib`` in the same ``site-packages`` directory. This +avoids embedding the build machine's absolute MLX library path and lets the +extension module load without importing ``mlx.core`` first. + +The build defines ``MLX_EXTENSION_NAME`` as the final component of the +extension name and ``MLX_METAL_LIBRARY_NAME`` as its string form. Use them so +the binding does not hard-code either the module or Metal library name: + +.. code-block:: C++ + + auto library = + device.get_library(MLX_METAL_LIBRARY_NAME, current_binary_dir()); + + NB_MODULE(MLX_EXTENSION_NAME, m) { + // bindings + } + +To choose Metal library names or build multiple libraries, pass +``extension.MetalLibrary`` objects through ``metal_libraries``: + +.. code-block:: python + + extension.MetalExtension( + "mlx_sample_metal_extension", + sources=["activation.cpp"], + metal_libraries=[ + extension.MetalLibrary( + "activation", + sources=["silu_and_mul.metal"], + extra_compile_args=["-O3"], + deployment_target="14.0", + ), + extension.MetalLibrary( + "something_else", + sources=["something_else.metal"], + ), + ], + ) + +When ``metal_libraries`` is set, put all ``.metal`` sources in those objects +and keep only C++ sources in ``MetalExtension.sources``. Each library needs a +unique name, given without a path or ``.metallib`` suffix. This example builds +``activation.metallib`` and ``something_else.metallib`` beside the Python +extension. + +Each library's ``extra_compile_args`` are added after the extension's shared +``extra_compile_args["metal"]`` options. ``MLX_METAL_LIBRARY_NAME`` still +contains the final component of the Python extension name. Load libraries +explicitly by their configured names: + +.. code-block:: C++ + + auto library = device.get_library("activation", current_binary_dir()); + +Debug builds include Metal line tables and recorded sources. Metal logging is +enabled when the current ``xcrun metal`` compiler advertises support. The +effective Python +``MACOSX_DEPLOYMENT_TARGET`` is forwarded to CMake and applied to both AIR +compilation and metallib linking. By default, the target recorded in the +installed ``libmlx.dylib`` is used. Set ``MACOSX_DEPLOYMENT_TARGET`` or pass +``CMAKE_OSX_DEPLOYMENT_TARGET`` through ``CMAKE_ARGS`` to override it. This can +select a lower target for cross-building, provided the extension is used with +an MLX build for that target at runtime. Explicit targets below macOS 14 are +rejected. + +``BuildExtension`` uses CMake's platform default generator. To use Ninja, +include ``ninja`` in the build requirements and configure the command class +with ``BuildExtension.with_options(use_ninja=True)``. It falls back to the platform +default generator if Ninja is not available. + +The complete standalone example is available in +``examples/metal_extension/``. Usage ----- @@ -827,7 +940,7 @@ Scripts .. admonition:: Download the code - The full example code is available in `mlx `_. + The full example code is available in `mlx `_. .. _Accelerate: https://developer.apple.com/documentation/accelerate/blas?language=objc .. _Metal: https://developer.apple.com/documentation/metal?language=objc diff --git a/docs/src/dev/release.rst b/docs/src/dev/release.rst new file mode 100644 index 0000000000..588d0e17ba --- /dev/null +++ b/docs/src/dev/release.rst @@ -0,0 +1,76 @@ +Publishing a New Release +======================== + +Steps +----- + +1. Check the current version on the latest ``main`` branch in ``mlx/version.h``. +2. Push a new tag for current version to the GitHub repository, which would + automatically trigger release workflow. +3. Wait for the release workflow to **succeed**. +4. Create a new GitHub Release for the latest tag from the `Tags + `__ page. +5. Create a pull request that increases the version in ``mlx/version.h``. + +Troubleshooting +--------------- + +Build or test failure +^^^^^^^^^^^^^^^^^^^^^ + +If the release workflow fails at the build or test step: + +1. Remove the tag from GitHub. +2. Fix the build or test failure. +3. Do the steps again. + +See `Common causes of release build failures`_ for possible causes. + +All publish jobs fail +^^^^^^^^^^^^^^^^^^^^^ + +If all the publish jobs fail, remove the tag from GitHub first. A possible cause +is that the credentials are not valid anymore, you must get it fixed before +retrying. + +Some publish jobs fail +^^^^^^^^^^^^^^^^^^^^^^ + +If only some publish jobs fail, find the cause: + +- If the cause is a network issue, restart **only** the failed publish jobs. +- If restarting cannot fix the cause (for example, the package is larger than + the PyPI size limit), create a fix and merge it to the main branch. Then + `trigger the release workflow manually`_. + +Trigger the release workflow manually +------------------------------------- + +Use this method only for troubleshooting. It is **not** the recommended way to +publish a release. + +1. Open https://github.com/ml-explore/mlx/actions/workflows/release.yml. +2. For a dry run, which only tests that the release build works, keep the + "Publish to PyPI" option unchecked. Then click "Run workflow". +3. To publish a release, select "Publish to PyPI". Then click "Run workflow". + Note that it is only possible to publish from main branch. + +Common causes of release build failures +--------------------------------------- + +Release build failures are rare, because pull requests run the full tests. +But the usual CI makes only debug builds, so a release build can fail because: + +1. Some code is inside a debug macro guard and behaves differently in release + builds. +2. A bug, for example a race condition, shows only when the code runs faster in + release builds. +3. In the CUDA build, the debug build targets only the current architecture, + while the release build targets all supported architectures, on which CUDA + code can fail to compile or run. So when changing a CUDA kernel that makes + use of hardware specific features, also start a dry run of the release build + to avoid such problems. +4. The release build makes two Python packages: a frontend package with only the + Python bindings, and a backend package with the headers and the backend- and + platform-specific binaries. A change to the CMake files or ``setup.py`` can + break them. See ``.github/actions/build-wheel/action.yml`` for details. diff --git a/docs/src/index.rst b/docs/src/index.rst index 8b3028be70..4eabd4767a 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -98,3 +98,4 @@ are the CPU and GPU. dev/metal_logging dev/custom_metal_kernels dev/mlx_in_cpp + dev/release diff --git a/docs/src/python/fft.rst b/docs/src/python/fft.rst index 78bfe7f8fc..0df0b665df 100644 --- a/docs/src/python/fft.rst +++ b/docs/src/python/fft.rst @@ -20,6 +20,8 @@ FFT irfft2 rfftn irfftn + stft + istft fftfreq rfftfreq fftshift diff --git a/docs/src/python/memory_management.rst b/docs/src/python/memory_management.rst index f708efbfd2..b0564bd0f2 100644 --- a/docs/src/python/memory_management.rst +++ b/docs/src/python/memory_management.rst @@ -7,6 +7,7 @@ Memory Management :toctree: _autosummary get_active_memory + get_array_buffer_size get_peak_memory reset_peak_memory get_cache_memory diff --git a/docs/src/python/ops.rst b/docs/src/python/ops.rst index f55ba1b4d4..52790680ff 100644 --- a/docs/src/python/ops.rst +++ b/docs/src/python/ops.rst @@ -134,6 +134,7 @@ Operations meshgrid min minimum + minmax moveaxis multiply nan_to_num @@ -203,6 +204,7 @@ Operations triu trunc unflatten + unique unstack vecdot var diff --git a/docs/src/usage/distributed.rst b/docs/src/usage/distributed.rst index 431aef7102..861525dcbf 100644 --- a/docs/src/usage/distributed.rst +++ b/docs/src/usage/distributed.rst @@ -292,6 +292,29 @@ The following JSON defines the valid 4-node mesh from the image above. } ] +Two Macs can also be connected with more than one thunderbolt cable. In that +case, write a list of rdma devices for the peer instead of one device. The +device at position ``k`` in the list must be connected to the device at +position ``k`` in the list of the peer. JACCL sends large messages over all +the cables at the same time. If some pairs have fewer cables than others, JACCL +uses the smallest number of cables for all pairs. The following JSON defines +two Macs connected with two cables. + +.. code-block:: json + + [ + { + "ssh": "m3-ultra-1", + "ips": ["123.123.123.1"], + "rdma": [null, ["rdma_en2", "rdma_en3"]] + }, + { + "ssh": "m3-ultra-2", + "ips": [], + "rdma": [["rdma_en2", "rdma_en3"], null] + } + ] + Even though TCP/IP is not used when communicating with Thunderbolt RDMA, disabling the thunderbolt bridge is still required as well as setting up isolated local networks for each thunderbolt connection. diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index 3584f4c22e..b43c053d52 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -87,11 +87,27 @@ handled by the CUDA runtime. Metal ----- +.. envvar:: MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS + + Re-request residency for existing wired allocations at this interval in + milliseconds. This works around macOS releasing residency while the GPU is + idle. The default is ``0`` (disabled); nonpositive values disable renewal. + For example, ``1000`` renews once per second. This does not change the wired + limit set by :func:`mlx.core.set_wired_limit` or submit GPU work. Renewal + continues while the Metal device exists and can keep memory wired during + long idle periods. Requires a Metal 3 GPU on macOS 15 or iOS 18 or later. + .. envvar:: MLX_METAL_FAST_SYNCH Enable the faster Metal CPU/GPU synchronization path. The default is ``0``. This requires Metal 3.2 or later (macOS 15 or later, or iOS 18 or later). +.. envvar:: MLX_CONV_WINOGRAD + + Allow the Winograd algorithm for 3x3 ``conv2d``. The default is ``1``. Set + it to ``0`` to use the GEMM convolution for all inputs. See + :doc:`precision`. + Advanced tuning --------------- @@ -177,8 +193,18 @@ The MLX-prefixed variables in this section are advanced CUDA backend controls. .. envvar:: MLX_ENABLE_CACHE_THRASHING_CHECK - Detect repeated CUDA cache misses and raise an error suggesting a larger - cache capacity. The default is ``1``. + Detect consecutive CUDA cache misses (more than twice the capacity with no + hit in between) and raise an error suggesting a larger cache capacity. The + default is ``1``. MLX also uses ``CUDA_HOME`` or ``CUDA_PATH`` to locate CUDA headers for runtime kernel compilation when they cannot be found in the Python environment. + +CPU +--- + +.. envvar:: MLX_CPU_CACHE_DIR + + Override the directory used to cache runtime-compiled CPU kernels. An unset + or empty value uses ``mlx//cpu`` under the system temporary + directory, which is the default. diff --git a/docs/src/usage/export.rst b/docs/src/usage/export.rst index 9900ed6d24..b06ca96720 100644 --- a/docs/src/usage/export.rst +++ b/docs/src/usage/export.rst @@ -207,7 +207,7 @@ The argument to the callback (``args``) is a dictionary which includes a * ``"keyword_inputs"``: The keyword specified inputs to the exported function * ``"outputs"``: The ordered outputs of the exported function * ``"constants"``: Any graph constants -* ``"primitives"``: Inner graph nodes representating the operations +* ``"primitive"``: An inner graph node representing an operation Each type has additional fields in the ``args`` dictionary. diff --git a/docs/src/usage/precision.rst b/docs/src/usage/precision.rst index 440a1f705d..31c3f2efea 100644 --- a/docs/src/usage/precision.rst +++ b/docs/src/usage/precision.rst @@ -19,3 +19,15 @@ To keep these operations in full ``float32``, set Which operations take the reduced-precision path, and how large the difference is, depends on the backend and the hardware. + +On Metal, ``conv2d`` can use the Winograd algorithm for 3x3 convolutions +with stride 1. Winograd is faster for large inputs, but its rounding error +in ``float32`` can be approximately 10 times larger. MLX selects Winograd +from the total input size, which includes the batch size. Thus, the same +image can give different results in a batch of 3 and in a batch of 1. + +To disable Winograd, set :envvar:`MLX_CONV_WINOGRAD` to ``0``: + +.. code-block:: shell + + MLX_CONV_WINOGRAD=0 python my_script.py diff --git a/examples/extensions/CMakeLists.txt b/examples/cmake_extension/CMakeLists.txt similarity index 77% rename from examples/extensions/CMakeLists.txt rename to examples/cmake_extension/CMakeLists.txt index eedc3a7dab..22ce3c3006 100644 --- a/examples/extensions/CMakeLists.txt +++ b/examples/cmake_extension/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.27) -project(_ext LANGUAGES CXX) +project(mlx_sample_extensions LANGUAGES CXX) # ----------------------------- Setup ----------------------------- set(CMAKE_CXX_STANDARD 20) @@ -10,15 +10,23 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON) option(BUILD_SHARED_LIBS "Build extensions as a shared library" ON) # ----------------------------- Dependencies ----------------------------- + +include(FetchContent) + +# Avoid warning about DOWNLOAD_EXTRACT_TIMESTAMP in CMake 3.24: +cmake_policy(SET CMP0135 NEW) + find_package( - Python 3.8 + Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED) -execute_process( - COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir - OUTPUT_STRIP_TRAILING_WHITESPACE - OUTPUT_VARIABLE nanobind_ROOT) -find_package(nanobind CONFIG REQUIRED) +FetchContent_Declare( + nanobind + GIT_REPOSITORY https://github.com/wjakob/nanobind.git + GIT_TAG v3.1.0 + GIT_SHALLOW TRUE + EXCLUDE_FROM_ALL) +FetchContent_MakeAvailable(nanobind) execute_process( COMMAND "${Python_EXECUTABLE}" -m mlx --cmake-dir @@ -63,16 +71,12 @@ endif() # ----------------------------- Python Bindings ----------------------------- nanobind_add_module( - _ext + mlx_sample_extensions NB_STATIC - STABLE_ABI + FREE_THREADED LTO NOMINSIZE NB_DOMAIN mlx ${CMAKE_CURRENT_LIST_DIR}/bindings.cpp) -target_link_libraries(_ext PRIVATE mlx_ext) - -if(BUILD_SHARED_LIBS) - target_link_options(_ext PRIVATE -Wl,-rpath,@loader_path) -endif() +target_link_libraries(mlx_sample_extensions PRIVATE mlx_ext) diff --git a/examples/extensions/README.md b/examples/cmake_extension/README.md similarity index 64% rename from examples/extensions/README.md rename to examples/cmake_extension/README.md index 610de99f42..0599fc1397 100644 --- a/examples/extensions/README.md +++ b/examples/cmake_extension/README.md @@ -1,4 +1,7 @@ +The example builds `mlx_sample_extensions` as a top-level Python extension +module. No `._ext` suffix or Python wrapper package is required. + ## Build ``` diff --git a/examples/extensions/axpby/axpby.cpp b/examples/cmake_extension/axpby/axpby.cpp similarity index 100% rename from examples/extensions/axpby/axpby.cpp rename to examples/cmake_extension/axpby/axpby.cpp diff --git a/examples/extensions/axpby/axpby.h b/examples/cmake_extension/axpby/axpby.h similarity index 100% rename from examples/extensions/axpby/axpby.h rename to examples/cmake_extension/axpby/axpby.h diff --git a/examples/extensions/axpby/axpby.metal b/examples/cmake_extension/axpby/axpby.metal similarity index 100% rename from examples/extensions/axpby/axpby.metal rename to examples/cmake_extension/axpby/axpby.metal diff --git a/examples/extensions/bindings.cpp b/examples/cmake_extension/bindings.cpp similarity index 95% rename from examples/extensions/bindings.cpp rename to examples/cmake_extension/bindings.cpp index 91892fa903..a094d1797f 100644 --- a/examples/extensions/bindings.cpp +++ b/examples/cmake_extension/bindings.cpp @@ -8,7 +8,7 @@ namespace nb = nanobind; using namespace nb::literals; -NB_MODULE(_ext, m) { +NB_MODULE(mlx_sample_extensions, m) { m.doc() = "Sample extension for MLX"; m.def( diff --git a/examples/extensions/pyproject.toml b/examples/cmake_extension/pyproject.toml similarity index 73% rename from examples/extensions/pyproject.toml rename to examples/cmake_extension/pyproject.toml index 560a58bc28..2386c9ec46 100644 --- a/examples/extensions/pyproject.toml +++ b/examples/cmake_extension/pyproject.toml @@ -2,7 +2,6 @@ requires = [ "setuptools>=42", "cmake>=3.25", - "mlx>=0.18.0", - "nanobind==2.15.0", + "mlx>=0.31.2", ] build-backend = "setuptools.build_meta" diff --git a/examples/extensions/requirements.txt b/examples/cmake_extension/requirements.txt similarity index 69% rename from examples/extensions/requirements.txt rename to examples/cmake_extension/requirements.txt index 917d125eea..41dce3ca7c 100644 --- a/examples/extensions/requirements.txt +++ b/examples/cmake_extension/requirements.txt @@ -1,4 +1,3 @@ setuptools>=42 cmake>=3.25 mlx>=0.31.2 -nanobind==2.15.0 diff --git a/examples/extensions/setup.py b/examples/cmake_extension/setup.py similarity index 76% rename from examples/extensions/setup.py rename to examples/cmake_extension/setup.py index be990a02b6..f8fe3ada76 100644 --- a/examples/extensions/setup.py +++ b/examples/cmake_extension/setup.py @@ -9,10 +9,9 @@ name="mlx_sample_extensions", version="0.0.0", description="Sample C++ and Metal extensions for MLX primitives.", - ext_modules=[extension.CMakeExtension("mlx_sample_extensions._ext")], + ext_modules=[extension.CMakeExtension("mlx_sample_extensions")], cmdclass={"build_ext": extension.CMakeBuild}, - packages=["mlx_sample_extensions"], - package_data={"mlx_sample_extensions": ["*.so", "*.dylib", "*.metallib"]}, + packages=[], zip_safe=False, python_requires=">=3.10", ) diff --git a/examples/extensions/test.py b/examples/cmake_extension/test.py similarity index 100% rename from examples/extensions/test.py rename to examples/cmake_extension/test.py diff --git a/examples/export/eval_mlp.py b/examples/export/eval_mlp.py index 133ab69179..07981523b9 100644 --- a/examples/export/eval_mlp.py +++ b/examples/export/eval_mlp.py @@ -2,7 +2,6 @@ import mlx.core as mx import mlx.nn as nn -import mlx.utils class MLP(nn.Module): @@ -19,13 +18,12 @@ def __init__( ] def __call__(self, x): - for l in self.layers[:-1]: - x = nn.relu(l(x)) + for layer in self.layers[:-1]: + x = nn.relu(layer(x)) return self.layers[-1](x) if __name__ == "__main__": - batch_size = 8 input_dim = 32 output_dim = 10 diff --git a/examples/export/train_mlp.py b/examples/export/train_mlp.py index 0e19650a14..c188a94b4b 100644 --- a/examples/export/train_mlp.py +++ b/examples/export/train_mlp.py @@ -20,13 +20,12 @@ def __init__( ] def __call__(self, x): - for l in self.layers[:-1]: - x = nn.relu(l(x)) + for layer in self.layers[:-1]: + x = nn.relu(layer(x)) return self.layers[-1](x) if __name__ == "__main__": - batch_size = 8 input_dim = 32 output_dim = 10 diff --git a/examples/extensions/mlx_sample_extensions/__init__.py b/examples/extensions/mlx_sample_extensions/__init__.py deleted file mode 100644 index b56a54fd2c..0000000000 --- a/examples/extensions/mlx_sample_extensions/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright © 2023 Apple Inc. - -import mlx.core as mx - -from ._ext import axpby diff --git a/examples/metal_extension/README.md b/examples/metal_extension/README.md new file mode 100644 index 0000000000..755cf4c3e2 --- /dev/null +++ b/examples/metal_extension/README.md @@ -0,0 +1,28 @@ +# Activation Metal extension + +A minimal MLX Metal extension exposing `silu_and_mul`. It uses +`mlx.extension.MetalExtension` to build the top-level module +`mlx_sample_metal_extension`, without a `._ext` suffix or Python wrapper package. + +The kernel is adapted from Hugging Face +[`activation_metal`](https://github.com/huggingface/kernels-community/tree/47a3168d0808921eef2f7daca794a4fccae13078/activation/activation_metal) +under Apache-2.0. + +## Build + +```bash +pip install -r requirements.txt +python setup.py build_ext -j8 --inplace +``` + +The build uses CMake's default generator and generates +`mlx_sample_metal_extension.pyi` by default. +To enable Ninja, install `ninja` and use +`BuildExtension.with_options(use_ninja=True)`. To disable stub generation, use +`BuildExtension.with_options(generate_stubs=False)`. + +## Test + +```bash +python test.py +``` diff --git a/examples/metal_extension/activation.cpp b/examples/metal_extension/activation.cpp new file mode 100644 index 0000000000..7f99b9df5a --- /dev/null +++ b/examples/metal_extension/activation.cpp @@ -0,0 +1,139 @@ +// Copyright © 2026 Apple Inc. + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mlx/backend/metal/device.h" +#include "mlx/ops.h" +#include "mlx/primitives.h" + +namespace mx = mlx::core; +namespace nb = nanobind; +using namespace nb::literals; + +namespace { + +std::string current_binary_dir() { + static std::string binary_dir = []() { + Dl_info info; + if (!dladdr(reinterpret_cast(¤t_binary_dir), &info)) { + throw std::runtime_error("Unable to get current binary directory."); + } + return std::filesystem::path(info.dli_fname).parent_path().string(); + }(); + return binary_dir; +} + +class SiluAndMul : public mx::UnaryPrimitive { + public: + explicit SiluAndMul(mx::Stream stream) : mx::UnaryPrimitive(stream) {} + + void eval_cpu(const std::vector&, mx::array&) override { + throw std::runtime_error("SiluAndMul is only implemented for the GPU."); + } + + void eval_gpu(const std::vector& inputs, mx::array& out) override { + const auto& input = inputs[0]; + out.set_data(mx::allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } + + const uint32_t last_dim = input.shape(-1); + const uint32_t d = last_dim / 2; + const uint32_t num_tokens = input.size() / last_dim; + const uint32_t num_chunks = (d + 7) / 8; + + auto& device = mx::metal::device(stream().device); + auto library = + device.get_library(MLX_METAL_LIBRARY_NAME, current_binary_dir()); + auto kernel = device.get_kernel("silu_and_mul_f16", library); + + auto& encoder = mx::metal::get_command_encoder(stream()); + encoder.set_compute_pipeline_state(kernel); + encoder.set_output_array(out, 0); + encoder.set_input_array(input, 1); + encoder.set_bytes(d, 2); + + const size_t group_width = std::min( + static_cast(num_chunks), + static_cast(kernel->maxTotalThreadsPerThreadgroup())); + encoder.dispatch_threads( + MTL::Size(num_chunks, num_tokens, 1), MTL::Size(group_width, 1, 1)); + } + + const char* name() const override { + return "SiluAndMul"; + } + + bool is_equivalent(const mx::Primitive&) const override { + return true; + } +}; + +mx::array silu_and_mul(const mx::array& input, mx::StreamOrDevice s = {}) { + if (input.ndim() == 0) { + throw std::invalid_argument( + "silu_and_mul input must have at least one dimension."); + } + if (input.shape(-1) % 2 != 0) { + throw std::invalid_argument( + "silu_and_mul requires an even-sized last dimension."); + } + if (input.dtype() != mx::float16) { + throw std::invalid_argument("silu_and_mul only supports float16."); + } + + auto stream = mx::to_stream(s); + auto contiguous_input = mx::contiguous(input, false, stream); + auto output_shape = input.shape(); + output_shape.back() /= 2; + return mx::array( + output_shape, + input.dtype(), + std::make_shared(stream), + {contiguous_input}); +} + +} // namespace + +NB_MODULE(MLX_EXTENSION_NAME, m) { + m.doc() = + "Fused float16 SiLU and multiplication implemented with MLX and Metal."; + m.def( + "silu_and_mul", + &silu_and_mul, + "input"_a, + nb::kw_only(), + "stream"_a = nb::none(), + nb::sig( + "def silu_and_mul(input: mlx.core.array, *, stream: " + "mlx.core.Stream | mlx.core.ThreadLocalStream | mlx.core.Device | " + "None = None) -> mlx.core.array"), + R"pbdoc( + Apply a fused SiLU activation and multiplication. + + Splits the last dimension into equal halves ``x`` and ``y``, then + computes ``silu(x) * y``. The input must be a float16 array with an + even-sized last dimension. + + Args: + input (mlx.core.array): Input array. + stream (Stream or Device, optional): Stream or device on which to + schedule the operation. Defaults to ``None``. + + Returns: + mlx.core.array: An array whose last dimension is half that of the + input. + )pbdoc"); +} diff --git a/examples/metal_extension/pyproject.toml b/examples/metal_extension/pyproject.toml new file mode 100644 index 0000000000..4a2250f870 --- /dev/null +++ b/examples/metal_extension/pyproject.toml @@ -0,0 +1,19 @@ +[build-system] +requires = [ + "setuptools>=80", + "cmake>=3.25", + "mlx>=0.32.0", + "nanobind==3.1.0", +] +build-backend = "setuptools.build_meta" + +[project] +name = "mlx_sample_metal_extension" +version = "0.0.0" +description = "Activation MetalExtension example for MLX." +requires-python = ">=3.10" +dynamic = ["dependencies"] + +[tool.setuptools] +packages = [] +zip-safe = false diff --git a/examples/metal_extension/requirements.txt b/examples/metal_extension/requirements.txt new file mode 100644 index 0000000000..9b15290149 --- /dev/null +++ b/examples/metal_extension/requirements.txt @@ -0,0 +1,4 @@ +setuptools>=42 +cmake>=3.25 +mlx>=0.32.0 +nanobind==3.1.0 diff --git a/examples/metal_extension/setup.py b/examples/metal_extension/setup.py new file mode 100644 index 0000000000..a87b302562 --- /dev/null +++ b/examples/metal_extension/setup.py @@ -0,0 +1,23 @@ +# Copyright © 2026 Apple Inc. + +# from importlib.metadata import version as package_version + +from setuptools import setup + +from mlx import extension + +if __name__ == "__main__": + setup( + ext_modules=[ + extension.MetalExtension( + "mlx_sample_metal_extension", + sources=[ + "activation.cpp", + "silu_and_mul.metal", + ], + extra_compile_args={"cxx": ["-O3"], "metal": ["-O3"]}, + ) + ], + cmdclass={"build_ext": extension.BuildExtension}, + # install_requires=[f"mlx=={package_version('mlx')}"], + ) diff --git a/examples/metal_extension/silu_and_mul.metal b/examples/metal_extension/silu_and_mul.metal new file mode 100644 index 0000000000..5ee7553451 --- /dev/null +++ b/examples/metal_extension/silu_and_mul.metal @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adapted from huggingface/kernels-community activation_metal at commit +// 47a3168d0808921eef2f7daca794a4fccae13078. +#include +using namespace metal; + +inline float silu(float x) { + return x / (1.0f + metal::exp(-x)); +} + +inline float4 silu(float4 x) { + return x / (1.0f + metal::exp(-x)); +} + +kernel void silu_and_mul_f16( + device half* out [[buffer(0)]], + device const half* input [[buffer(1)]], + constant uint& d [[buffer(2)]], + uint2 gid [[thread_position_in_grid]]) { + uint base_idx = gid.x * 8; + if (base_idx >= d) { + return; + } + + uint in_base = gid.y * 2u * d; + uint out_base = gid.y * d; + + if (base_idx + 8 <= d) { + float4 x0 = float4( + *reinterpret_cast(&input[in_base + base_idx])); + float4 x1 = float4( + *reinterpret_cast(&input[in_base + base_idx + 4])); + float4 y0 = float4( + *reinterpret_cast(&input[in_base + d + base_idx])); + float4 y1 = float4(*reinterpret_cast( + &input[in_base + d + base_idx + 4])); + + *reinterpret_cast(&out[out_base + base_idx]) = + half4(silu(x0) * y0); + *reinterpret_cast(&out[out_base + base_idx + 4]) = + half4(silu(x1) * y1); + } else if (base_idx + 4 <= d) { + float4 x = float4( + *reinterpret_cast(&input[in_base + base_idx])); + float4 y = float4( + *reinterpret_cast(&input[in_base + d + base_idx])); + *reinterpret_cast(&out[out_base + base_idx]) = + half4(silu(x) * y); + + for (uint i = base_idx + 4; i < d; i++) { + float x = float(input[in_base + i]); + float y = float(input[in_base + d + i]); + out[out_base + i] = half(silu(x) * y); + } + } else { + for (uint i = base_idx; i < d; i++) { + float x = float(input[in_base + i]); + float y = float(input[in_base + d + i]); + out[out_base + i] = half(silu(x) * y); + } + } +} diff --git a/examples/metal_extension/test.py b/examples/metal_extension/test.py new file mode 100644 index 0000000000..21630cb16c --- /dev/null +++ b/examples/metal_extension/test.py @@ -0,0 +1,17 @@ +import mlx.core as mx +from mlx_sample_metal_extension import silu_and_mul + +base = mx.arange(2 * 74 * 3, dtype=mx.float32).reshape(2, 74, 3) +x = mx.sin(base * 0.17).transpose(0, 2, 1).astype(mx.float16) + +d = x.shape[-1] // 2 +left = x[..., :d] +right = x[..., d:] + +output = silu_and_mul(x, stream=mx.gpu) +expected = (left * mx.sigmoid(left)) * right +mx.eval(output, expected) + +correct = mx.allclose(output, expected, rtol=2e-3, atol=2e-3).item() +print(f"silu_and_mul: shape={output.shape}, dtype={output.dtype}, correct={correct}") +assert correct diff --git a/fork.yaml b/fork.yaml index f5d1ba32b7..16854c7466 100644 --- a/fork.yaml +++ b/fork.yaml @@ -6,11 +6,12 @@ footer: | base: name: ml-explore/mlx url: https://github.com/ml-explore/mlx - # The upstream commit this fork is based on. CI (`scripts/check_forkdiff.py`) - # requires this to equal `git merge-base HEAD upstream/main`, so a rebase onto - # newer upstream fails the gate until the hash — and the sections below — are - # brought up to date. Upstream main as of 2026-08-14. - hash: 77a0c1e8ae16eb781a79e2b7134ba84b2ee7b597 + # The upstream commit this fork is based on: upstream main on 2026-10-23, the + # head that the fork merged on that date. CI (`scripts/check_forkdiff.py`) + # requires this hash to equal `git merge-base HEAD upstream/main`. Each upstream + # merge moves the merge-base, so the gate fails until this hash and the + # sections below are brought up to date. + hash: afc03c51105a8e25e70fa2ba0befb214e4f5ec6f fork: name: Layr-Labs/mlx url: https://github.com/Layr-Labs/mlx @@ -29,10 +30,6 @@ def: control, declared-mutable custom-kernel inputs for paged KV, and a use-after-free fix in Metal eval. Every change is meant to be additive and rebasable; each is gated by shape, device or environment checks so the upstream path stays the default elsewhere. - - One section is not fork work at all: the fork carries upstream's own v0.32.2 changes - (applied in PR #10 rather than merged), and those files are listed as such so the page - stays honest about what Layr-Labs actually changed. sub: - title: "Metal eval: use-after-free with mid-eval synchronization" description: | @@ -55,17 +52,16 @@ def: an older library fails the route closed; `trust` skips the descriptor-retract readback when the caller guarantees sorted indices. A retracted call runs the unsorted gather route, because the sorted `gather_qmm_rhs` kernels read per-expert offsets and give a - correct result only for sorted indices. Diagnostics counters + correct result only for sorted indices (PR #27). Diagnostics counters (`mlx_metal_gemma4_expert_qmm_diagnostics_*`) are exposed through a C ABI so mlx-c / - mlx-swift can arm, snapshot and reset them. Also in these kernels: every affine - quantized-vector bias-sum operand is promoted to the accumulator type before summation - (PR #15). + mlx-swift can arm, snapshot and reset them. globs: - "mlx/backend/common/gemma4_expert_qmm.h" - "mlx/backend/metal/device.h" - "mlx/backend/metal/device.cpp" - "mlx/backend/metal/kernels/quantized.h" - "mlx/backend/metal/kernels/quantized.metal" + - "mlx/backend/metal/quantized.cpp" - "tests/gpu_tests.cpp" - title: "Thread-scoped command-buffer commit limits" description: | @@ -176,26 +172,20 @@ def: - "mlx/compile.cpp" - "mlx/compile_impl.h" - "tests/compile_tests.cpp" - - title: "Integer floor_divide rounds down" + - title: "Integer floor_divide tests" description: | - `floor_divide` on integers uses the `Divide` primitive. The CPU and Metal `Divide` - functors truncated toward zero, so `-7 // 2` gave -3. NumPy and Python give -4. For - signed integers the functors now subtract 1 when the remainder is not zero and the - signs are different. On the CPU the signed-integer functor does not divide by 0 or - divide the minimum value by -1, because C++ does not define these. It returns 0 for - `x // 0` and the minimum value for `min // -1`, the same values as before. The Metal - Shading Language does not define these cases either. Unsigned and floating-point - division do not change. Upstream fixed the same defect in `ops.cpp` (ml-explore/mlx - #4515); the fork does the fix in the kernels. If a later upstream sync ports #4515 on - top of these kernels, `floor_divide` subtracts 1 twice; the tests catch this. The CUDA - `Divide` functor (`cuda/device/binary_ops.cuh:36-41`) does not change and still - truncates; no workflow in this fork builds CUDA. mlx-swift keeps generated copies of - both headers (`Source/Cmlx/mlx-generated/binary_ops.cpp`, - `mlx-generated/metal/binary_ops.h`, `mlx-generated/compiled_preamble.cpp`), so - `tools/update-mlx.sh` must run at the mlx-swift pin bump. + The fork keeps its regression tests for integer `floor_divide` from PR #32. Upstream + now does the fix itself: ml-explore/mlx #4515 fixes `floor_divide` in `ops.cpp` and + #4642 adds a `FloorDivide` primitive that rounds down. The fork dropped its own flooring `Divide` functors when it merged + upstream on 2026-10-22, so integer `Divide` truncates again, as in upstream. The tests + check negative operands of every signed integer type, the SIMD and scalar paths, + unsigned and floating-point division, and compiled graphs. On the CPU they also check + that `x // 0` gives 0 and `min // -1` gives the minimum value. Upstream's CPU + `floor_divide` divided `min` by -1, which overflows and traps on x86 (SIGFPE). The + fork divides by 1 there, as PR #32 did, so the result wraps to `min`. globs: - - "mlx/backend/cpu/binary_ops.h" - - "mlx/backend/metal/kernels/binary_ops.h" + - "mlx/backend/cpu/simd/base_simd.h" + - "mlx/backend/cpu/simd/accelerate_simd.h" - "tests/ops_tests.cpp" - "python/tests/test_ops.py" - title: "Validated custom Metal threadgroups and bounded compiler retry" @@ -242,172 +232,133 @@ def: globs: - "mlx/backend/cpu/quantized.cpp" - "python/tests/test_quantized.py" - - title: "Upstream v0.32.2 sync carried in PR #10" + - title: "Every simdgroup runs the MMA in the sorted gather_qmm NAX kernels" description: | - **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official - v0.32.2 by applying upstream's changes rather than merging them, so `git` sees them as - fork commits even though the imported content matches upstream `v0.32.2` - (CUDA backend, CPU SIMD, kernels, Python bindings and tests, repository CI and - templates, `AGENTS.md` / `CLAUDE.md`, docs). Listed here so the page does not credit - Layr-Labs with upstream's changes; the section disappears once the fork rebases onto - an upstream commit at or past v0.32.2. Later fork changes to these paths - are described in their own sections, including quantized NAX tile bounds. + The fork reverts one upstream change in two NAX kernels: the simdgroup skip of + [ml-explore/mlx#4352](https://github.com/ml-explore/mlx/pull/4352) (`c7ff35d9`, kept by + [ml-explore/mlx#4572](https://github.com/ml-explore/mlx/pull/4572) as + `sg_active = sgp_sm > 0`). `fp_gather_qmm_rhs_nax` and `affine_gather_qmm_rhs_nax` run + the MMA in every simdgroup. With the skip, mixture-of-experts serving on a two-Mac + JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB wired + until a reboot. Stores stay bounded by `sgp_sm`, so the output does not change. Keep + the revert at every upstream merge. Upstream added the row-tile scheduling of #4567 + and #4572, which the fork had carried as a backport in PR #27, so only this revert + remains. globs: - - ".pre-commit-config.yaml" - - "AGENTS.md" - - "CLAUDE.md" - - "CMakeLists.txt" - - "CONTRIBUTING.md" - - "setup.py" - - ".github/pull_request_template.md" - - ".github/ISSUE_TEMPLATE/*" - - ".github/actions/build-macos/action.yml" - - ".github/actions/setup/action.yml" - - ".github/actions/build-wheel/action.yml" - - ".github/actions/test-linux/action.yml" - - ".github/actions/test-macos/action.yml" - - "benchmarks/python/sdpa_bench.py" - - "docs/src/install.rst" - - "docs/src/python/fast.rst" - - "examples/extensions/*" - - "mlx/array.h" - - "mlx/einsum.cpp" - - "mlx/error.h" - - "mlx/event.h" - - "mlx/fast.cpp" - - "mlx/fence.h" - - "mlx/fft.cpp" - - "mlx/ops.cpp" - - "mlx/ops.h" - - "mlx/primitives.cpp" - - "mlx/primitives.h" - - "mlx/scheduler.cpp" - - "mlx/scheduler.h" - - "mlx/version.h" - - "mlx/backend/common/load.cpp" - - "mlx/backend/cpu/*" - - "mlx/backend/cpu/simd/base_simd.h" - - "mlx/backend/cuda/CMakeLists.txt" - - "mlx/backend/cuda/cross_entropy.cu" - - "mlx/backend/cuda/cuda_utils.h" - - "mlx/backend/cuda/custom_kernel.cpp" - - "mlx/backend/cuda/delayload.cpp" - - "mlx/backend/cuda/device.cpp" - - "mlx/backend/cuda/device.h" - - "mlx/backend/cuda/dirs.cpp" - - "mlx/backend/cuda/event.cu" - - "mlx/backend/cuda/event.h" - - "mlx/backend/cuda/fence.cpp" - - "mlx/backend/cuda/jit_module.cpp" - - "mlx/backend/cuda/scaled_dot_product_attention.cpp" - - "mlx/backend/cuda/device/binary_ops.cuh" - - "mlx/backend/metal/compiled.cpp" - - "mlx/backend/metal/conv.cpp" - - "mlx/backend/metal/event.cpp" - - "mlx/backend/metal/event.h" - - "mlx/backend/metal/fence.cpp" - - "mlx/backend/metal/jit_kernels.cpp" - - "mlx/backend/metal/kernels.h" - - "mlx/backend/metal/nojit_kernels.cpp" - - "mlx/backend/metal/normalization.cpp" - - "mlx/backend/metal/primitives.cpp" - - "mlx/backend/metal/kernels/binary_ops.h" - - "mlx/backend/metal/kernels/copy.h" - - "mlx/backend/metal/kernels/fp_quantized_nax.h" - - "mlx/backend/metal/kernels/fp_quantized_nax.metal" - - "mlx/backend/metal/kernels/fp8.h" - "mlx/backend/metal/kernels/quantized_nax.h" - - "mlx/backend/metal/kernels/quantized_nax.metal" - - "mlx/backend/metal/kernels/rms_norm.metal" - - "mlx/backend/metal/kernels/sort.h" - - "mlx/backend/metal/kernels/utils.h" - - "mlx/backend/metal/kernels/reduction/*" - - "mlx/backend/metal/kernels/steel/attn/kernels/*" - - "mlx/backend/no_gpu/event.cpp" - - "mlx/backend/no_gpu/fence.cpp" - - "mlx/backend/no_gpu/primitives.cpp" - - "mlx/distributed/mpi/mpi.cpp" - - "mlx/distributed/ring/ring.cpp" - - "mlx/io/gguf.cpp" - - "python/mlx/*" - - "python/mlx/_distributed_utils/launch.py" - - "python/mlx/nn/losses.py" - - "python/mlx/nn/layers/normalization.py" - - "python/mlx/optimizers/optimizers.py" - - "python/src/*" - - "python/tests/__main__.py" - - "python/tests/mlx_tests.py" - - "python/tests/run.py" - - "python/tests/test_array.py" - - "python/tests/test_compile.py" - - "python/tests/test_conv_transpose.py" - - "python/tests/test_double.py" - - "python/tests/test_einsum.py" - - "python/tests/test_eval.py" - - "python/tests/test_fast.py" - - "python/tests/test_load.py" - - "python/tests/test_nn.py" - - "python/tests/test_ops.py" - - "python/tests/test_quantized.py" - - "python/tests/test_reduce.py" - - "python/tests/test_vmap.py" - - "tests/load_tests.cpp" - - "tests/ops_tests.cpp" - - title: "Upstream gather_mm and gather_qmm row-tile scheduling (ml-explore/mlx #4567, #4572)" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - title: "64-bit products in the JACCL ring and the vector SDPA layout check" description: | - **Not fork work.** Cherry-picks of upstream commits `a2a09fd5` - ([ml-explore/mlx#4567](https://github.com/ml-explore/mlx/pull/4567)) and `90089440` - ([ml-explore/mlx#4572](https://github.com/ml-explore/mlx/pull/4572)). The sorted - `gather_mm` and `gather_qmm` kernels schedule row tiles from per-expert offsets, so - one tile holds rows of one expert and does one matmul pass. A small kernel - (`gather_mm_offsets`) computes the offsets from the sorted `rhs_indices`. - - The `gather_qmm` change is in `quantized.h`, `quantized_nax.h`, `fp_quantized.h`, - `fp_quantized_nax.h` and `quantized.cpp`, which are listed in the sections that - describe the fork work in those files. `utils.h` (`schedule_row_tile`) is listed in - the v0.32.2 section. Two differences from upstream `90089440` remain in the ported - kernels, because the fork base does not have the related upstream changes: the - floating-point kernels have no global-scale input, and the NAX kernels keep the - fork's bound for the last K tile. The section disappears once the fork rebases onto - an upstream commit at or past `90089440`. - - One upstream change in these NAX kernels is reverted on purpose: the simdgroup skip - of [ml-explore/mlx#4352](https://github.com/ml-explore/mlx/pull/4352) (`c7ff35d9`, - which arrived with the v0.32.2 changes; `#4572` kept it as - `sg_active = sgp_sm > 0`). `fp_gather_qmm_rhs_nax` and `affine_gather_qmm_rhs_nax` run - the MMA in every simdgroup again. With the skip, mixture-of-experts serving on a - two-Mac JACCL pair with one NAX GPU lost all-reduce completions and left 92 to 96 GiB - wired until a reboot. Stores stay bounded by `sgp_sm`, so the output is unchanged. - Keep the revert at every rebase onto upstream. + The JACCL ring computes each wire's byte offset as `lr * n_wires * size`. Upstream + multiplies `lr` and `n_wires` as `int` before the product widens to 64 bits, and + compares `size_ * 2 * n_conns_` as `int`. The fork widens the first operand to + `int64_t`, so each product is computed in 64 bits. The values are small, so the result + does not change. The vector SDPA path checks a query layout with + `strides[2] == shape[3] * shape[bidx]`, where the product is `int` and the stride is + 64-bit. The fork widens `shape[3]` to `int64_t` there too. These changes close the CodeQL + alerts `cpp/integer-multiplication-cast-to-long` in these files. + globs: + - "mlx/distributed/jaccl/lib/jaccl/ring_impl.h" + - "mlx/distributed/jaccl/lib/jaccl/ring.cpp" + - "mlx/backend/metal/scaled_dot_product_attention.cpp" + - title: "CPU qqmm refuses a global scale" + description: | + The CPU `QQMatmul` kernel has no global scale input. Upstream passes the scales to it, + and the kernel ignores them, so `qqmm` with `global_scale_x` and `global_scale_w` on + a CPU stream returns a wrong result with no error (upstream marks this as a TODO in + `test_quantized.py`). The fork's CPU test pass found it: the error was about 1000 + against a tolerance of 1e-3. `qqmm` now raises "Global scale is only supported on the + GPU" on a stream that is not a GPU stream, as `gather_qmm` already does. + globs: + - "mlx/ops.cpp" + - title: "CPU BLAS gemm clears C when beta is 0" + description: | + The CPU backend calls BLAS gemm with beta = 0 in five places: the float32, float64 + and complex64 `matmul` wrappers in `gemms/cblas.cpp` (used by `Matmul`, `AddMM` + and `SegmentedMM`), `BlockMaskedMM` and `GatherMM` in `masked_mm.cpp`, and the two + explicit-gemm convolutions in `conv.cpp`. BLAS must not read C when beta is 0, but + Accelerate can (seen with M = 1). An output buffer from the allocator cache can + hold old data, for example packed fp4 weights that read as NaN, and NaN * 0 is NaN. + Upstream's `test_fp_gather_qmm_non_multiple_of_32` found it in the fork's CPU test + pass: its float32 reference `x @ w_sel` reused the 266240-byte buffer of the + previous subtest's packed weights. One helper, `clear_gemm_output` in `gemm.h`, + fills the exact C region of each call (rows by columns, with its `ldc`) with zeros + before the call. MLX's own SIMD gemm already skips C when beta is 0. This is a + latent upstream bug. globs: - - ".gitignore" - - "benchmarks/python/swiglu_bench.py" - - "benchmarks/python/swiglu_qmm_bench.py" - - "mlx/backend/metal/matmul.cpp" - - "mlx/backend/metal/matmul.h" - - "mlx/backend/metal/kernels/CMakeLists.txt" - - "mlx/backend/metal/kernels/gather_mm_offsets.metal" - - "mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_gather.h" - - "mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_gather_nax.h" + - "mlx/backend/cpu/gemm.h" + - "mlx/backend/cpu/gemms/cblas.cpp" + - "mlx/backend/cpu/masked_mm.cpp" + - "mlx/backend/cpu/conv.cpp" + - title: "Reference uniqueness without buffer ownership" + description: | + Upstream [ml-explore/mlx#4634](https://github.com/ml-explore/mlx/pull/4634) (`5dbe9991`) + makes `is_donatable()` also require that MLX owns the buffer, so the allocator never + reuses a wrapped external buffer. The fork's C API (`mlx_array_get_buffer_info`, field + `unique`) used `is_donatable()` to prove that no other array references a buffer. + Callers in mlx-swift-lm use that proof for paged KV segments, checkpoint memory + accounting and the MTP state, also for wrapped host pages. The fork adds + `array::is_uniquely_referenced()`: the same reference-count test without the ownership + test. `is_donatable()` and buffer donation do not change. + globs: + - "mlx/array.h" + - title: "async_eval does not throw a stream task error" + description: | + Upstream #4338 raises a CPU stream task error from `synchronize`, and its test + expects `async_eval` not to throw. But `StreamThread::enqueue` throws the stored + error on the main thread (#3742). `async_eval` enqueues several tasks: when the + stream thread runs a failing task before `async_eval` enqueues the next one, that + enqueue throws. This is a race. It failed `test_async_eval_error_in_synchronize` + in the fork's CPU test pass on some runs. `async_eval` now holds a + `scheduler::DeferStreamErrors` guard, and `enqueue` does not throw while the guard + lives on the thread. `synchronize` throws the error later. `eval` does not change. + A C++ test stores the error first, so it fails without the fix on every run. + globs: + - "mlx/scheduler.h" + - "mlx/scheduler.cpp" + - "mlx/transforms.cpp" + - "tests/scheduler_tests.cpp" - title: "Fork tooling" description: | - The fork deletes the upstream workflows that cannot run here: the PyPI release build and - the documentation deploy. `build_and_test.yml` keeps the lint, sanitizer and Fedora jobs. - The fork deletes the jobs that run only in the upstream repository, and the composite - actions that only the deleted workflows and jobs used. + The fork deletes the upstream workflows that cannot run here: the PyPI release build, + the documentation deploy and the daily bypass-list update with its two scripts. + `build_and_test.yml` keeps the lint, sanitizer and Fedora jobs. The fork deletes the + jobs that run only in the upstream repository, and the composite actions that only + the deleted workflows and jobs used. An upstream merge adds these files again, so + delete them again at each merge. The gate that keeps this page honest: `check_forkdiff.py` fails CI when `base.hash` is not the merge-base with upstream, when a file the fork changes is not described by a section above, or when a section names files the fork no longer changes. - `fork-tests.yml` builds the fork with Metal and runs its C++ and Python tests on a - GitHub-hosted macOS runner. The `setup` action pins its actions to full commit SHAs, - because the organization blocks actions that are not pinned. The organization also - blocks `hendrikmuhs/ccache-action`, so `setup` installs ccache with Homebrew and keeps - the ccache files with `actions/cache`. It then runs the same tests a second time with - the CPU as the default device. Two Python tests check behavior that exists only in the - Metal backend (Winograd batch tiling and the FFT size limit), so they skip when the - default device is not the GPU. + `fork-tests.yml` builds the fork with Metal and runs its C++ and Python tests on + GitHub-hosted macOS runners. Two jobs build in parallel. One job builds the Python + wheel. The other job builds the C++ library and tests, and runs the C++ tests with the + GPU and then with the CPU as the default device. The Python tests run in shard jobs: + one set with the GPU as the default device, and one set with the CPU. + `.github/scripts/fork-tests/python-shards.json` gives the shards. + `python_shards.py` fails a job when a test file is in no shard or in two shards, and + the last job fails when a test ran in two shards. The last job also merges the coverage + profiles of all jobs into one report. The `setup` action pins its actions to full + commit SHAs, because the organization blocks actions that are not pinned. The + organization also blocks `hendrikmuhs/ccache-action`, so `setup` installs ccache with + Homebrew and restores the ccache files with `actions/cache`. The `fork-build-cache` + action saves the ccache files. It also keeps a cache of the compiled Metal kernels: the + build jobs put `metal-cache/xcrun` first in `PATH`, and that script gives the kernel + compile and link commands a cache. The key of a kernel is its preprocessed source, + its arguments, the metal compiler version and the SDK build. The ccache key holds + the clang version, and ccache checks the compiler content of each object. Three Python tests check behavior that exists only in + the Metal backend (Winograd batch tiling, the Winograd switch and the FFT size limit), + so they skip when the default device is not the GPU. Upstream's + `test_init_reduce_large_output` skips only when the default device cannot hold its + 4 GiB output: on the GPU when `max_buffer_length` is less than 4 GiB, on the CPU when + `memory_size` is less than 16 GiB. The hosted `macos-26` runner caps Metal buffers at + 3.5 GiB. The test cannot be smaller: it is the regression test for ml-explore/mlx + #4437, which needs 2^32 output elements (more than one 32-bit grid dimension), and + bool outputs of one byte each give 4 GiB. David ruled on 2026-10-23 to keep this skip + and not to use a larger runner. When a Python test entry fails, the job prints the end of + its log at once. Upstream tests that run only a GPU path (forced fused SDPA, global-scale + `qqmm` and `gather_qmm`) check on the CPU pass that the documented error is raised. globs: - ".github/actions/build/action.yml" - ".github/actions/build-docs/action.yml" @@ -418,13 +369,21 @@ def: - ".github/workflows/build_and_test.yml" - ".github/workflows/documentation.yml" - ".github/workflows/release.yml" + - ".github/workflows/update_bypass_list.yml" + - ".github/scripts/find-eligible-contributors.js" + - ".github/scripts/update-bypass-list.js" - "scripts/check_forkdiff.py" - "FORKDIFF.md" - "README.md" - ".github/actions/setup/action.yml" + - ".github/actions/fork-build-cache/action.yml" + - ".github/scripts/fork-tests/metal-cache/xcrun" + - ".github/scripts/fork-tests/python-shards.json" + - ".github/scripts/fork-tests/python_shards.py" - ".github/workflows/fork-tests.yml" - "python/tests/test_conv.py" - "python/tests/test_fft.py" + - "python/tests/test_reduce.py" # ignored globally, does not count towards line count ignore: diff --git a/mlx/CMakeLists.txt b/mlx/CMakeLists.txt index 0df4f42349..f6d1a4aa2d 100644 --- a/mlx/CMakeLists.txt +++ b/mlx/CMakeLists.txt @@ -18,6 +18,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/transforms.cpp ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/linalg.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/memory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/backend/metal/metal.h) # Define MLX_VERSION only in the version.cpp file. @@ -27,11 +28,13 @@ target_include_directories(mlx_version PRIVATE ${PROJECT_SOURCE_DIR}) target_link_libraries(mlx PRIVATE $) # Do not export symbols by default. -set_target_properties( - mlx mlx_version - PROPERTIES VISIBILITY_INLINES_HIDDEN ON - CXX_VISIBILITY_PRESET hidden - CUDA_VISIBILITY_PRESET hidden) +if(NOT MLX_EXPORT_ALL_SYMBOLS) + set_target_properties( + mlx mlx_version + PROPERTIES VISIBILITY_INLINES_HIDDEN ON + CXX_VISIBILITY_PRESET hidden + CUDA_VISIBILITY_PRESET hidden) +endif() # Define MLX_EXPORT for shared libraries, MLX_STATIC for static libraries. set_target_properties(mlx PROPERTIES DEFINE_SYMBOL MLX_EXPORT) @@ -52,6 +55,9 @@ endif() if(WIN32) # windows.h defines min/max macros that conflict with std::min/std::max. target_compile_definitions(mlx PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN) + # TODO: Remove after removing std::atomic_store/load. + target_compile_definitions( + mlx PUBLIC _SILENCE_CXX20_OLD_SHARED_PTR_ATOMIC_SUPPORT_DEPRECATION_WARNING) endif() if(MSVC) # Unicode support in fmt does not compile in .cu files. diff --git a/mlx/allocator.h b/mlx/allocator.h index c831b7247d..6ef8599455 100644 --- a/mlx/allocator.h +++ b/mlx/allocator.h @@ -3,9 +3,20 @@ #pragma once #include +#include +#include #include "mlx/api.h" +namespace mlx::core::allocator { +class Data; +} // namespace mlx::core::allocator + +namespace mlx::core::cu { +class CommandEncoder; +allocator::Data malloc_async(size_t size, CommandEncoder& encoder); +} // namespace mlx::core::cu + namespace mlx::core::allocator { // Simple wrapper around buffer pointers @@ -51,12 +62,47 @@ class MLX_API Allocator { MLX_API Allocator& allocator(); -inline Buffer malloc(size_t size) { - return allocator().malloc(size); -} +using Deleter = std::function; + +// The allocator owns data from malloc +class Data { + public: + Data(Buffer buffer, Deleter d) : buffer_(buffer), deleter_(std::move(d)) {} + Data(const Data& other) = delete; + Data& operator=(const Data& other) = delete; + Data(Data&& other) noexcept + : buffer_(std::exchange(other.buffer_, Buffer(nullptr))), + deleter_(std::exchange(other.deleter_, nullptr)), + owned_(std::exchange(other.owned_, false)) {} + ~Data() { + if (owned_) { + allocator().free(buffer_); + } else if (deleter_) { + deleter_(buffer_); + } + } + + Buffer buffer() const& { + return buffer_; + } + Buffer buffer() const&& = delete; + + bool is_owned() const { + return owned_; + } + + private: + Buffer buffer_; + Deleter deleter_; + bool owned_{false}; + + explicit Data(Buffer buffer) : buffer_(buffer), owned_(true) {} + friend Data malloc(size_t size); + friend Data cu::malloc_async(size_t size, cu::CommandEncoder& encoder); +}; -inline void free(Buffer buffer) { - allocator().free(buffer); +inline Data malloc(size_t size) { + return Data(allocator().malloc(size)); } // Make a Buffer from a raw pointer of the given size without a copy. If a diff --git a/mlx/array.cpp b/mlx/array.cpp index 07d3acd616..cf49a0fe5f 100644 --- a/mlx/array.cpp +++ b/mlx/array.cpp @@ -60,13 +60,11 @@ std::vector array::make_arrays( array array::unsafe_weak_copy(const array& other) { auto cpy = array(other.shape(), other.dtype(), nullptr, {}); cpy.set_data( - other.buffer(), + Data(other.buffer(), nullptr), other.data_size(), other.strides(), other.flags(), - 0, - [](auto) {}); - cpy.array_desc_->offset = other.array_desc_->offset; + other.offset()); return cpy; } @@ -104,14 +102,13 @@ array::array( allocator::release(buffer); return deleter(ptr); }; - set_data(buffer, std::move(wrapped_deleter)); + set_data(Data(buffer, std::move(wrapped_deleter))); } } -/* Build an array from a shared buffer */ -array::array(allocator::Buffer data, Shape shape, Dtype dtype, Deleter deleter) +array::array(allocator::Data data, Shape shape, Dtype dtype) : array_desc_(std::make_shared(std::move(shape), dtype)) { - set_data(data, deleter); + set_data(std::move(data)); } void array::detach() { @@ -166,8 +163,8 @@ bool array::is_tracer() const { detail::retain_graph(); } -void array::set_data(allocator::Buffer buffer, Deleter d) { - array_desc_->data = std::make_shared(buffer, d); +void array::set_data(allocator::Data data) { + array_desc_->data = std::make_shared(std::move(data)); array_desc_->offset = 0; array_desc_->data_size = size(); array_desc_->flags.contiguous = true; @@ -177,13 +174,12 @@ void array::set_data(allocator::Buffer buffer, Deleter d) { } void array::set_data( - allocator::Buffer buffer, + allocator::Data data, size_t data_size, Strides strides, Flags flags, - int64_t offset, - Deleter d) { - array_desc_->data = std::make_shared(buffer, d); + int64_t offset) { + array_desc_->data = std::make_shared(std::move(data)); array_desc_->offset = offset; array_desc_->data_size = data_size; array_desc_->strides = std::move(strides); @@ -208,34 +204,33 @@ void array::copy_shared_buffer(const array& other) { copy_shared_buffer(other, other.strides(), other.flags(), other.data_size()); } -array::~array() { - if (array_desc_ == nullptr) { +void array::release(std::shared_ptr desc) { + if (desc == nullptr) { return; } // Detached/detaching - if (array_desc_->primitive == nullptr) { + if (desc->primitive == nullptr) { return; } // Break circular reference for non-detached arrays with siblings - if (auto n = siblings().size(); n > 0) { + if (auto n = desc->siblings.size(); n > 0) { bool do_detach = true; // If all siblings have siblings.size() references except - // the one we are currently destroying (which has siblings.size() + 1) + // the one we are currently releasing (which has siblings.size() + 1) // then there are no more external references - do_detach &= (array_desc_.use_count() == (n + 1)); - for (auto& s : siblings()) { + do_detach &= (desc.use_count() == (n + 1)); + for (auto& s : desc->siblings) { do_detach &= (s.array_desc_.use_count() == n); if (!do_detach) { break; } } if (do_detach) { - for (auto& s : siblings()) { + for (auto& s : desc->siblings) { for (auto& ss : s.siblings()) { - // Set to null here to avoid descending into array destructor - // for siblings + // Set to null here to avoid descending into reset() for siblings ss.array_desc_ = nullptr; } s.array_desc_->siblings.clear(); diff --git a/mlx/array.h b/mlx/array.h index 3f45e9cb9d..43483aab4d 100644 --- a/mlx/array.h +++ b/mlx/array.h @@ -3,8 +3,10 @@ #include #include +#include #include #include +#include #include #include "mlx/allocator.h" @@ -18,7 +20,6 @@ namespace mlx::core { // Forward declaration class Primitive; -using Deleter = std::function; using ShapeElem = int32_t; using Shape = SmallVector; using Strides = SmallVector; @@ -68,25 +69,30 @@ class MLX_API array { Dtype dtype, const std::function& deleter); - /* Build an array from a buffer */ - explicit array( - allocator::Buffer data, - Shape shape, - Dtype dtype, - Deleter deleter = allocator::free); + /* Build an array from data */ + explicit array(allocator::Data data, Shape shape, Dtype dtype); /** Assignment to rvalue does not compile. */ array& operator=(const array& other) && = delete; array& operator=(array&& other) && = delete; /** Default copy and move constructors otherwise. */ - array& operator=(array&& other) & = default; array(const array& other) = default; array(array&& other) = default; + /** Assignment goes through release() to break sibling reference cycle. */ array& operator=(const array& other) & { - if (this->id() != other.id()) { - this->array_desc_ = other.array_desc_; + if (array_desc_ != other.array_desc_) { + // Hold the old descriptor while assigning, and then release it. Otherwise + // when |this| and |other| are siblings they would be both destroyed. + release(std::exchange(array_desc_, other.array_desc_)); + } + return *this; + } + + array& operator=(array&& other) & noexcept { + if (array_desc_ != other.array_desc_) { + release(std::exchange(array_desc_, std::move(other.array_desc_))); } return *this; } @@ -228,22 +234,7 @@ class MLX_API array { return reinterpret_cast(array_desc_->primitive.get()); } - struct Data { - allocator::Buffer buffer; - Deleter d; - Data(allocator::Buffer buffer, Deleter d = allocator::free) - : buffer(buffer), d(d) {} - // Not copyable - Data(const Data& d) = delete; - Data& operator=(const Data& d) = delete; - Data(Data&& o) : buffer(o.buffer), d(o.d) { - o.buffer = allocator::Buffer(nullptr); - o.d = [](allocator::Buffer) {}; - } - ~Data() { - d(buffer); - } - }; + using Data = allocator::Data; struct Flags { // True iff there are no gaps in the underlying data. Each item @@ -292,6 +283,14 @@ class MLX_API array { /** True indicates the arrays buffer is safe to reuse */ bool is_donatable() const { + return array_desc_.use_count() == 1 && + (array_desc_->data.use_count() == 1) && array_desc_->data->is_owned(); + } + + /** True when no other array references this array or its data. Unlike + * is_donatable(), this does not require MLX to own the buffer, so a wrapped + * external buffer can be unique. */ + bool is_uniquely_referenced() const { return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1); } @@ -349,11 +348,8 @@ class MLX_API array { return array_desc_->data_size; } - allocator::Buffer& buffer() { - return array_desc_->data->buffer; - } - const allocator::Buffer& buffer() const { - return array_desc_->data->buffer; + allocator::Buffer buffer() const { + return array_desc_->data->buffer(); } size_t buffer_size() const { @@ -437,24 +433,14 @@ class MLX_API array { // Check if the array is a tracer array bool is_tracer() const; - void set_data(allocator::Buffer buffer, Deleter d = allocator::free); + void set_data(allocator::Data data); void set_data( - allocator::Buffer buffer, + allocator::Data data, size_t data_size, Strides strides, Flags flags, - Deleter d) { - set_data(buffer, data_size, std::move(strides), flags, 0, std::move(d)); - } - - void set_data( - allocator::Buffer buffer, - size_t data_size, - Strides strides, - Flags flags, - int64_t offset = 0, - Deleter d = allocator::free); + int64_t offset = 0); void copy_shared_buffer( const array& other, @@ -466,10 +452,12 @@ class MLX_API array { void copy_shared_buffer(const array& other); void overwrite_descriptor(const array& other) { - array_desc_ = other.array_desc_; + release(std::exchange(array_desc_, other.array_desc_)); } - ~array(); + ~array() { + release(std::move(array_desc_)); + } private: // Initialize the arrays data @@ -532,6 +520,12 @@ class MLX_API array { // the primitive which knows how to compute the array's data from its inputs // and the list of array's inputs for the primitive. std::shared_ptr array_desc_; + + /** + * Lets go of an ArrayDesc, breaking the sibling reference cycle of a + * multi-output primitive. + */ + static void release(std::shared_ptr desc); }; template @@ -579,20 +573,19 @@ T array::item() { throw std::invalid_argument("item can only be called on arrays of size 1."); } eval(); - return *data(); + // Use memcpy to read unaligned data. + T value; + std::memcpy(&value, data(), sizeof(T)); + return value; } template T array::item() const { - if (size() != 1) { - throw std::invalid_argument("item can only be called on arrays of size 1."); - } if (status() == Status::unscheduled) { throw std::invalid_argument( "item() const can only be called on evaled arrays"); } - const_cast(this)->eval(); - return *data(); + return const_cast(this)->item(); } template diff --git a/mlx/backend/common/binary.h b/mlx/backend/common/binary.h index 78607ef07a..a05bc434ca 100644 --- a/mlx/backend/common/binary.h +++ b/mlx/backend/common/binary.h @@ -39,7 +39,7 @@ inline void set_binary_op_output_data( const array& b, array& out, BinaryOpType bopt, - std::function mallocfn = allocator::malloc) { + std::function mallocfn = allocator::malloc) { bool b_donatable = is_donatable(b, out); bool a_donatable = is_donatable(a, out); switch (bopt) { diff --git a/mlx/backend/common/common.cpp b/mlx/backend/common/common.cpp index 5426301a35..1e0692973c 100644 --- a/mlx/backend/common/common.cpp +++ b/mlx/backend/common/common.cpp @@ -2,43 +2,42 @@ #include #include "mlx/backend/common/broadcasting.h" +#include "mlx/backend/common/slicing.h" #include "mlx/backend/common/utils.h" #include "mlx/dtype_utils.h" #include "mlx/primitives.h" namespace mlx::core { -void AsStrided::eval(const std::vector& inputs, array& out) { - assert(inputs.size() == 1); - - auto& in = inputs[0]; - - if (!in.flags().row_contiguous) { - // Just ensuring that inputs[0] came from the ops which would ensure the - // input is row contiguous. - throw std::runtime_error( - "AsStrided must be used with row contiguous arrays only."); - } - - auto [no_bsx_size, row_contiguous, col_contiguous] = - check_contiguity(shape_, strides_); +void AsStrided::eval(const array& in, array& out) { + assert(in.flags().row_contiguous); + auto [_, row_contiguous, col_contiguous] = check_contiguity(shape_, strides_); int64_t l = 0, h = 0; - bool has_negative_stride = false; + std::vector> dims; for (int i = 0; i < strides_.size(); i++) { auto delta = strides_[i] * (shape_[i] - 1); if (strides_[i] >= 0) { h += delta; } else { l += delta; - has_negative_stride |= shape_[i] > 1; + } + if (shape_[i] > 1 && strides_[i] != 0) { + dims.emplace_back(strides_[i], shape_[i]); } } size_t data_size = out.size() == 0 ? 0 : (h - l) + 1; + std::sort(dims.begin(), dims.end()); + int64_t expected_stride = 1; + bool dense = true; + for (auto [stride, size] : dims) { + dense &= stride == expected_stride; + expected_stride *= size; + } + auto flags = in.flags(); - flags.contiguous = - out.size() == 0 || (!has_negative_stride && no_bsx_size == data_size); + flags.contiguous = out.size() == 0 || dense; flags.row_contiguous = row_contiguous; flags.col_contiguous = col_contiguous; @@ -155,6 +154,12 @@ void shared_buffer_reshape( // becomes col contiguous again. auto max_dim = std::max_element(out.shape().begin(), out.shape().end()); flags.col_contiguous = out.size() <= 1 || out.size() == *max_dim; + } else { + // New shape can change contiguity + auto [_, row_contiguous, col_contiguous] = + check_contiguity(out.shape(), out_strides); + flags.row_contiguous = row_contiguous; + flags.col_contiguous = col_contiguous; } out.copy_shared_buffer(in, out_strides, flags, in.data_size()); } @@ -166,48 +171,29 @@ void Split::eval( auto& in = inputs[0]; - auto compute_new_flags = [](const auto& shape, - const auto& strides, - size_t in_data_size, - auto flags) { - size_t data_size = 1; - size_t f_stride = 1; - size_t b_stride = 1; - flags.row_contiguous = true; - flags.col_contiguous = true; - for (int i = 0, ri = shape.size() - 1; ri >= 0; i++, ri--) { - flags.col_contiguous &= strides[i] == f_stride || shape[i] == 1; - flags.row_contiguous &= strides[ri] == b_stride || shape[ri] == 1; - f_stride *= shape[i]; - b_stride *= shape[ri]; - if (strides[i] > 0) { - data_size *= shape[i]; - } + for (int i = 0; i < outputs.size(); i++) { + if (outputs[i].size() == 0) { + outputs[i].set_data(allocator::malloc(0)); + continue; } - if (data_size == 1) { - // Broadcasted scalar array is contiguous. - flags.contiguous = true; - } else if (data_size == in_data_size) { - // Means we sliced a broadcasted dimension so leave the "no holes" flag - // alone. - } else { - // We sliced something. So either we are row or col contiguous or we - // punched a hole. - flags.contiguous &= flags.row_contiguous || flags.col_contiguous; + int64_t start = i == 0 ? 0 : indices_[i - 1]; + int64_t offset = start * in.strides()[axis_]; + + // compute the span + int64_t low_idx = 0; + int64_t high_idx = 0; + for (int j = 0; j < in.ndim(); j++) { + auto delta = in.strides()[j] * (outputs[i].shape()[j] - 1); + if (in.strides()[j] > 0) { + high_idx += delta; + } else { + low_idx += delta; + } } - return std::pair{flags, data_size}; - }; - - std::vector indices(1, 0); - indices.insert(indices.end(), indices_.begin(), indices_.end()); - for (int i = 0; i < indices.size(); i++) { - size_t offset = indices[i] * in.strides()[axis_]; - auto [new_flags, data_size] = compute_new_flags( - outputs[i].shape(), in.strides(), in.data_size(), in.flags()); - outputs[i].copy_shared_buffer( - in, in.strides(), new_flags, data_size, offset); + shared_buffer_slice( + in, in.strides(), offset, (high_idx - low_idx) + 1, outputs[i]); } } diff --git a/mlx/backend/common/compiled.cpp b/mlx/backend/common/compiled.cpp index 9dc5a4c54c..0bcd66fe98 100644 --- a/mlx/backend/common/compiled.cpp +++ b/mlx/backend/common/compiled.cpp @@ -110,7 +110,7 @@ void compiled_allocate_outputs( std::vector& outputs, const std::function& is_constant, bool contiguous, - const std::function& + const std::function& mallocfn /* = allocator::malloc */) { if (contiguous) { int o = 0; diff --git a/mlx/backend/common/compiled.h b/mlx/backend/common/compiled.h index 8c6466da03..c5f91d5786 100644 --- a/mlx/backend/common/compiled.h +++ b/mlx/backend/common/compiled.h @@ -37,9 +37,9 @@ void print_float_constant(std::ostream& os, const array& x) { auto old_precision = os.precision(); if constexpr (std::is_same_v) { - os << std::setprecision(std::numeric_limits::digits10 + 1); + os << std::setprecision(std::numeric_limits::max_digits10); } else { - os << std::setprecision(std::numeric_limits::digits10 + 1); + os << std::setprecision(std::numeric_limits::max_digits10); } os << value << std::setprecision(old_precision); } @@ -78,8 +78,7 @@ void compiled_allocate_outputs( std::vector& outputs, const std::function& is_constant, bool contiguous, - const std::function& mallocfn = - allocator::malloc); + const std::function& mallocfn = allocator::malloc); // Collapse contiguous dims ignoring scalars and constants. std::tuple> diff --git a/mlx/backend/common/copy.h b/mlx/backend/common/copy.h index 859ce0410e..943061b5c4 100644 --- a/mlx/backend/common/copy.h +++ b/mlx/backend/common/copy.h @@ -26,7 +26,7 @@ inline bool set_copy_output_data( const array& in, array& out, CopyType ctype, - std::function mallocfn = allocator::malloc) { + std::function mallocfn = allocator::malloc) { if (ctype == CopyType::Vector) { // If the input is donateable, we are doing a vector copy and the types // have the same size, then the input buffer can hold the output. diff --git a/mlx/backend/common/metal_kernel.cpp b/mlx/backend/common/metal_kernel.cpp index 0efb605a3b..f253f599aa 100644 --- a/mlx/backend/common/metal_kernel.cpp +++ b/mlx/backend/common/metal_kernel.cpp @@ -209,7 +209,7 @@ std::string make_template_hash(const std::string& template_def) { template_hash.reserve(template_def.size()); for (size_t i = 0; i < template_def.size(); ++i) { auto c = template_def[i]; - if (c == '<' || c == '>') { + if (c == '<' || c == '>' || c == '-') { template_hash += '_'; } else if ( c == ',' && i + 1 < template_def.size() && template_def[i + 1] == ' ') { diff --git a/mlx/backend/common/slicing.cpp b/mlx/backend/common/slicing.cpp index cad2fd6196..e2723fb8a7 100644 --- a/mlx/backend/common/slicing.cpp +++ b/mlx/backend/common/slicing.cpp @@ -30,7 +30,8 @@ void shared_buffer_slice( auto flags = in.flags(); flags.row_contiguous = is_row_contiguous; flags.col_contiguous = is_col_contiguous; - flags.contiguous = (no_bsx_size == data_size); + flags.contiguous = is_row_contiguous || is_col_contiguous || + (flags.contiguous && no_bsx_size == data_size); out.copy_shared_buffer(in, out_strides, flags, data_size, data_offset); } diff --git a/mlx/backend/common/slicing.h b/mlx/backend/common/slicing.h index b667d2619d..436a855c2a 100644 --- a/mlx/backend/common/slicing.h +++ b/mlx/backend/common/slicing.h @@ -11,6 +11,13 @@ std::tuple prepare_slice( const Shape& start_indices, const Shape& strides); +void shared_buffer_slice( + const array& in, + const Strides& out_strides, + int64_t data_offset, + size_t data_size, + array& out); + void slice( const array& in, array& out, diff --git a/mlx/backend/common/ternary.h b/mlx/backend/common/ternary.h index c63a572615..bd8da25805 100644 --- a/mlx/backend/common/ternary.h +++ b/mlx/backend/common/ternary.h @@ -47,7 +47,7 @@ inline void set_ternary_op_output_data( const array& c, array& out, TernaryOpType topt, - std::function mallocfn = allocator::malloc) { + std::function mallocfn = allocator::malloc) { auto maybe_donate = [&out](const array& x) { if (is_donatable(x, out)) { out.copy_shared_buffer(x); diff --git a/mlx/backend/common/unary.h b/mlx/backend/common/unary.h index b19fc98eda..b37bb90ab2 100644 --- a/mlx/backend/common/unary.h +++ b/mlx/backend/common/unary.h @@ -10,7 +10,7 @@ namespace mlx::core { inline void set_unary_output_data( const array& in, array& out, - std::function mallocfn = allocator::malloc) { + std::function mallocfn = allocator::malloc) { if (in.flags().contiguous) { if (is_donatable(in, out)) { out.copy_shared_buffer(in); diff --git a/mlx/backend/common/utils.cpp b/mlx/backend/common/utils.cpp index ae169e35e2..a13c022071 100644 --- a/mlx/backend/common/utils.cpp +++ b/mlx/backend/common/utils.cpp @@ -1,6 +1,7 @@ // Copyright © 2023-2024 Apple Inc. #include +#include #include "mlx/backend/common/utils.h" @@ -88,13 +89,16 @@ std::pair collapse_contiguous_dims( Strides collapsed_strides; if (shape.size() > 0) { - collapsed_shape.push_back(shape[0]); - collapsed_strides.push_back(strides[0]); - for (int i = 1; i < shape.size(); i++) { + for (int i = 0; i < shape.size(); i++) { if (shape[i] == 1) { continue; - } else if ( - strides[i] * shape[i] != collapsed_strides.back() || + } + if (collapsed_shape.empty()) { + collapsed_shape.push_back(shape[i]); + collapsed_strides.push_back(strides[i]); + continue; + } + if (strides[i] * shape[i] != collapsed_strides.back() || collapsed_shape.back() * static_cast(shape[i]) > size_cap) { collapsed_shape.push_back(shape[i]); collapsed_strides.push_back(strides[i]); @@ -103,6 +107,10 @@ std::pair collapse_contiguous_dims( collapsed_strides.back() = strides[i]; } } + if (collapsed_shape.empty()) { + collapsed_shape.push_back(1); + collapsed_strides.push_back(1); + } } return std::make_pair(collapsed_shape, collapsed_strides); @@ -174,6 +182,22 @@ Dims get_2d_grid_dims_common( const Shape& shape, const Strides& strides, size_t divisor) { + // Shortcut when size is a multiple of divisor, for example: + // 36: {2 / 2, 4 / 2, 9 / 9} = {1, 2, 1} + Shape divided_shape = shape; + size_t remaining_divisor = divisor; + for (int i = 0; i < shape.size(); ++i) { + if (strides[i] == 0) { + continue; + } + auto factor = std::gcd(static_cast(shape[i]), remaining_divisor); + divided_shape[i] /= factor; + remaining_divisor /= factor; + } + if (remaining_divisor == 1) { + return get_2d_grid_dims_common(divided_shape, strides); + } + // Compute the 2d grid dimensions such that the total size of the grid is // divided by divisor. size_t grid_x = 1; diff --git a/mlx/backend/cpu/arg_reduce.cpp b/mlx/backend/cpu/arg_reduce.cpp index d93f74cf0a..57c765bc63 100644 --- a/mlx/backend/cpu/arg_reduce.cpp +++ b/mlx/backend/cpu/arg_reduce.cpp @@ -41,7 +41,7 @@ void arg_reduce_dispatch( switch (rtype) { case ArgReduce::ArgMin: { auto op = [](auto ind_x, auto x, auto ind_y, auto y) { - if (x < (*y)) { + if ((!mlx::core::isnan(*y) && mlx::core::isnan(x)) || x < (*y)) { (*y) = x; (*ind_y) = ind_x; } @@ -51,7 +51,7 @@ void arg_reduce_dispatch( } case ArgReduce::ArgMax: { auto op = [](auto ind_x, auto x, auto ind_y, auto y) { - if (x > (*y)) { + if ((!mlx::core::isnan(*y) && mlx::core::isnan(x)) || x > (*y)) { (*y) = x; (*ind_y) = ind_x; } diff --git a/mlx/backend/cpu/binary.cpp b/mlx/backend/cpu/binary.cpp index 90b0378f6a..150cf58339 100644 --- a/mlx/backend/cpu/binary.cpp +++ b/mlx/backend/cpu/binary.cpp @@ -119,6 +119,13 @@ void Equal::eval_cpu(const std::vector& inputs, array& out) { } } +void FloorDivide::eval_cpu(const std::vector& inputs, array& out) { + assert(inputs.size() == 2); + auto& a = inputs[0]; + auto& b = inputs[1]; + binary_op_cpu(a, b, out, detail::FloorDivide(), stream()); +} + void Greater::eval_cpu(const std::vector& inputs, array& out) { assert(inputs.size() == 2); comparison_op_cpu(inputs[0], inputs[1], out, detail::Greater(), stream()); diff --git a/mlx/backend/cpu/binary.h b/mlx/backend/cpu/binary.h index 5333aff9a1..2eb4afc95b 100644 --- a/mlx/backend/cpu/binary.h +++ b/mlx/backend/cpu/binary.h @@ -16,7 +16,7 @@ namespace mlx::core { template struct VectorScalar { template - void operator()(const T* a, const T* b, U* dst, int size) { + void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *b; constexpr int N = simd::max_size; while (size >= N) { @@ -36,7 +36,7 @@ struct VectorScalar { template struct ScalarVector { template - void operator()(const T* a, const T* b, U* dst, int size) { + void operator()(const T* a, const T* b, U* dst, size_t size) { T scalar = *a; constexpr int N = simd::max_size; while (size >= N) { @@ -56,7 +56,7 @@ struct ScalarVector { template struct VectorVector { template - void operator()(const T* a, const T* b, U* dst, int size) { + void operator()(const T* a, const T* b, U* dst, size_t size) { constexpr int N = simd::max_size; while (size >= N) { simd::store(dst, Op{}(simd::load(a), simd::load(b))); @@ -112,7 +112,7 @@ void binary_op_dispatch_dims( const T* b, U* out, int dim, - int size, + size_t size, const Shape& shape, const Strides& a_strides, const Strides& b_strides, @@ -135,7 +135,7 @@ void binary_op_dispatch_dims( ContiguousIterator a_it(shape, a_strides, dim - 3); ContiguousIterator b_it(shape, b_strides, dim - 3); auto stride = out_strides[dim - 4]; - for (int64_t elem = 0; elem < size; elem += stride) { + for (size_t elem = 0; elem < size; elem += stride) { binary_op_dims( a + a_it.loc, b + b_it.loc, @@ -387,6 +387,7 @@ void binary_int_op_cpu( switch (out.dtype()) { case bool_: binary_op(a, b, out, bopt); + break; case uint8: binary_op(a, b, out, bopt); break; diff --git a/mlx/backend/cpu/binary_ops.h b/mlx/backend/cpu/binary_ops.h index aaceb0032b..c613bc505e 100644 --- a/mlx/backend/cpu/binary_ops.h +++ b/mlx/backend/cpu/binary_ops.h @@ -25,6 +25,8 @@ using namespace mlx::core::simd; DEFAULT_BINARY_OP(Add, operator+) DEFAULT_BINARY_OP(ArcTan2, atan2) +DEFAULT_BINARY_OP(Divide, divide) +DEFAULT_BINARY_OP(FloorDivide, floor_divide) DEFAULT_BINARY_OP(Multiply, operator*) DEFAULT_BINARY_OP(Subtract, operator-) DEFAULT_BINARY_OP(LogicalAnd, operator&&) @@ -39,29 +41,6 @@ DEFAULT_BINARY_OP(Maximum, maximum) DEFAULT_BINARY_OP(Minimum, minimum) DEFAULT_BINARY_OP(Power, pow) -struct Divide { - template - Simd operator()(Simd x, Simd y) { - if constexpr (std::is_integral_v && std::is_signed_v) { - // Integer Divide is floor_divide: round down. Divide by 1 where C++ - // does not define x / y: x / 0 gives 0 and min / -1 gives min. - const Simd zero_v(T(0)); - const Simd one_v(T(1)); - auto zero = y == zero_v; - auto wrap = (x == Simd(std::numeric_limits::min())) && - (y == Simd(T(-1))); - Simd d = select(zero || wrap, one_v, y); - Simd q = x / d; - auto mask = (x != q * d) && ((x < 0) != (y < 0)); - q = q - select(mask, one_v, zero_v); - return select(zero, zero_v, q); - } else { - return x / y; - } - } - BINARY_SINGLE() -}; - #define DEFAULT_BOOL_OP(Op, op) \ struct Op { \ template \ diff --git a/mlx/backend/cpu/compiled.cpp b/mlx/backend/cpu/compiled.cpp index f5b516e44b..5ef78cba30 100644 --- a/mlx/backend/cpu/compiled.cpp +++ b/mlx/backend/cpu/compiled.cpp @@ -1,10 +1,12 @@ // Copyright © 2023-2024 Apple Inc. #include +#include #include #include #include #include +#include #include #include @@ -97,11 +99,13 @@ void* compile( kernel_file_name = kernel_name; } - auto output_dir = - std::filesystem::temp_directory_path() / "mlx" / version() / "cpu"; - if (!std::filesystem::exists(output_dir)) { - std::filesystem::create_directories(output_dir); - } + static const std::filesystem::path output_dir = [] { + if (auto dir = std::getenv("MLX_CPU_CACHE_DIR"); dir && *dir) { + return std::filesystem::absolute(dir); + } + return std::filesystem::temp_directory_path() / "mlx" / version() / "cpu"; + }(); + std::filesystem::create_directories(output_dir); #ifdef _WIN32 std::string shared_lib_name = kernel_file_name + ".dll"; @@ -116,9 +120,14 @@ void* compile( } if (!lib_exists) { - // Open source file and write source code to it - std::string source_file_name = kernel_file_name + ".cpp"; - auto source_file_path = (output_dir / source_file_name).string(); + // Build under a unique name, then move the files into place. Other + // processes then never load a partly written library. + auto tmp_name = fmt::format("tmp_{:08x}", std::random_device{}()); + std::string source_file_name = tmp_name + ".cpp"; + std::string tmp_lib_name = + tmp_name + std::filesystem::path(shared_lib_name).extension().string(); + auto source_file_path = output_dir / source_file_name; + auto tmp_lib_path = output_dir / tmp_lib_name; std::ofstream source_file(source_file_path); source_file << source_code; @@ -127,7 +136,7 @@ void* compile( try { JitCompiler::exec( JitCompiler::build_command( - output_dir, source_file_name, shared_lib_name)); + output_dir, source_file_name, tmp_lib_name)); } catch (const std::exception& error) { throw std::runtime_error( fmt::format( @@ -135,6 +144,19 @@ void* compile( kernel_name, error.what())); } + + std::error_code error; + std::filesystem::rename( + source_file_path, output_dir / (kernel_file_name + ".cpp"), error); + std::filesystem::rename(tmp_lib_path, shared_lib_path, error); + if (error) { + // On Windows the rename can fail while another process uses the file. + if (std::filesystem::exists(shared_lib_path, error)) { + std::filesystem::remove(tmp_lib_path, error); + } else { + shared_lib_path = tmp_lib_path.string(); + } + } } // load library diff --git a/mlx/backend/cpu/conv.cpp b/mlx/backend/cpu/conv.cpp index 17bc6cb9ff..16b32e1c6b 100644 --- a/mlx/backend/cpu/conv.cpp +++ b/mlx/backend/cpu/conv.cpp @@ -5,6 +5,7 @@ #include "mlx/backend/cpu/copy.h" #include "mlx/backend/cpu/encoder.h" +#include "mlx/backend/cpu/gemm.h" #include "mlx/backend/cpu/lapack.h" #include "mlx/primitives.h" #include "mlx/utils.h" @@ -299,18 +300,20 @@ void slow_conv_2D( int oH_border_1 = is_idil_one ? ((padding_lo[0] + wt_strides[0] - 1) / wt_strides[0]) : oH; - int oH_border_2 = std::max( - oH_border_1, - (iH + padding_lo[0] - wH * wt_dilation[0]) / wt_strides[0]); + oH_border_1 = std::min(std::max(oH_border_0, oH_border_1), oH); + int oH_border_2 = + (iH + padding_lo[0] - wH * wt_dilation[0]) / wt_strides[0]; + oH_border_2 = std::min(std::max(oH_border_1, oH_border_2), oH); int oH_border_3 = oH; int oW_border_0 = 0; int oW_border_1 = is_idil_one ? ((padding_lo[1] + wt_strides[1] - 1) / wt_strides[1]) : oW; - int oW_border_2 = std::max( - oW_border_1, - (iW + padding_lo[1] - wW * wt_dilation[1]) / wt_strides[1]); + oW_border_1 = std::min(std::max(oW_border_0, oW_border_1), oW); + int oW_border_2 = + (iW + padding_lo[1] - wW * wt_dilation[1]) / wt_strides[1]; + oW_border_2 = std::min(std::max(oW_border_1, oW_border_2), oW); int oW_border_3 = oW; for (int n = 0; n < N; ++n) { @@ -586,27 +589,30 @@ void slow_conv_3D( int oD_border_1 = is_idil_one ? ((padding_lo[0] + wt_strides[0] - 1) / wt_strides[0]) : oD; - int oD_border_2 = std::max( - oD_border_1, - (iD + padding_lo[0] - wD * wt_dilation[0]) / wt_strides[0]); + oD_border_1 = std::min(std::max(oD_border_0, oD_border_1), oD); + int oD_border_2 = + (iD + padding_lo[0] - wD * wt_dilation[0]) / wt_strides[0]; + oD_border_2 = std::min(std::max(oD_border_1, oD_border_2), oD); int oD_border_3 = oD; int oH_border_0 = 0; int oH_border_1 = is_idil_one ? ((padding_lo[1] + wt_strides[1] - 1) / wt_strides[1]) : oH; - int oH_border_2 = std::max( - oH_border_1, - (iH + padding_lo[1] - wH * wt_dilation[1]) / wt_strides[1]); + oH_border_1 = std::min(std::max(oH_border_0, oH_border_1), oH); + int oH_border_2 = + (iH + padding_lo[1] - wH * wt_dilation[1]) / wt_strides[1]; + oH_border_2 = std::min(std::max(oH_border_1, oH_border_2), oH); int oH_border_3 = oH; int oW_border_0 = 0; int oW_border_1 = is_idil_one ? ((padding_lo[2] + wt_strides[2] - 1) / wt_strides[2]) : oW; - int oW_border_2 = std::max( - oW_border_1, - (iW + padding_lo[2] - wW * wt_dilation[2]) / wt_strides[2]); + oW_border_1 = std::min(std::max(oW_border_0, oW_border_1), oW); + int oW_border_2 = + (iW + padding_lo[2] - wW * wt_dilation[2]) / wt_strides[2]; + oW_border_2 = std::min(std::max(oW_border_1, oW_border_2), oW); int oW_border_3 = oW; for (int n = 0; n < N; ++n) { @@ -911,6 +917,8 @@ void explicit_gemm_conv_1D_cpu( C_per_group]() { for (int g = 0; g < groups; ++g) { // Perform gemm + clear_gemm_output( + gemm_out_ptr + g * O_per_group, strided_reshape, O_per_group, O); cblas_sgemm( CblasRowMajor, CblasNoTrans, // no trans A @@ -1081,6 +1089,7 @@ void explicit_gemm_conv_ND_cpu( strided_reshape = std::move(strided_reshape), O]() { // Perform gemm + clear_gemm_output(gemm_out_ptr, strided_reshape[0], O, O); cblas_sgemm( CblasRowMajor, CblasNoTrans, // no trans A diff --git a/mlx/backend/cpu/copy.cpp b/mlx/backend/cpu/copy.cpp index 381719eb0c..ffe290ffa8 100644 --- a/mlx/backend/cpu/copy.cpp +++ b/mlx/backend/cpu/copy.cpp @@ -27,7 +27,13 @@ void copy_vector(const array& src, array& dst) { auto src_ptr = src.data(); auto dst_ptr = dst.data(); auto size = src.data_size(); - std::copy(src_ptr, src_ptr + size, dst_ptr); + if constexpr (std::is_same_v) { + std::copy(src_ptr, src_ptr + size, dst_ptr); + } else { + std::transform(src_ptr, src_ptr + size, dst_ptr, [](SrcT x) { + return static_cast(x); + }); + } } template diff --git a/mlx/backend/cpu/distributed.cpp b/mlx/backend/cpu/distributed.cpp index 6b788cde25..88ec269fe4 100644 --- a/mlx/backend/cpu/distributed.cpp +++ b/mlx/backend/cpu/distributed.cpp @@ -98,7 +98,7 @@ void Recv::eval_cpu( void ReduceScatter::eval_cpu( const std::vector& inputs, std::vector& outputs) { - assert(inputs.size() == 0); + assert(inputs.size() == 1); assert(outputs.size() == 1); auto [in, copied] = ensure_row_contiguous(inputs[0], stream()); diff --git a/mlx/backend/cpu/eig.cpp b/mlx/backend/cpu/eig.cpp index 7bf674cfda..109d7dfd0c 100644 --- a/mlx/backend/cpu/eig.cpp +++ b/mlx/backend/cpu/eig.cpp @@ -63,12 +63,12 @@ struct EigWork< } void run(T* a, O* values, O* vectors) { - auto eig_tmp = static_cast(buffers[0].buffer.raw_ptr()); + auto eig_tmp = static_cast(buffers[0].buffer().raw_ptr()); T* vec_tmp = nullptr; if (vectors) { - vec_tmp = static_cast(buffers[1].buffer.raw_ptr()); + vec_tmp = static_cast(buffers[1].buffer().raw_ptr()); } - auto work = static_cast(buffers.back().buffer.raw_ptr()); + auto work = static_cast(buffers.back().buffer().raw_ptr()); int n_vecs_l = vectors ? N : 1; int n_vecs_r = 1; @@ -166,9 +166,9 @@ struct EigWork> { &n_vecs_l, nullptr, &n_vecs_r, - static_cast(buffers[0].buffer.raw_ptr()), + static_cast(buffers[0].buffer().raw_ptr()), &lwork, - static_cast(buffers[1].buffer.raw_ptr()), + static_cast(buffers[1].buffer().raw_ptr()), &info); } }; diff --git a/mlx/backend/cpu/eigh.cpp b/mlx/backend/cpu/eigh.cpp index ff5a4805a3..41d94205d0 100644 --- a/mlx/backend/cpu/eigh.cpp +++ b/mlx/backend/cpu/eigh.cpp @@ -59,9 +59,9 @@ struct EighWork< vectors, &N, values, - static_cast(buffers[0].buffer.raw_ptr()), + static_cast(buffers[0].buffer().raw_ptr()), &lwork, - static_cast(buffers[1].buffer.raw_ptr()), + static_cast(buffers[1].buffer().raw_ptr()), &liwork, &info); } @@ -116,11 +116,11 @@ struct EighWork> { vectors, &N, values, - static_cast(buffers[0].buffer.raw_ptr()), + static_cast(buffers[0].buffer().raw_ptr()), &lwork, - static_cast(buffers[1].buffer.raw_ptr()), + static_cast(buffers[1].buffer().raw_ptr()), &lrwork, - static_cast(buffers[2].buffer.raw_ptr()), + static_cast(buffers[2].buffer().raw_ptr()), &liwork, &info); if (jobz == 'V') { diff --git a/mlx/backend/cpu/encoder.cpp b/mlx/backend/cpu/encoder.cpp index bb2c06ea0a..0b4654b22f 100644 --- a/mlx/backend/cpu/encoder.cpp +++ b/mlx/backend/cpu/encoder.cpp @@ -22,8 +22,13 @@ CommandEncoder& get_command_encoder(Stream s) { } std::unordered_map& get_command_encoders() { - static thread_local std::unordered_map encoders; - return encoders; + if (is_main_thread()) { + static auto* encoders = new std::unordered_map(); + return *encoders; + } else { + static thread_local std::unordered_map encoders; + return encoders; + } } std::unordered_map& get_global_command_encoders() { diff --git a/mlx/backend/cpu/gemm.h b/mlx/backend/cpu/gemm.h index d665cb91ff..b8689a41ab 100644 --- a/mlx/backend/cpu/gemm.h +++ b/mlx/backend/cpu/gemm.h @@ -1,10 +1,22 @@ // Copyright © 2025 Apple Inc. #pragma once +#include + #include "mlx/array.h" namespace mlx::core { +// A BLAS gemm with beta = 0 must not read C, but Accelerate can (seen with +// M = 1). A buffer from the allocator cache can hold NaN, and NaN * 0 is NaN. +// Call this on the C region of every BLAS gemm with beta = 0. +template +inline void clear_gemm_output(T* c, size_t rows, size_t cols, size_t ldc) { + for (size_t r = 0; r < rows; ++r) { + std::fill_n(c + r * ldc, cols, T(0)); + } +} + template void matmul( const T* a, diff --git a/mlx/backend/cpu/gemms/cblas.cpp b/mlx/backend/cpu/gemms/cblas.cpp index 765e9f539a..f12542fbed 100644 --- a/mlx/backend/cpu/gemms/cblas.cpp +++ b/mlx/backend/cpu/gemms/cblas.cpp @@ -29,6 +29,9 @@ void matmul( size_t K = a_shape[ndim - 1]; for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -70,6 +73,9 @@ void matmul( size_t K = a_shape[ndim - 1]; for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_dgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -113,6 +119,9 @@ void matmul( auto cbeta = static_cast(beta); for (int i = 0; i < batch_size; ++i) { + if (beta == 0.0f) { + clear_gemm_output(out + M * N * i, M, N, ldc); + } cblas_cgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA diff --git a/mlx/backend/cpu/inverse.cpp b/mlx/backend/cpu/inverse.cpp index ddc979daa6..a02c48b149 100644 --- a/mlx/backend/cpu/inverse.cpp +++ b/mlx/backend/cpu/inverse.cpp @@ -11,14 +11,14 @@ namespace mlx::core { template void general_inv(T* inv, int N) { int info; - auto ipiv = array::Data{allocator::malloc(sizeof(int) * N)}; + auto ipiv = allocator::malloc(sizeof(int) * N); // Compute LU factorization. getrf( /* m = */ &N, /* n = */ &N, /* a = */ inv, /* lda = */ &N, - /* ipiv = */ static_cast(ipiv.buffer.raw_ptr()), + /* ipiv = */ static_cast(ipiv.buffer().raw_ptr()), /* info = */ &info); if (info != 0) { @@ -49,15 +49,15 @@ void general_inv(T* inv, int N) { } const int lwork = workspace_size; - auto scratch = array::Data{allocator::malloc(sizeof(T) * lwork)}; + auto scratch = allocator::malloc(sizeof(T) * lwork); // Compute inverse. getri( /* m = */ &N, /* a = */ inv, /* lda = */ &N, - /* ipiv = */ static_cast(ipiv.buffer.raw_ptr()), - /* work = */ static_cast(scratch.buffer.raw_ptr()), + /* ipiv = */ static_cast(ipiv.buffer().raw_ptr()), + /* work = */ static_cast(scratch.buffer().raw_ptr()), /* lwork = */ &lwork, /* info = */ &info); diff --git a/mlx/backend/cpu/masked_mm.cpp b/mlx/backend/cpu/masked_mm.cpp index db38f39424..89f3bd7214 100644 --- a/mlx/backend/cpu/masked_mm.cpp +++ b/mlx/backend/cpu/masked_mm.cpp @@ -325,6 +325,7 @@ void BlockMaskedMM::eval_cpu(const std::vector& inputs, array& out) { } // Do matmul + clear_gemm_output(ci, M, N, ldc); cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA @@ -469,6 +470,7 @@ void GatherMM::eval_cpu(const std::vector& inputs, array& out) { uint32_t indx_B = rhs_indices_ptr[elem_to_loc( i, rhs_indices_shape, rhs_indices_strides)]; + clear_gemm_output(out_ptr + matrix_stride_out * i, M, N, ldc); cblas_sgemm( CblasRowMajor, a_transposed ? CblasTrans : CblasNoTrans, // transA diff --git a/mlx/backend/cpu/primitives.cpp b/mlx/backend/cpu/primitives.cpp index 3299b74717..1633e0a647 100644 --- a/mlx/backend/cpu/primitives.cpp +++ b/mlx/backend/cpu/primitives.cpp @@ -35,6 +35,14 @@ static std::pair compute_dynamic_offset( const Strides& strides, const std::vector& axes, Stream stream) { + auto& encoder = cpu::get_command_encoder(stream); + // The kernel reads the indices contiguously + if (!indices.flags().row_contiguous) { + auto copy = contiguous_copy_cpu(indices, stream); + encoder.add_temporary(copy); + return compute_dynamic_offset(copy, strides, axes, stream); + } + array offset({1}, int64, nullptr, {}); bool donate = indices.is_donatable() && (indices.data_size() * indices.itemsize()) >= offset.itemsize(); @@ -44,7 +52,6 @@ static std::pair compute_dynamic_offset( offset.set_data(allocator::malloc(offset.itemsize())); } - auto& encoder = cpu::get_command_encoder(stream); encoder.set_input_array(indices); encoder.set_output_array(offset); auto compute_offset = @@ -79,7 +86,14 @@ static std::pair compute_dynamic_offset( } void AsStrided::eval_cpu(const std::vector& inputs, array& out) { - eval(inputs, out); + assert(inputs.size() == 1); + if (inputs[0].flags().row_contiguous) { + eval(inputs[0], out); + } else { + auto copy = contiguous_copy_cpu(inputs[0], stream()); + cpu::get_command_encoder(stream()).add_temporary(copy); + eval(copy, out); + } } void Broadcast::eval_cpu(const std::vector& inputs, array& out) { eval(inputs, out); @@ -380,8 +394,20 @@ void View::eval_cpu(const std::vector& inputs, array& out) { strides[i] *= ibytes; strides[i] /= obytes; } + // Last axis can have any stride + if (obytes < ibytes) { + strides.back() = 1; + } + auto flags = in.flags(); + if (ibytes != obytes) { + // Last axis size can change contiguity + auto [_, row_contiguous, col_contiguous] = + check_contiguity(out.shape(), strides); + flags.row_contiguous = row_contiguous; + flags.col_contiguous = col_contiguous; + } out.copy_shared_buffer( - in, strides, in.flags(), in.data_size() * ibytes / obytes); + in, strides, flags, in.data_size() * ibytes / obytes); } else { auto tmp = array( in.shape(), in.dtype() == bool_ ? uint8 : in.dtype(), nullptr, {}); diff --git a/mlx/backend/cpu/qrf.cpp b/mlx/backend/cpu/qrf.cpp index f438d492ae..358544aa8d 100644 --- a/mlx/backend/cpu/qrf.cpp +++ b/mlx/backend/cpu/qrf.cpp @@ -69,12 +69,11 @@ void qrf_impl(const array& a, array& q, array& r, Stream stream) { &N, in_ptr + M * N * i, &lda, - static_cast(tau.raw_ptr()) + num_reflectors * i, - static_cast(work.raw_ptr()), + static_cast(tau.buffer().raw_ptr()) + num_reflectors * i, + static_cast(work.buffer().raw_ptr()), &lwork, &info); } - allocator::free(work); for (int i = 0; i < num_matrices; ++i) { /// num_reflectors x N @@ -102,7 +101,7 @@ void qrf_impl(const array& a, array& q, array& r, Stream stream) { &lwork, &info); lwork = optimal_work; - work = allocator::malloc(sizeof(T) * lwork); + auto orgqr_work = allocator::malloc(sizeof(T) * lwork); // Loop over matrices for (int i = 0; i < num_matrices; ++i) { @@ -113,8 +112,8 @@ void qrf_impl(const array& a, array& q, array& r, Stream stream) { &num_reflectors, in_ptr + M * N * i, &lda, - static_cast(tau.raw_ptr()) + num_reflectors * i, - static_cast(work.raw_ptr()), + static_cast(tau.buffer().raw_ptr()) + num_reflectors * i, + static_cast(orgqr_work.buffer().raw_ptr()), &lwork, &info); } @@ -128,10 +127,6 @@ void qrf_impl(const array& a, array& q, array& r, Stream stream) { } } } - - // Cleanup - allocator::free(work); - allocator::free(tau); }); encoder.add_temporary(in); } diff --git a/mlx/backend/cpu/quantized.cpp b/mlx/backend/cpu/quantized.cpp index 30b11c87d6..3f03608c85 100644 --- a/mlx/backend/cpu/quantized.cpp +++ b/mlx/backend/cpu/quantized.cpp @@ -353,6 +353,10 @@ void _qmm_dispatch_typed( int bits, bool transposed_w) { switch (bits) { + case 1: + _qmm_dispatch_group( + result, x, w, scales, biases, M, N, K, group_size, transposed_w); + break; case 2: _qmm_dispatch_group( result, x, w, scales, biases, M, N, K, group_size, transposed_w); @@ -378,7 +382,8 @@ void _qmm_dispatch_typed( result, x, w, scales, biases, M, N, K, group_size, transposed_w); break; default: - throw std::invalid_argument("Quantization bits must be 2, 3, 4, 6 or 8."); + throw std::invalid_argument( + "Quantization bits must be 1, 2, 3, 4, 5, 6 or 8."); } } @@ -1185,15 +1190,24 @@ void quantize( w_min = std::min(w_min, (float)w[w_idx + j]); } bool mask = std::abs(w_min) > std::abs(w_max); - float scale = std::max((w_max - w_min) / n_bins, eps); - scale = mask ? scale : -scale; - - float edge = mask ? w_min : w_max; - float q0 = std::rint(edge / scale); - float bias = 0; - if (q0 != 0) { - scale = edge / q0; - bias = edge; + float scale; + float bias; + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scale = std::max(w_max - w_min, eps); + bias = w_min; + } else { + scale = std::max((w_max - w_min) / n_bins, eps); + scale = mask ? scale : -scale; + + float edge = mask ? w_min : w_max; + float q0 = std::rint(edge / scale); + bias = 0; + if (q0 != 0) { + scale = edge / q0; + bias = edge; + } } size_t out_idx = i * int_per_group; for (int j = 0; j < int_per_group / bytes_per_pack; ++j) { diff --git a/mlx/backend/cpu/reduce.cpp b/mlx/backend/cpu/reduce.cpp index 64b3fab339..cd4911e898 100644 --- a/mlx/backend/cpu/reduce.cpp +++ b/mlx/backend/cpu/reduce.cpp @@ -68,6 +68,18 @@ const complex64_t Limits::max = const complex64_t Limits::min = -std::numeric_limits::infinity(); +template +struct ReductionAccumulator { + static constexpr int N = std::min(simd::max_size, simd::max_size); + // Widen to float32 only if the input is float16 (with N=1) or bfloat16 as it + // improves performance. + static constexpr bool widen_to_float = + (std::is_same_v || + (N == 1 && std::is_same_v)); + + using type = std::conditional_t; +}; + template void strided_reduce( const T* x, @@ -96,7 +108,12 @@ void strided_reduce( }; template -void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) { +void contiguous_reduce( + const T* x, + U* accumulator, + int64_t size, + Op op, + U init) { constexpr int N = std::min(simd::max_size, simd::max_size); simd::Simd accumulator_v(init); while (size >= N) { @@ -113,11 +130,11 @@ void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) { // Helper for the ndimensional strided loop void nd_loop( - std::function callback, + std::function callback, const Shape& shape, const Strides& strides) { - std::function loop_inner; - loop_inner = [&](int dim, int offset) { + std::function loop_inner; + loop_inner = [&](int dim, int64_t offset) { if (dim < shape.size() - 1) { auto size = shape[dim]; auto stride = strides[dim]; @@ -169,16 +186,16 @@ void reduction_op( auto [shape, strides] = shapes_without_reduction_axes(x, axes); if (plan.shape.size() == 0) { for (int i = 0; i < out.size(); i++, out_ptr++) { - int offset = elem_to_loc(i, shape, strides); + int64_t offset = elem_to_loc(i, shape, strides); *out_ptr = init; contiguous_reduce(in_ptr + offset, out_ptr, reduction_size, Op{}, init); } } else { for (int i = 0; i < out.size(); i++, out_ptr++) { - int offset = elem_to_loc(i, shape, strides); + int64_t offset = elem_to_loc(i, shape, strides); *out_ptr = init; nd_loop( - [&](int extra_offset) { + [&](int64_t extra_offset) { contiguous_reduce( in_ptr + offset + extra_offset, out_ptr, @@ -217,7 +234,7 @@ void reduction_op( if (plan.shape.size() == 0) { for (int i = 0; i < out.size(); i += reduction_stride) { - int offset = elem_to_loc(i, shape, strides); + int64_t offset = elem_to_loc(i, shape, strides); std::fill_n(out_ptr, reduction_stride, init); strided_reduce( in_ptr + offset, out_ptr, reduction_size, reduction_stride, Op{}); @@ -225,10 +242,10 @@ void reduction_op( } } else { for (int i = 0; i < out.size(); i += reduction_stride) { - int offset = elem_to_loc(i, shape, strides); + int64_t offset = elem_to_loc(i, shape, strides); std::fill_n(out_ptr, reduction_stride, init); nd_loop( - [&](int extra_offset) { + [&](int64_t extra_offset) { strided_reduce( in_ptr + offset + extra_offset, out_ptr, @@ -248,10 +265,10 @@ void reduction_op( auto [shape, strides] = shapes_without_reduction_axes(x, axes); for (int i = 0; i < out.size(); i++, out_ptr++) { - int offset = elem_to_loc(i, shape, strides); + int64_t offset = elem_to_loc(i, shape, strides); U val = init; nd_loop( - [&](int extra_offset) { + [&](int64_t extra_offset) { val = Op{}(val, *(in_ptr + offset + extra_offset)); }, plan.shape, @@ -261,10 +278,27 @@ void reduction_op( } } +template +void float_reduction( + const array& x, + array& out, + const std::vector& axes, + U init) { + using AccT = ReductionAccumulator::type; + if constexpr (std::is_same_v) { + reduction_op(x, out, axes, init); + } else { + array temp(out.shape(), TypeToDtype(), nullptr, {}); + temp.set_data(allocator::malloc(temp.nbytes())); + reduction_op(x, temp, axes, static_cast(init)); + std::copy_n(temp.data(), out.size(), out.data()); + } +} + struct AndReduce { template bool operator()(bool x, T y) { - return x & (y != 0); + return x & static_cast(y); } bool operator()(bool x, bool y) { @@ -290,7 +324,7 @@ struct AndReduce { struct OrReduce { template bool operator()(bool x, T y) { - return x | (y != 0); + return x | static_cast(y); } bool operator()(bool x, bool y) { @@ -420,13 +454,13 @@ void reduce_dispatch_sum_prod( if constexpr (std::is_integral_v && sizeof(InT) <= 4) { reduction_op(in, out, axes, 0); } else { - reduction_op(in, out, axes, 0); + float_reduction(in, out, axes, 0); } } else { if constexpr (std::is_integral_v && sizeof(InT) <= 4) { reduction_op(in, out, axes, 1); } else { - reduction_op(in, out, axes, 1); + float_reduction(in, out, axes, 1); } } } @@ -488,12 +522,11 @@ void Reduce::eval_cpu(const std::vector& inputs, array& out) { break; case uint64: case int64: - // complex64 stays on the integer path. Testing it as a complex - // would go through complex64_t's conversion to float and only look - // at the real part, which would miss 1j. - case complex64: reduce_dispatch_and_or(in, out, reduce_type_, axes_); break; + case complex64: + reduce_dispatch_and_or(in, out, reduce_type_, axes_); + break; case float64: reduce_dispatch_and_or(in, out, reduce_type_, axes_); break; diff --git a/mlx/backend/cpu/scan.cpp b/mlx/backend/cpu/scan.cpp index ab2ca14366..6632e44e7a 100644 --- a/mlx/backend/cpu/scan.cpp +++ b/mlx/backend/cpu/scan.cpp @@ -269,6 +269,11 @@ void scan_dispatch( void Scan::eval_cpu(const std::vector& inputs, array& out) { assert(inputs.size() == 1); + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + auto& encoder = cpu::get_command_encoder(stream()); // Ensure contiguity @@ -278,6 +283,9 @@ void Scan::eval_cpu(const std::vector& inputs, array& out) { encoder.add_temporary(in); } out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } encoder.set_input_array(in); encoder.set_output_array(out); diff --git a/mlx/backend/cpu/simd/accelerate_simd.h b/mlx/backend/cpu/simd/accelerate_simd.h index e11cc7f5f9..b3cea20b22 100644 --- a/mlx/backend/cpu/simd/accelerate_simd.h +++ b/mlx/backend/cpu/simd/accelerate_simd.h @@ -233,6 +233,45 @@ Simd minimum(Simd a, Simd b) { return out; } +// Integer division by zero gives 0. See the scalar divide in base_simd.h. +template +Simd divide(Simd a, Simd b) { + if constexpr (std::is_integral_v) { + return select(b == Simd(0), Simd(0), Simd(a / b)); + } else { + return a / b; + } +} + +// Signed types round the quotient towards minus infinity. +template +Simd floor_divide(Simd a, Simd b) { + if constexpr (std::is_integral_v) { + // Swap zero divisors for 1 before dividing so the quotient is defined. + // For signed types also swap -1 where a is min: min / -1 overflows, and + // min / 1 gives min, the wrapped result. + auto zero = b == Simd(0); + auto use_one = zero; + if constexpr (is_signed_v) { + use_one = use_one || + (a == Simd(std::numeric_limits::min()) && + b == Simd(-1)); + } + auto q = a / select(use_one, Simd(1), b); + q = select(zero, Simd(0), q); + if constexpr (is_signed_v) { + // a - b * q is the remainder and needs no division by zero. + auto mask = b != 0 && (a - b * q) != 0 && (a < 0 != b < 0); + q = select(mask, q - Simd(1), q); + } + return q; + } else if constexpr (is_complex) { + return a / b; + } else { + return floor(divide(a, b)); + } +} + template Simd remainder(Simd a, Simd b) { Simd r; @@ -268,15 +307,17 @@ Simd pow(Simd base, Simd exp) { return asd::pow(base.value, exp.value); } else { Simd res = 1; - // Raising an integer to a negative power is undefined - if (any(exp < 0)) { - return 0; - } while (any(exp > 0)) { res = select((exp & 1) != 0, res * base, res); base = select(exp > 0, base * base, base); exp = exp >> 1; } + if constexpr (std::is_signed_v) { + // Raising an integer to a negative power is undefined, so return 0 for + // those lanes. Select per lane: a single negative exponent must not zero + // the whole vector. exp stays negative through the shifts above. + res = select(exp < 0, Simd(0), res); + } return res; } } diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index 1ae883f7e5..483eff69e8 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -8,11 +8,13 @@ #include #include #include +#include #ifdef _MSC_VER #include // For _BitScanReverse #endif +#include "mlx/types/complex.h" #include "mlx/types/half_types.h" namespace mlx::core::simd { @@ -159,7 +161,7 @@ auto imag(Simd in) -> Simd { } template Simd isnan(Simd in) { - return std::isnan(in.value); + return mlx::core::isnan(in.value); } #define DEFAULT_BINARY(OP) \ @@ -203,12 +205,58 @@ Simd clz(Simd x_) { #endif } +// Integer division by zero traps on x86 and returns 0 on arm64. Define the +// quotient as 0 on all platforms, which keeps a == (a / b) * b + (a % b). +template +Simd divide(Simd a_, Simd b_) { + T a = a_.value; + T b = b_.value; + if constexpr (std::is_integral_v) { + if (b == 0) { + return T(0); + } + } + return a / b; +} + +template +Simd floor_divide(Simd a_, Simd b_) { + T a = a_.value; + T b = b_.value; + if constexpr (std::is_integral_v) { + // Integer division by zero gives 0. See divide above. + if (b == 0) { + return T(0); + } + if constexpr (is_signed_v) { + // min / -1 overflows and traps on x86. The result wraps to min. + if (b == T(-1)) { + return a == std::numeric_limits::min() ? a : T(-a); + } + } + T q = a / b; + if constexpr (is_signed_v) { + if (a % b != 0 && (a < 0 != b < 0)) { + q -= 1; + } + } + return q; + } else if constexpr (is_complex) { + return a / b; + } else { + return floor(divide(a_, b_)); + } +} + template Simd remainder(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; T r; if constexpr (std::is_integral_v) { + if (b == 0) { + return a; + } r = a % b; } else { r = std::remainder(a, b); @@ -226,7 +274,7 @@ Simd maximum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { - if (std::isnan(a)) { + if (mlx::core::isnan(a)) { return a; } } @@ -238,7 +286,7 @@ Simd minimum(Simd a_, Simd b_) { T a = a_.value; T b = b_.value; if constexpr (!std::is_integral_v) { - if (std::isnan(a)) { + if (mlx::core::isnan(a)) { return a; } } diff --git a/mlx/backend/cpu/simd/neon_fp16_simd.h b/mlx/backend/cpu/simd/neon_fp16_simd.h index 5d32042cc9..ad258296e8 100644 --- a/mlx/backend/cpu/simd/neon_fp16_simd.h +++ b/mlx/backend/cpu/simd/neon_fp16_simd.h @@ -80,7 +80,7 @@ DEFINE_NEON_UNARY_OP(rint, vrndnq_f16) inline Simd operator!(Simd v) { auto out = vceqzq_f16(v.value); - return Simd(*(uint16_t*)&out); + return load(reinterpret_cast(&out)); } inline Simd operator-(Simd v) { @@ -94,21 +94,21 @@ DEFINE_NEON_BINARY_OP(operator-, vsubq_f16) DEFINE_NEON_BINARY_OP(operator*, vmulq_f16) DEFINE_NEON_BINARY_OP(operator/, vdivq_f16) -#define DEFINE_NEON_COMPARISON(Op, op) \ - template \ - Simd operator Op(Simd a, T b) { \ - auto out = op(a.value, Simd(b).value); \ - return Simd(*(uint16_t*)(&out)); \ - } \ - template \ - Simd operator Op(T a, Simd b) { \ - auto out = op(Simd(a).value, b.value); \ - return Simd(*(uint16_t*)(&out)); \ - } \ - inline Simd operator Op( \ - Simd a, Simd b) { \ - auto out = op(a.value, b.value); \ - return Simd(*(uint16_t*)(&out)); \ +#define DEFINE_NEON_COMPARISON(Op, op) \ + template \ + Simd operator Op(Simd a, T b) { \ + auto out = op(a.value, Simd(b).value); \ + return load(reinterpret_cast(&out)); \ + } \ + template \ + Simd operator Op(T a, Simd b) { \ + auto out = op(Simd(a).value, b.value); \ + return load(reinterpret_cast(&out)); \ + } \ + inline Simd operator Op( \ + Simd a, Simd b) { \ + auto out = op(a.value, b.value); \ + return load(reinterpret_cast(&out)); \ } DEFINE_NEON_COMPARISON(==, vceqq_f16) diff --git a/mlx/backend/cpu/sort.cpp b/mlx/backend/cpu/sort.cpp index 767e7ef1d3..92378981b6 100644 --- a/mlx/backend/cpu/sort.cpp +++ b/mlx/backend/cpu/sort.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include "mlx/backend/common/utils.h" @@ -19,9 +18,9 @@ namespace { template bool nan_aware_less(T a, T b) { if constexpr (is_floating_point_v || std::is_same_v) { - if (std::isnan(a)) + if (mlx::core::isnan(a)) return false; - if (std::isnan(b)) + if (mlx::core::isnan(b)) return true; } return a < b; @@ -118,6 +117,10 @@ struct StridedIterator { template void sort(array& out, int axis) { + if (out.size() == 0) { + return; + } + // Get axis, shape and stride info axis = axis < 0 ? axis + out.ndim() : axis; size_t in_size = out.size(); @@ -149,6 +152,10 @@ void sort(array& out, int axis) { template void argsort(const array& in, array& out, int axis) { + if (in.size() == 0) { + return; + } + // Get axis, shape and stride info axis = axis < 0 ? axis + in.ndim() : axis; size_t n_rows = in.size() / in.shape(axis); @@ -198,10 +205,10 @@ void argsort(const array& in, array& out, int axis) { auto v2 = data_ptr[b * in_stride]; // Handle NaNs (place them at the end) - if constexpr (is_floating_point_v) { - if (std::isnan(v1)) + if constexpr (is_floating_point_v || std::is_same_v) { + if (mlx::core::isnan(v1)) return false; - if (std::isnan(v2)) + if (mlx::core::isnan(v2)) return true; } @@ -212,6 +219,10 @@ void argsort(const array& in, array& out, int axis) { template void partition(array& out, int axis, int kth) { + if (out.size() == 0) { + return; + } + // Get axis, shape and stride info axis = axis < 0 ? axis + out.ndim() : axis; size_t in_size = out.size(); @@ -246,6 +257,10 @@ void partition(array& out, int axis, int kth) { template void argpartition(const array& in, array& out, int axis, int kth) { + if (in.size() == 0) { + return; + } + // Get axis, shape and stride info axis = axis < 0 ? axis + in.ndim() : axis; size_t n_rows = in.size() / in.shape(axis); @@ -299,10 +314,10 @@ void argpartition(const array& in, array& out, int axis, int kth) { auto v2 = data_ptr[b * in_stride]; // Handle NaNs (place them at the end) - if constexpr (is_floating_point_v) { - if (std::isnan(v1)) + if constexpr (is_floating_point_v || std::is_same_v) { + if (mlx::core::isnan(v1)) return false; - if (std::isnan(v2)) + if (mlx::core::isnan(v2)) return true; } @@ -357,6 +372,10 @@ void ArgSort::eval_cpu(const std::vector& inputs, array& out) { // Allocate output out.set_data(allocator::malloc(out.nbytes())); + if (out.size() == 0) { + return; + } + auto& encoder = cpu::get_command_encoder(stream()); encoder.set_input_array(in); encoder.set_input_array(out); @@ -384,6 +403,10 @@ void Sort::eval_cpu(const std::vector& inputs, array& out) { : CopyType::General; copy_cpu(in, out, ctype, stream()); + if (out.size() == 0) { + return; + } + auto& encoder = cpu::get_command_encoder(stream()); encoder.set_output_array(out); encoder.dispatch([out = array::unsafe_weak_copy(out), axis]() mutable { diff --git a/mlx/backend/cpu/svd.cpp b/mlx/backend/cpu/svd.cpp index 80101e9072..c4084ed4f0 100644 --- a/mlx/backend/cpu/svd.cpp +++ b/mlx/backend/cpu/svd.cpp @@ -55,7 +55,7 @@ struct SVDWork< /* ldvt = */ &ldvt, /* work = */ &workspace_dimension, /* lwork = */ &lwork_query, - /* iwork = */ static_cast(buffers[0].buffer.raw_ptr()), + /* iwork = */ static_cast(buffers[0].buffer().raw_ptr()), /* info = */ &info); if (info != 0) { @@ -84,9 +84,9 @@ struct SVDWork< // According to the identity above, lapack will write Uᵀ as Vᵀ. /* vt = */ vt, /* ldvt = */ &ldvt, - /* work = */ static_cast(buffers[1].buffer.raw_ptr()), + /* work = */ static_cast(buffers[1].buffer().raw_ptr()), /* lwork = */ &lwork, - /* iwork = */ static_cast(buffers[0].buffer.raw_ptr()), + /* iwork = */ static_cast(buffers[0].buffer().raw_ptr()), /* info = */ &info); if (info != 0) { @@ -143,8 +143,8 @@ struct SVDWork> { /* ldvt = */ &ldvt, /* work = */ &workspace_dimension, /* lwork = */ &lwork_query, - /* rwork = */ static_cast(buffers[1].buffer.raw_ptr()), - /* iwork = */ static_cast(buffers[0].buffer.raw_ptr()), + /* rwork = */ static_cast(buffers[1].buffer().raw_ptr()), + /* iwork = */ static_cast(buffers[0].buffer().raw_ptr()), /* info = */ &info); if (info != 0) { @@ -173,10 +173,10 @@ struct SVDWork> { // According to the identity above, lapack will write Uᵀ as Vᵀ. /* vt = */ vt, /* ldvt = */ &ldvt, - /* work = */ static_cast(buffers[2].buffer.raw_ptr()), + /* work = */ static_cast(buffers[2].buffer().raw_ptr()), /* lwork = */ &lwork, - /* rwork = */ static_cast(buffers[1].buffer.raw_ptr()), - /* iwork = */ static_cast(buffers[0].buffer.raw_ptr()), + /* rwork = */ static_cast(buffers[1].buffer().raw_ptr()), + /* iwork = */ static_cast(buffers[0].buffer().raw_ptr()), /* info = */ &info); if (info != 0) { diff --git a/mlx/backend/cpu/unary_ops.h b/mlx/backend/cpu/unary_ops.h index f441e88bd5..e2dd7413f7 100644 --- a/mlx/backend/cpu/unary_ops.h +++ b/mlx/backend/cpu/unary_ops.h @@ -154,19 +154,20 @@ struct ToFP8 { struct FromFP8 { template Simd operator()(Simd x) { - auto v = Simd(x & 127) << 7; + auto v = Simd(x & 127); + auto sign_bit = Simd((x >> 7) & 1) << 15; + auto u = (v << 7) | (((v + 1) >> 7) << 14) | sign_bit; Simd out; if constexpr (simd::max_size >= N) { - auto converted = *(Simd*)(&v); + auto converted = *(Simd*)(&u); out = converted * 256.0; } else { for (int i = 0; i < N; ++i) { - auto converted = *(float16_t*)(&v[i]); + auto converted = *(float16_t*)(&u[i]); out[i] = converted * 256.0; } } - auto sign = Simd(x & 128); - return select(sign, -out, out); + return out; } float operator()(uint8_t x) { return (*this)(Simd(x)).value; diff --git a/mlx/backend/cuda/CMakeLists.txt b/mlx/backend/cuda/CMakeLists.txt index 9c8d3174c1..50be6f404f 100644 --- a/mlx/backend/cuda/CMakeLists.txt +++ b/mlx/backend/cuda/CMakeLists.txt @@ -9,6 +9,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/arange.cu ${CMAKE_CURRENT_SOURCE_DIR}/arg_reduce.cu ${CMAKE_CURRENT_SOURCE_DIR}/binary_two.cu + ${CMAKE_CURRENT_SOURCE_DIR}/cholesky.cu ${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp ${CMAKE_CURRENT_SOURCE_DIR}/copy.cu ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_contiguous.cu @@ -21,6 +22,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/cublas_utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cross_entropy.cu ${CMAKE_CURRENT_SOURCE_DIR}/cudnn_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cusolver_utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/device_info.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom_kernel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/device.cpp @@ -77,6 +79,10 @@ target_sources( add_library(mlx_dirs OBJECT ${CMAKE_CURRENT_SOURCE_DIR}/dirs.cpp) target_include_directories(mlx_dirs PRIVATE "${PROJECT_SOURCE_DIR}") target_link_libraries(mlx PRIVATE $) +# TODO: Remove after removing std::atomic_store/load. +target_compile_definitions( + mlx_dirs + PUBLIC _SILENCE_CXX20_OLD_SHARED_PTR_ATOMIC_SUPPORT_DEPRECATION_WARNING) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/binary) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/unary) @@ -181,6 +187,8 @@ set_target_properties(mlx PROPERTIES CUDA_ARCHITECTURES # Configure Windows CUDA DLL loading. if(WIN32) + target_sources(mlx PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/wddm.cpp) + target_link_libraries(mlx PRIVATE dxgi) set(MLX_CUDA_BIN_DIR "" CACHE STRING "Directory containing CUDA DLLs for Windows delay-loading") @@ -241,6 +249,7 @@ else() "$ORIGIN/../../nvidia/cuda_nvrtc/lib" "$ORIGIN/../../nvidia/cudnn/lib" "$ORIGIN/../../nvidia/cufft/lib" + "$ORIGIN/../../nvidia/cusolver/lib" "$ORIGIN/../../nvidia/nccl/lib") endif() endif() @@ -286,6 +295,9 @@ target_link_libraries(mlx PRIVATE CUDA::cublasLt) # Use cuFFT. target_link_libraries(mlx PRIVATE CUDA::cufft) +# Use cuSOLVER. +target_link_libraries(mlx PRIVATE CUDA::cusolver) + # Use NVRTC and driver APIs. target_link_libraries(mlx PRIVATE CUDA::nvrtc CUDA::cuda_driver) diff --git a/mlx/backend/cuda/allocator.cpp b/mlx/backend/cuda/allocator.cpp index b29cc3a2b3..2aac8780ec 100644 --- a/mlx/backend/cuda/allocator.cpp +++ b/mlx/backend/cuda/allocator.cpp @@ -1,13 +1,18 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include "mlx/backend/cuda/allocator.h" #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/utils.h" #include "mlx/backend/gpu/device_info.h" +#include "mlx/device.h" #include "mlx/memory.h" #include "mlx/scheduler.h" #include "mlx/utils.h" +#ifdef _WIN32 +#include "mlx/backend/cuda/wddm.h" +#endif + #include #include @@ -77,9 +82,9 @@ inline void* unified_malloc(size_t size) { inline void unified_free(void* data) { if (supports_managed_memory()) { - CHECK_CUDA_ERROR(cudaFree(data)); + cudaFree(data); } else { - CHECK_CUDA_ERROR(cudaFreeHost(data)); + cudaFreeHost(data); } } @@ -193,7 +198,7 @@ CudaAllocator::malloc_async(size_t size, int device, cudaStream_t stream) { if (!buf) { // If we have a lot of memory pressure try to reclaim memory from the cache. int64_t mem_to_free = - get_active_memory() + get_cache_memory() + size - memory_limit_; + get_active_memory() + get_cache_memory() + size - get_memory_limit(); if (mem_to_free > 0) { buffer_cache_.release_cached_buffers(mem_to_free); } @@ -326,9 +331,9 @@ void CudaAllocator::free_async(CudaBuffer& buf, cudaStream_t stream) { if (!stream) { stream = free_streams_[buf.device]; } - CHECK_CUDA_ERROR(cudaFreeAsync(buf.data, stream)); + cudaFreeAsync(buf.data, stream); } else { - CHECK_CUDA_ERROR(cudaFree(buf.data)); + cudaFree(buf.data); } } } @@ -352,7 +357,13 @@ MemorySnapshot CudaAllocator::get_memory_snapshot() { } size_t CudaAllocator::get_memory_limit() { +#ifdef _WIN32 + int device = default_device().index; + return std::min( + memory_limit_, get_wddm_memory_limit(device, mem_pools_[device])); +#else return memory_limit_; +#endif } size_t CudaAllocator::set_memory_limit(size_t limit) { @@ -372,8 +383,17 @@ size_t CudaAllocator::set_cache_limit(size_t limit) { } void CudaAllocator::clear_cache() { - std::lock_guard lk(mutex_); - buffer_cache_.clear(); + { + std::lock_guard lk(mutex_); + buffer_cache_.clear(); + } + for (size_t i = 0; i < mem_pools_.size(); ++i) { + if (mem_pools_[i]) { + cu::device(static_cast(i)).make_current(); + CHECK_CUDA_ERROR(cudaStreamSynchronize(free_streams_[i])); + CHECK_CUDA_ERROR(cudaMemPoolTrimTo(mem_pools_[i], 0)); + } + } } CudaAllocator& allocator() { @@ -388,9 +408,10 @@ CudaAllocator& allocator() { return *allocator_; } -Buffer malloc_async(size_t size, CommandEncoder& encoder) { - return allocator().malloc_async( - size, encoder.device().cuda_device(), encoder.stream()); +allocator::Data malloc_async(size_t size, CommandEncoder& encoder) { + return allocator::Data( + allocator().malloc_async( + size, encoder.device().cuda_device(), encoder.stream())); } } // namespace cu diff --git a/mlx/backend/cuda/allocator.h b/mlx/backend/cuda/allocator.h index df703b8ff3..e851ce6f7f 100644 --- a/mlx/backend/cuda/allocator.h +++ b/mlx/backend/cuda/allocator.h @@ -91,6 +91,6 @@ class CudaAllocator : public allocator::Allocator { CudaAllocator& allocator(); -Buffer malloc_async(size_t size, CommandEncoder& encoder); +allocator::Data malloc_async(size_t size, CommandEncoder& encoder); } // namespace mlx::core::cu diff --git a/mlx/backend/cuda/arg_reduce.cu b/mlx/backend/cuda/arg_reduce.cu index 9609b85972..39abb274aa 100644 --- a/mlx/backend/cuda/arg_reduce.cu +++ b/mlx/backend/cuda/arg_reduce.cu @@ -35,8 +35,11 @@ struct ArgMin { __device__ IndexValPair operator()( const IndexValPair& best, const IndexValPair& current) { - if (best.val > current.val || - (best.val == current.val && best.index > current.index)) { + if ((cuda::std::isnan(current.val) && + (!cuda::std::isnan(best.val) || best.index > current.index)) || + (!cuda::std::isnan(best.val) && + (best.val > current.val || + (best.val == current.val && best.index > current.index)))) { return current; } else { return best; @@ -50,7 +53,8 @@ struct ArgMin { uint32_t offset) { #pragma unroll for (int i = 0; i < N; i++) { - if (vals[i] < best.val) { + if ((!cuda::std::isnan(best.val) && cuda::std::isnan(vals[i])) || + vals[i] < best.val) { best.val = vals[i]; best.index = offset + i; } @@ -68,8 +72,11 @@ struct ArgMax { __device__ IndexValPair operator()( const IndexValPair& best, const IndexValPair& current) { - if (best.val < current.val || - (best.val == current.val && best.index > current.index)) { + if ((cuda::std::isnan(current.val) && + (!cuda::std::isnan(best.val) || best.index > current.index)) || + (!cuda::std::isnan(best.val) && + (best.val < current.val || + (best.val == current.val && best.index > current.index)))) { return current; } else { return best; @@ -83,7 +90,8 @@ struct ArgMax { uint32_t offset) { #pragma unroll for (int i = 0; i < N; i++) { - if (vals[i] > best.val) { + if ((!cuda::std::isnan(best.val) && cuda::std::isnan(vals[i])) || + vals[i] > best.val) { best.val = vals[i]; best.index = offset + i; } diff --git a/mlx/backend/cuda/binary/CMakeLists.txt b/mlx/backend/cuda/binary/CMakeLists.txt index bda289de70..db83265050 100644 --- a/mlx/backend/cuda/binary/CMakeLists.txt +++ b/mlx/backend/cuda/binary/CMakeLists.txt @@ -5,6 +5,7 @@ target_sources( PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/bitwise_binary.cu PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/divide.cu PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/equal.cu + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/floor_divide.cu PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/greater.cu PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/greater_equal.cu PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/less.cu diff --git a/mlx/backend/cuda/binary/binary.cuh b/mlx/backend/cuda/binary/binary.cuh index 6130f63c71..e7445b287c 100644 --- a/mlx/backend/cuda/binary/binary.cuh +++ b/mlx/backend/cuda/binary/binary.cuh @@ -209,9 +209,10 @@ __global__ void binary_g( template constexpr bool supports_binary_op() { if (std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v) { + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v) { return std::is_same_v; } if (std::is_same_v || std::is_same_v || diff --git a/mlx/backend/cuda/binary/floor_divide.cu b/mlx/backend/cuda/binary/floor_divide.cu new file mode 100644 index 0000000000..337c71af89 --- /dev/null +++ b/mlx/backend/cuda/binary/floor_divide.cu @@ -0,0 +1,7 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cuda/binary/binary.cuh" + +namespace mlx::core { +BINARY_GPU(FloorDivide) +} // namespace mlx::core diff --git a/mlx/backend/cuda/cholesky.cu b/mlx/backend/cuda/cholesky.cu new file mode 100644 index 0000000000..47c993fb0e --- /dev/null +++ b/mlx/backend/cuda/cholesky.cu @@ -0,0 +1,141 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cuda/cusolver_utils.h" +#include "mlx/backend/cuda/device.h" +#include "mlx/backend/cuda/kernel_utils.cuh" +#include "mlx/backend/cuda/utils.h" +#include "mlx/backend/gpu/copy.h" +#include "mlx/primitives.h" + +#include +#include + +namespace mlx::core { + +namespace cu { + +namespace cg = cooperative_groups; + +// potrf writes only one triangle; zero the other one to match the CPU op. +template +__global__ void zero_triangle(T* out, IdxT size, int32_t n, bool zero_below) { + IdxT index = cg::this_grid().thread_rank(); + if (index >= size) { + return; + } + int32_t row = (index / n) % n; + int32_t col = index % n; + if (zero_below ? (col < row) : (col > row)) { + out[index] = T(0); + } +} + +// potrfBatched wants a device array of per matrix pointers. +__global__ void +fill_matrix_pointers(void** ptrs, float* base, int64_t n2, int64_t batch) { + int64_t i = cg::this_grid().thread_rank(); + if (i < batch) { + ptrs[i] = base + i * n2; + } +} + +} // namespace cu + +void Cholesky::eval_gpu(const std::vector& inputs, array& out) { + nvtx3::scoped_range r("Cholesky::eval_gpu"); + auto& s = stream(); + auto& a = inputs[0]; + + // Copy the input to the output; the factorization runs in place. + copy_gpu( + a, + out, + a.flags().row_contiguous ? CopyType::Vector : CopyType::General, + s); + + if (a.size() == 0) { + return; + } + + auto& encoder = cu::get_command_encoder(s); + + auto handle = get_cusolver_handle(encoder.device()); + CHECK_CUSOLVER_ERROR(cusolverDnSetStream(handle, encoder.stream())); + + // cuSOLVER is column major. The input is symmetric and a column major + // lower triangle is a row major upper one, so pass the opposite of + // upper_, same as the CPU op. + cublasFillMode_t uplo = + upper_ ? CUBLAS_FILL_MODE_LOWER : CUBLAS_FILL_MODE_UPPER; + + // Only float32 reaches eval_gpu: float64 is rejected on GPU streams at + // array construction. + auto type = CUDA_R_32F; + auto* out_ptr = gpu_ptr(out); + + int64_t n = a.shape(-1); + int64_t batch = a.size() / (n * n); + + // Matching the CPU op, info is never read back: a non positive definite + // input gives an undefined factor rather than an error. + auto* info = static_cast( + allocate_workspace(encoder, batch * sizeof(int))); + + // TODO: For some consumer cards serialized loop might be faster. + if (batch > 1) { + array ptrs( + cu::malloc_async(batch * sizeof(void*), encoder), + {static_cast(batch)}, + uint64); + encoder.add_temporary(ptrs); + encoder.set_output_array(ptrs); + encoder.add_kernel_node( + &cu::fill_matrix_pointers, + cuda::ceil_div(batch, 256), + 256, + gpu_ptr(ptrs), + out_ptr, + n * n, + batch); + + encoder.set_input_array(ptrs); + encoder.set_output_array(out); + auto capture = encoder.capture_context(); + CHECK_CUSOLVER_ERROR(cusolverDnSpotrfBatched( + handle, + uplo, + n, + gpu_ptr(ptrs), + /* lda */ n, + info, + batch)); + } else { + int lwork = 0; + CHECK_CUSOLVER_ERROR(cusolverDnSpotrf_bufferSize( + handle, uplo, n, out_ptr, n, &lwork)); + auto* workspace = static_cast( + allocate_workspace(encoder, lwork * sizeof(float))); + + encoder.set_input_array(out); + encoder.set_output_array(out); + auto capture = encoder.capture_context(); + CHECK_CUSOLVER_ERROR(cusolverDnSpotrf( + handle, uplo, n, out_ptr, n, workspace, lwork, info)); + } + + encoder.set_output_array(out); + dispatch_bool(out.size() > INT32_MAX, [&](auto large) { + using IdxT = std::conditional_t; + auto [num_blocks, block_dims] = get_launch_args(out, large()); + encoder.add_kernel_node( + cu::zero_triangle, + num_blocks, + block_dims, + out_ptr, + static_cast(out.size()), + static_cast(n), + upper_); + }); +} + +} // namespace mlx::core diff --git a/mlx/backend/cuda/cuda_utils.h b/mlx/backend/cuda/cuda_utils.h index f8a234ee65..083d19e6ff 100644 --- a/mlx/backend/cuda/cuda_utils.h +++ b/mlx/backend/cuda/cuda_utils.h @@ -26,11 +26,10 @@ class CudaHandle { } ~CudaHandle() { - // Skip if there was an error to avoid throwing in the destructors - if (cudaPeekAtLastError() != cudaSuccess) { - return; + // Skip error check to avoid throwing in destructors. + if (handle_ != nullptr) { + Destroy(handle_); } - reset(); } CudaHandle(const CudaHandle&) = delete; diff --git a/mlx/backend/cuda/cusolver_utils.cpp b/mlx/backend/cuda/cusolver_utils.cpp new file mode 100644 index 0000000000..b4366d8d74 --- /dev/null +++ b/mlx/backend/cuda/cusolver_utils.cpp @@ -0,0 +1,47 @@ +// Copyright © 2026 Apple Inc. +#include "mlx/backend/cuda/cusolver_utils.h" +#include "mlx/backend/gpu/device_info.h" + +#include + +namespace mlx::core { + +namespace { + +auto& cusolver_handles_cache() { + struct CusolverHandle { + ~CusolverHandle() { + if (handle) { + // Not checked: runs at thread exit where a throw would terminate. + cusolverDnDestroy(handle); + } + } + cusolverDnHandle_t handle{nullptr}; + }; + static thread_local std::vector cache(gpu::device_count()); + return cache; +} + +} // namespace + +cusolverDnHandle_t get_cusolver_handle(cu::Device& device) { + auto& storage = cusolver_handles_cache().at(device.cuda_device()); + if (!storage.handle) { + device.make_current(); + CHECK_CUSOLVER_ERROR(cusolverDnCreate(&storage.handle)); + } + return storage.handle; +} + +void init_cusolver_handles_cache() { + cusolver_handles_cache(); +} + +void check_cusolver_error(const char* name, cusolverStatus_t err) { + if (err != CUSOLVER_STATUS_SUCCESS) { + throw std::runtime_error( + fmt::format("{} failed with code: {}.", name, static_cast(err))); + } +} + +} // namespace mlx::core diff --git a/mlx/backend/cuda/cusolver_utils.h b/mlx/backend/cuda/cusolver_utils.h new file mode 100644 index 0000000000..ad457a9824 --- /dev/null +++ b/mlx/backend/cuda/cusolver_utils.h @@ -0,0 +1,18 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include "mlx/backend/cuda/device.h" + +#include + +namespace mlx::core { + +void check_cusolver_error(const char* name, cusolverStatus_t err); + +#define CHECK_CUSOLVER_ERROR(cmd) check_cusolver_error(#cmd, (cmd)) + +void init_cusolver_handles_cache(); + +cusolverDnHandle_t get_cusolver_handle(cu::Device& device); + +} // namespace mlx::core diff --git a/mlx/backend/cuda/delayload.cpp b/mlx/backend/cuda/delayload.cpp index 7092d4497c..44f6d163c6 100644 --- a/mlx/backend/cuda/delayload.cpp +++ b/mlx/backend/cuda/delayload.cpp @@ -61,6 +61,22 @@ fs::path load_cudnn() { return cudnn_dir; } +fs::path load_cusolver() { + fs::path cusolver_dir; + if (const char* dir = cuda_bin_dir()) { + cusolver_dir = dir; + } else { + cusolver_dir = relative_to_current_binary("../nvidia/cusolver/bin"); + ::AddDllDirectory(cublas_dir().c_str()); + ::AddDllDirectory( + relative_to_current_binary("../nvidia/cusparse/bin").c_str()); + ::AddDllDirectory( + relative_to_current_binary("../nvidia/nvjitlink/bin").c_str()); + } + ::AddDllDirectory(cusolver_dir.c_str()); + return cusolver_dir; +} + // Called by system when failed to locate a lazy-loaded DLL. FARPROC WINAPI delayload_helper(unsigned dliNotify, PDelayLoadInfo pdli) { HMODULE mod = NULL; @@ -71,6 +87,9 @@ FARPROC WINAPI delayload_helper(unsigned dliNotify, PDelayLoadInfo pdli) { mod = ::LoadLibraryW((cudnn_dir / dll).c_str()); } else if (dll.starts_with("cublas")) { mod = ::LoadLibraryW((cublas_dir() / dll).c_str()); + } else if (dll.starts_with("cusolver")) { + static auto cusolver_dir = load_cusolver(); + mod = ::LoadLibraryW((cusolver_dir / dll).c_str()); } else if (dll.starts_with("nvrtc")) { static auto nvrtc_dir = load_nvrtc(); mod = ::LoadLibraryW((nvrtc_dir / dll).c_str()); diff --git a/mlx/backend/cuda/device.cpp b/mlx/backend/cuda/device.cpp index 472b3d99fb..6e40b34038 100644 --- a/mlx/backend/cuda/device.cpp +++ b/mlx/backend/cuda/device.cpp @@ -213,7 +213,11 @@ CommandEncoder::CommandEncoder(Device& d) } CommandEncoder::~CommandEncoder() { - synchronize(); + try { + synchronize(); + } catch (...) { + // Synchronizing can fail when the CUDA runtime is shutting down. + } worker_->stop(); } @@ -612,13 +616,20 @@ CommandEncoder& get_command_encoder(Stream s) { } std::unordered_map& get_command_encoders() { - static thread_local std::unordered_map encoders; - return encoders; + if (is_main_thread()) { + static auto* encoders = new std::unordered_map(); + return *encoders; + } else { + static thread_local std::unordered_map encoders; + return encoders; + } } std::unordered_map& get_global_command_encoders() { - static std::unordered_map encoders; - return encoders; + // encoders are leaked intentionally as they would synchronize on process + // shutdown + static auto* encoders = new std::unordered_map(); + return *encoders; } } // namespace mlx::core::cu diff --git a/mlx/backend/cuda/device.h b/mlx/backend/cuda/device.h index 198f0b5ad8..1ec8f20fa5 100644 --- a/mlx/backend/cuda/device.h +++ b/mlx/backend/cuda/device.h @@ -18,7 +18,7 @@ std::pair subgraph_to_key(cudaGraph_t graph); class Worker; -class CommandEncoder { +class MLX_API CommandEncoder { public: struct CaptureContext { CaptureContext(CommandEncoder& enc); @@ -165,7 +165,7 @@ class CommandEncoder { int max_mb_per_graph_; }; -class Device { +class MLX_API Device { public: explicit Device(int device); ~Device(); diff --git a/mlx/backend/cuda/device/cast_op.cuh b/mlx/backend/cuda/device/cast_op.cuh index b85a40c83d..c2dfdd4f5f 100644 --- a/mlx/backend/cuda/device/cast_op.cuh +++ b/mlx/backend/cuda/device/cast_op.cuh @@ -25,7 +25,7 @@ struct CastOp, bool> { static constexpr bool is_castable = true; __device__ bool operator()(complex_t x) { - return x.real() != 0 && x.imag() != 0; + return x.real() != 0 || x.imag() != 0; } }; @@ -34,7 +34,7 @@ struct CastOp> { static constexpr bool is_castable = true; __device__ complex_t operator()(bool x) { - return x ? complex_t{1, 1} : complex_t{0, 0}; + return x ? complex_t{1, 0} : complex_t{0, 0}; } }; diff --git a/mlx/backend/cuda/device/gemm_sm70.cuh b/mlx/backend/cuda/device/gemm_sm70.cuh index f66b890750..63b38aee56 100644 --- a/mlx/backend/cuda/device/gemm_sm70.cuh +++ b/mlx/backend/cuda/device/gemm_sm70.cuh @@ -220,9 +220,9 @@ CUTE_DEVICE void gemm_sm70_mainloop( template inline constexpr auto make_matrix_stride(int m, int k) { if constexpr (KMajor) { - return cute::make_stride(k, cute::Int<1>{}, m * k); + return cute::make_stride(k, cute::Int<1>{}, int64_t(m) * k); } else { - return cute::make_stride(cute::Int<1>{}, m, m * k); + return cute::make_stride(cute::Int<1>{}, m, int64_t(m) * k); } } diff --git a/mlx/backend/cuda/device/qmm_naive.cuh b/mlx/backend/cuda/device/qmm_naive.cuh index e2ad855b9f..5eea030c50 100644 --- a/mlx/backend/cuda/device/qmm_naive.cuh +++ b/mlx/backend/cuda/device/qmm_naive.cuh @@ -269,6 +269,10 @@ void qmm_naive_kernel( // For gather, use index lookup for input batch slicing. uint32_t a_batch = lhs_indices ? lhs_indices[l_coord] : l_coord; uint32_t b_batch = rhs_indices ? rhs_indices[l_coord] : l_coord; + // The global scale is per gathered expert; a non-gathered call has one. + if (global_scale && rhs_indices) { + global_scale += b_batch; + } // Get batch slice. Tensor mA = mA_mkl(_,_,a_batch); // (M,K) diff --git a/mlx/backend/cuda/device/qmm_sm80.cuh b/mlx/backend/cuda/device/qmm_sm80.cuh index e6efe04022..5fea5b51b2 100644 --- a/mlx/backend/cuda/device/qmm_sm80.cuh +++ b/mlx/backend/cuda/device/qmm_sm80.cuh @@ -267,6 +267,9 @@ CUTE_DEVICE void qmm_sm80_mainloop( for (int i = 0; i < size(tCrC_accu); i++) { tCrC(i) = Element(tCrC_accu(i)); } + // The last prefetches may still be landing in the buffers C reuses. + cp_async_wait<0>(); + __syncthreads(); copy(r2s_copy_c, r2s_tCrC, r2s_tCsC); __syncthreads(); copy_if(s2g_copy_c, tCpC, s2g_tCsC, s2g_tCgC); @@ -300,9 +303,9 @@ void qmm_sm80_kernel( int l_coord = int(blockIdx.z); // Define layouts (mixed). - auto dA = make_stride(k, Int<1>{}, m * k); // (dM,dK,dL) - auto dB = make_stride(k, Int<1>{}, n * k); // (dN,dK,dL) - auto dC = make_stride(n, Int<1>{}, m * n); // (dM,dN,dL) + auto dA = make_stride(k, Int<1>{}, int64_t(m) * k); // (dM,dK,dL) + auto dB = make_stride(k, Int<1>{}, int64_t(n) * k); // (dN,dK,dL) + auto dC = make_stride(n, Int<1>{}, int64_t(m) * n); // (dM,dN,dL) auto S_layout = make_scales_layout(n, k, l); // Handle broadcasting. @@ -355,4 +358,116 @@ void qmm_sm80_kernel( thread_idx); } +template +__global__ +__launch_bounds__(decltype(size(make_tiled_mma()))::value) +void qmm_sm80_rhs_kernel( + const Element* A, + const Quant* B, + const Scale* S, + const Element* Z, + const uint32_t* rhs_indices, + Element* C, + int m, + int n, + int k, + int group_count) { + int thread_idx = int(threadIdx.x); + int m_coord = int(blockIdx.x); + int n_coord = int(blockIdx.y); + + auto cta_tiler = CtaTiler{}; + int tile_m = int(size<0>(cta_tiler)); + int y_row = m_coord * tile_m; + int m_max_coord = m - y_row; + int tgp_bm = m_max_coord < tile_m ? m_max_coord : tile_m; + + // Define layouts (mixed). All gathered rows form one matrix; each run of + // equal rhs_indices inside the row tile reuses one expert tile. + auto dA = make_stride(k, Int<1>{}, int64_t(m) * k); // (dM,dK,dL) + auto dB = make_stride(k, Int<1>{}, int64_t(n) * k); // (dN,dK,dL) + auto dC = make_stride(n, Int<1>{}, int64_t(m) * n); // (dM,dN,dL) + auto S_layout = make_scales_layout(n, k, group_count); + + Tensor mA_mkl = make_tensor(make_gmem_ptr(A), make_shape(m, k, 1), dA); // (M,K,L) + Tensor mB_nkl = make_tensor(make_gmem_ptr(B), make_shape(n, k, group_count), dB); // (N,K,L) + Tensor mC_mnl = make_tensor(make_gmem_ptr(C), make_shape(m, n, 1), dC); // (M,N,L) + + Tensor mS_nkl = make_tensor(make_gmem_ptr(S), S_layout); // (N,(group_size,K/group_size),L) + Tensor mZ_nkl = make_tensor(make_gmem_ptr(Z), S_layout); // (N,(group_size,K/group_size),L) + + Tensor mA = mA_mkl(_,_,0); // (M,K) + Tensor mC = mC_mnl(_,_,0); // (M,N) + uint32_t index_next = rhs_indices[y_row]; + int offset_next = 0; + while (offset_next < tgp_bm) { + int offset = offset_next; + uint32_t b_batch = index_next; + offset_next = tgp_bm; + for (int row = offset + 1; row < tgp_bm; ++row) { + uint32_t index = rhs_indices[y_row + row]; + if (index != b_batch) { + offset_next = row; + index_next = index; + break; + } + } + + int run_rows = offset_next - offset; + Tensor mA_offset = + domain_offset(make_coord(y_row + offset, 0), mA); + Tensor mC_offset = + domain_offset(make_coord(y_row + offset, 0), mC); + Tensor mB = mB_nkl(_,_,b_batch); // (N,K) + Tensor mS = mS_nkl(_,_,b_batch); // (N,(group_size,K/group_size)) + Tensor mZ = mZ_nkl(_,_,b_batch); // (N,(group_size,K/group_size)) + + auto run_qmm = [&](auto run_tiler) { + Tensor gA = local_tile(mA_offset, run_tiler, make_coord(0, n_coord, _), Step<_1, X,_1>{}); // (BLK_M,BLK_K,k) + Tensor gB = local_tile(mB, run_tiler, make_coord(0, n_coord, _), Step< X,_1,_1>{}); // (BLK_N,BLK_K,k) + Tensor gC = local_tile(mC_offset, run_tiler, make_coord(0, n_coord, _), Step<_1,_1, X>{}); // (BLK_M,BLK_N) + Tensor gS = local_tile(mS, run_tiler, make_coord(0, n_coord, _), Step< X,_1,_1>{}); // (BLK_N,BLK_K,k) + Tensor gZ = local_tile(mZ, run_tiler, make_coord(0, n_coord, _), Step< X,_1,_1>{}); // (BLK_N,BLK_K,k) + + qmm_sm80_mainloop( + run_tiler, + gA, + gB, + gS, + gZ, + gC, + run_rows, + thread_idx); + }; + + constexpr int tile_rows = decltype(size<0>(cta_tiler))::value; + if constexpr (tile_rows > 32) { + if (run_rows <= 16) { + run_qmm(make_shape( + Int<16>{}, size<1>(cta_tiler), size<2>(cta_tiler))); + } else if (run_rows <= 32) { + run_qmm(make_shape( + Int<32>{}, size<1>(cta_tiler), size<2>(cta_tiler))); + } else { + run_qmm(cta_tiler); + } + } else if constexpr (tile_rows > 16) { + if (run_rows <= 16) { + run_qmm(make_shape( + Int<16>{}, size<1>(cta_tiler), size<2>(cta_tiler))); + } else { + run_qmm(cta_tiler); + } + } else { + run_qmm(cta_tiler); + } + // The next run's loads must not overwrite C while it is still being stored. + __syncthreads(); + } +} + } // namespace mlx::core::cu diff --git a/mlx/backend/cuda/eval.cpp b/mlx/backend/cuda/eval.cpp index f8a71d71bc..2862f38223 100644 --- a/mlx/backend/cuda/eval.cpp +++ b/mlx/backend/cuda/eval.cpp @@ -4,6 +4,7 @@ #include "mlx/backend/cuda/allocator.h" #include "mlx/backend/cuda/cublas_utils.h" #include "mlx/backend/cuda/cudnn_utils.h" +#include "mlx/backend/cuda/cusolver_utils.h" #include "mlx/backend/cuda/event.h" #include "mlx/primitives.h" #include "mlx/scheduler.h" @@ -20,6 +21,7 @@ void init() { mlx::core::cu::CudaEvent::init_pool(); init_cublas_handles_cache(); init_cudnn_handles_cache(); + init_cusolver_handles_cache(); init_cudnn_conv_cache(); init_cudnn_sdpa_cache(); } diff --git a/mlx/backend/cuda/event.cu b/mlx/backend/cuda/event.cu index d3b6f97f5d..aef5096262 100644 --- a/mlx/backend/cuda/event.cu +++ b/mlx/backend/cuda/event.cu @@ -232,8 +232,7 @@ AtomicEvent::AtomicEvent(Device& d) { cuda_free = cudaFree; coherent_ = false; } - buf_ = std::shared_ptr( - buf, [cuda_free](void* buf) { CHECK_CUDA_ERROR(cuda_free(buf)); }); + buf_ = std::shared_ptr(buf, [cuda_free](void* buf) { cuda_free(buf); }); if (coherent_) { *ptr() = 0; } else { @@ -341,7 +340,8 @@ void Event::wait() { } else { event.atomic->wait(value()); } - CHECK_CUDA_ERROR(cudaPeekAtLastError()); + // Check for errors during kernel execution and reset the error state. + CHECK_CUDA_ERROR(cudaGetLastError()); check_error(); } diff --git a/mlx/backend/cuda/fence.cpp b/mlx/backend/cuda/fence.cpp index 3a3acdba09..1b29044df6 100644 --- a/mlx/backend/cuda/fence.cpp +++ b/mlx/backend/cuda/fence.cpp @@ -5,31 +5,47 @@ #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/event.h" +#include + namespace mlx::core { struct FenceImpl { uint32_t count; - Event event; + std::vector gpu_events; + Event cpu_event; - FenceImpl(uint32_t count, Stream s) : count(count), event(s) {} + FenceImpl(uint32_t count, Stream s) : count(count), cpu_event(s) { + // Ensure that we use AtomicEvent, it is the only event that can order a CPU + // stream against the GPU. + cpu_event.cast().ensure_created(s, 2); + } }; Fence::Fence(Stream s) { fence_ = std::make_shared(0, s); - // Ensure that we use AtomicEvent. - cast().event.cast().ensure_created(s, 2); } -void Fence::wait(Stream s, const array&) { - cast().event.wait(); +void Fence::wait(Stream s, const array&, uint32_t value) { + auto& f = cast(); + if (value == 0) { + return; + } + if (!f.gpu_events.empty() && s.device == Device::gpu) { + f.gpu_events.at(value - 1).wait(s); + } else { + // AtomicEvent can not reliably notify a GPU stream, so a dependency that + // involves the CPU keeps the synchronous wait. + auto& event = f.cpu_event; + event.set_value(value); + event.wait(); + } } -void Fence::update(Stream s, const array& a, bool cross_device) { +uint32_t Fence::update(Stream s, const array& a, bool cross_device) { auto& f = cast(); if (cross_device) { // Move to managed memory if there is a device switch - auto& cbuf = - *static_cast(const_cast(a).buffer().ptr()); + auto& cbuf = *static_cast(a.buffer().ptr()); if (cbuf.device != -1) { auto& encoder = cu::get_command_encoder(s); encoder.commit(); @@ -37,8 +53,15 @@ void Fence::update(Stream s, const array& a, bool cross_device) { } } f.count++; - f.event.set_value(f.count); - f.event.signal(s); + if (s.device == Device::gpu) { + // Keep each recording so a consumer can wait for an earlier update. + auto& event = f.gpu_events.emplace_back(s); + event.set_value(1); + event.signal(s); + } + f.cpu_event.set_value(f.count); + f.cpu_event.signal(s); + return f.count; } } // namespace mlx::core diff --git a/mlx/backend/cuda/gemms/grouped_gemm_unaligned.cu b/mlx/backend/cuda/gemms/grouped_gemm_unaligned.cu index 319c759c22..c27c6be1a7 100644 --- a/mlx/backend/cuda/gemms/grouped_gemm_unaligned.cu +++ b/mlx/backend/cuda/gemms/grouped_gemm_unaligned.cu @@ -87,9 +87,12 @@ __global__ void prepare_grouped_mm_data( out_lds[group] = N; // Fill pointers. auto offset = group == 0 ? 0 : cum_histo[group - 1]; - a_ptrs[group] = a_start + offset * item_size * a_batch_stride; - b_ptrs[group] = b_start + group * item_size * b_batch_stride; - out_ptrs[group] = out_start + offset * item_size * out_batch_stride; + a_ptrs[group] = + a_start + static_cast(offset) * item_size * a_batch_stride; + b_ptrs[group] = + b_start + static_cast(group) * item_size * b_batch_stride; + out_ptrs[group] = + out_start + static_cast(offset) * item_size * out_batch_stride; } } diff --git a/mlx/backend/cuda/indexing.cpp b/mlx/backend/cuda/indexing.cpp index 68f5ea1393..fbdba986c6 100644 --- a/mlx/backend/cuda/indexing.cpp +++ b/mlx/backend/cuda/indexing.cpp @@ -57,6 +57,12 @@ void append_indices_arg( args.append(std::move(indices_strides)); } +// The 64-bit path must cover both the logical size and the span reachable +// through the strides (views) or a smaller span (broadcast arrays). +inline bool exceeds_int32(const array& a) { + return a.size() > INT32_MAX || a.data_size() > INT32_MAX; +} + } // namespace void Gather::eval_gpu(const std::vector& inputs, array& out) { @@ -75,12 +81,17 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { Dtype idx_dtype = nidx > 0 ? inputs[1].dtype() : int32; int32_t idx_ndim = nidx > 0 ? inputs[1].ndim() : 0; - bool large = (nidx > 0 && inputs[1].size() > INT32_MAX) || - (src.size() > INT32_MAX) || (out.size() > INT32_MAX); - uint32_t slice_size = std::accumulate( slice_sizes_.begin(), slice_sizes_.end(), 1, std::multiplies()); + bool large_index = false; + for (int i = 1; i <= nidx; ++i) { + large_index |= exceeds_int32(inputs[i]); + } + bool large_src = exceeds_int32(src); + bool large_out = out.size() > INT32_MAX; + bool large = large_index || large_src || large_out; + std::string module_name = fmt::format( "gather_{}_{}_{}", dtype_to_string(out.dtype()), @@ -164,8 +175,13 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { Dtype idx_dtype = nidx > 0 ? inputs[1].dtype() : int32; int32_t idx_ndim = nidx > 0 ? inputs[1].ndim() : 0; - bool large = (nidx > 0 && inputs[1].size() > INT32_MAX) || - (upd.size() > INT32_MAX) || (out.size() > INT32_MAX); + bool large_out = out.size() > INT32_MAX; + bool large_idx = false; + for (int i = 1; i <= nidx; ++i) { + large_idx |= exceeds_int32(inputs[i]); + } + bool large_upd = exceeds_int32(upd); + bool large = large_out || large_idx || large_upd; int32_t upd_post_idx_size = std::accumulate( upd.shape().begin() + idx_ndim, @@ -256,7 +272,7 @@ void GatherAxis::eval_gpu(const std::vector& inputs, array& out) { return; } - bool large = idx.size() > INT32_MAX || src.size() > INT32_MAX; + bool large = exceeds_int32(idx) || exceeds_int32(src); std::string module_name = fmt::format( "gather_axis_{}_{}", @@ -357,7 +373,8 @@ void ScatterAxis::eval_gpu(const std::vector& inputs, array& out) { return; } - bool large = idx.size() > INT32_MAX || src.size() > INT32_MAX; + bool large = + exceeds_int32(idx) || src.size() > INT32_MAX || exceeds_int32(upd); const char* op = reduce_type_ == ScatterAxis::Sum ? "Sum" : "Assign"; std::string module_name = fmt::format( @@ -459,7 +476,9 @@ void MaskedScatter::eval_gpu(const std::vector& inputs, array& out) { return; } - array mask_flat = flatten_in_eval(mask, 1, -1, s); + array mask_flat = (mask.ndim() == 1) + ? reshape_in_eval(mask, {mask.shape(0), 1}, s) + : flatten_in_eval(mask, 1, -1, s); if (gpu_ptr(mask_flat) != gpu_ptr(mask)) { encoder.add_temporary(mask_flat); } @@ -621,7 +640,7 @@ void SliceUpdate::eval_gpu(const std::vector& inputs, array& out) { bool upd_contiguous = upd.flags().row_contiguous; bool upd_scalar = upd.data_size() == 1; bool out_contiguous = rc; - bool large = upd.size() > INT32_MAX; + bool large = exceeds_int32(upd); std::string module_name = fmt::format("slice_update_{}_{}", op_name, dtype_to_string(out.dtype())); diff --git a/mlx/backend/cuda/lru_cache.h b/mlx/backend/cuda/lru_cache.h index d208315a0a..02bebe673e 100644 --- a/mlx/backend/cuda/lru_cache.h +++ b/mlx/backend/cuda/lru_cache.h @@ -76,6 +76,7 @@ class LRUCache { auto it = map_.find(key); if (it == map_.end()) return end(); + cache_misses_ = 0; vlist_.splice(vlist_.begin(), vlist_, it->second); return it->second; } @@ -84,6 +85,7 @@ class LRUCache { std::pair emplace(const K& key, U&& value) { auto it = map_.find(key); if (it != map_.end()) { + cache_misses_ = 0; vlist_.splice(vlist_.begin(), vlist_, it->second); return {it->second, false}; } diff --git a/mlx/backend/cuda/primitives.cpp b/mlx/backend/cuda/primitives.cpp index 94f260767f..104c7fd3fc 100644 --- a/mlx/backend/cuda/primitives.cpp +++ b/mlx/backend/cuda/primitives.cpp @@ -24,14 +24,37 @@ namespace mlx::core { throw std::runtime_error(#func " has no CUDA implementation."); \ } +bool fast::GatedDeltaUpdate::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + const bool has_mask, + Stream s) { + return true; +} + +bool fast::GatedDeltaUpdateVJP::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + Stream s) { + return true; +} + NO_GPU_MULTI(LUF) NO_GPU_MULTI(QRF) NO_GPU_MULTI(SVD) NO_GPU(Inverse) -NO_GPU(Cholesky) NO_GPU_MULTI(Eig) NO_GPU_MULTI(Eigh) +namespace fast { +NO_GPU_MULTI(GatedDeltaUpdate) +NO_GPU_MULTI(GatedDeltaUpdateVJP) +} // namespace fast + namespace distributed { NO_GPU_MULTI(Send) NO_GPU_MULTI(Recv) diff --git a/mlx/backend/cuda/quantized/qmm/fp_qmv.cu b/mlx/backend/cuda/quantized/qmm/fp_qmv.cu index 41de03e85c..4e148744c0 100644 --- a/mlx/backend/cuda/quantized/qmm/fp_qmv.cu +++ b/mlx/backend/cuda/quantized/qmm/fp_qmv.cu @@ -1,4 +1,4 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include "mlx/backend/common/quantized.h" #include "mlx/backend/cuda/device/utils.cuh" @@ -64,6 +64,7 @@ __device__ void fp_qmv_impl( const uint8_t* scales_, const T* vec, T* out, + float scale, int rows, int cols) { auto block = cg::this_thread_block(); @@ -150,7 +151,7 @@ __device__ void fp_qmv_impl( sum = cg::reduce(warp, sum, cg::plus{}); if (warp.thread_rank() == 0) { - out[row] = static_cast(sum); + out[row] = static_cast(sum * scale); } } } @@ -170,7 +171,7 @@ __global__ void fp_qmv_single( int rows, int cols) { fp_qmv_impl( - mat, scales, vec, out, rows, cols); + mat, scales, vec, out, 1.0f, rows, cols); } template < @@ -208,7 +209,39 @@ __global__ void fp_qmv_batched( mat_strides, scales_strides); fp_qmv_impl( - mat, scales, vec, out, rows, cols); + mat, scales, vec, out, 1.0f, rows, cols); +} + +template < + typename T, + int rows_per_block, + int n_per_thread, + int bits, + int group_size, + bool use_mx_scale> +__global__ void fp_gather_qmv( + const uint32_t* mat, + const uint8_t* scales, + const float* global_scale, + const T* vec, + T* out, + const uint32_t* lhs_indices, + const uint32_t* rhs_indices, + int rows, + int cols) { + constexpr int vals_per_item = bits == 8 ? 4 : 8; + uint32_t idx = cg::this_grid().block_index().z; + int64_t mat_size = static_cast(rows) * (cols / vals_per_item); + int64_t scales_size = static_cast(rows) * (cols / group_size); + mat += rhs_indices[idx] * mat_size; + scales += rhs_indices[idx] * scales_size; + vec += static_cast(lhs_indices[idx]) * cols; + out += static_cast(idx) * rows; + float scale = global_scale + ? global_scale[rhs_indices[idx]] / (F8E4M3_MAX * F4E2M1_MAX) + : 1.0f; + fp_qmv_impl( + mat, scales, vec, out, scale, rows, cols); } } // namespace cu @@ -228,6 +261,24 @@ void dispatch_1_2_4(int n, F&& f) { } } +// Packed words loaded per thread, limited by the alignment of the inputs. +template +int fp_qmv_n_per_thread( + const uint32_t* mat, + const T* vec, + uint32_t K, + int bits) { + if (K % 32 == 0 && cu::is_aligned<4>(mat) && + ((bits == 4 && cu::is_aligned<8>(vec)) || cu::is_aligned<4>(vec))) { + return 4; + } + if (cu::is_aligned<2>(mat) && + ((bits == 4 && cu::is_aligned<4>(vec)) || cu::is_aligned<2>(vec))) { + return 2; + } + return 1; +} + void fp_qmv( const array& x, const array& w, @@ -259,17 +310,7 @@ void fp_qmv( uint32_t blocks_y = (N + rows_per_block - 1) / rows_per_block; const uint32_t* mat_ptr = gpu_ptr(mat); const T* vec_ptr = gpu_ptr(vec); - int n = 1; - if (K % 32 == 0 && cu::is_aligned<4>(mat_ptr) && - ((bits == 4 && cu::is_aligned<8>(vec_ptr)) || - cu::is_aligned<4>(vec_ptr))) { - n = 4; - } else if ( - cu::is_aligned<2>(mat_ptr) && - ((bits == 4 && cu::is_aligned<4>(vec_ptr)) || - cu::is_aligned<2>(vec_ptr))) { - n = 2; - } + int n = fp_qmv_n_per_thread(mat_ptr, vec_ptr, K, bits); dispatch_1_2_4(n, [&](auto n) { if (B == 1) { auto kernel = @@ -323,4 +364,95 @@ void fp_qmv( }); } +bool supports_fp_gather_qmv( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& out, + bool transpose, + int bits, + int group_size, + QuantizationMode mode, + cu::Device& device) { + constexpr uint32_t max_grid_yz_dim = 65535; + if (mode == QuantizationMode::Affine || !transpose) { + return false; + } + if (out.shape(-2) != 1) { + return false; + } + if (!w.flags().row_contiguous || !scales.flags().row_contiguous) { + return false; + } + int k = x.shape(-1); + if (k < 512 || k % 32 != 0) { + return false; + } + uint32_t n = out.shape(-1); + if (n > rows_per_block * max_grid_yz_dim || + out.size() / n > max_grid_yz_dim) { + return false; + } + return true; +} + +void fp_gather_qmv( + const array& x, + const array& w, + const array& scales, + const std::optional& global_scale, + const array& lhs_indices, + const array& rhs_indices, + array& out, + int bits, + int group_size, + cu::CommandEncoder& encoder) { + uint32_t N = out.shape(-1); + uint32_t K = x.shape(-1); + uint32_t B = out.size() / N; + + encoder.set_input_array(w); + encoder.set_input_array(scales); + if (global_scale) { + encoder.set_input_array(*global_scale); + } + encoder.set_input_array(x); + encoder.set_input_array(lhs_indices); + encoder.set_input_array(rhs_indices); + encoder.set_output_array(out); + dispatch_float_types(out.dtype(), "gather_qmv", [&](auto type_tag) { + using T = cuda_type_t; + if constexpr (!std::is_same_v) { + dim3 block_dims{WARP_SIZE, rows_per_block}; + uint32_t blocks_y = (N + rows_per_block - 1) / rows_per_block; + const uint32_t* mat_ptr = gpu_ptr(w); + const T* vec_ptr = gpu_ptr(x); + int n = fp_qmv_n_per_thread(mat_ptr, vec_ptr, K, bits); + dispatch_1_2_4(n, [&](auto n) { + auto kernel = + cu::fp_gather_qmv; + if (bits == 8) { + kernel = cu::fp_gather_qmv; + } else if (group_size == 16) { + kernel = cu::fp_gather_qmv; + } + encoder.add_kernel_node( + kernel, + {1, blocks_y, B}, + block_dims, + mat_ptr, + gpu_ptr(scales), + global_scale ? gpu_ptr(*global_scale) : nullptr, + vec_ptr, + gpu_ptr(out), + gpu_ptr(lhs_indices), + gpu_ptr(rhs_indices), + N, + K); + }); + } + }); +} + } // namespace mlx::core diff --git a/mlx/backend/cuda/quantized/qmm/qmm.h b/mlx/backend/cuda/quantized/qmm/qmm.h index 64cfecfd5a..7c567ed244 100644 --- a/mlx/backend/cuda/quantized/qmm/qmm.h +++ b/mlx/backend/cuda/quantized/qmm/qmm.h @@ -57,6 +57,30 @@ void qmm_sm80( QuantizationMode mode, cu::CommandEncoder& encoder); +bool supports_gather_qmm_rhs_sm80( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& out, + bool transpose, + int bits, + int group_size, + QuantizationMode mode, + cu::Device& device); + +void gather_qmm_rhs_sm80( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& rhs_indices, + array& out, + int bits, + int group_size, + QuantizationMode mode, + cu::CommandEncoder& encoder); + bool supports_qmm_naive( const array& x, const array& w, @@ -106,6 +130,30 @@ void fp_qmv( cu::CommandEncoder& encoder, Stream s); +bool supports_fp_gather_qmv( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& out, + bool transpose, + int bits, + int group_size, + QuantizationMode mode, + cu::Device& device); + +void fp_gather_qmv( + const array& x, + const array& w, + const array& scales, + const std::optional& global_scale, + const array& lhs_indices, + const array& rhs_indices, + array& out, + int bits, + int group_size, + cu::CommandEncoder& encoder); + bool supports_qmv( const array& x, const array& w, @@ -135,6 +183,7 @@ void gather_qmv( const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, const array& lhs_indices, const array& rhs_indices, array& out, diff --git a/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu b/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu index 9818239561..4ce2817d34 100644 --- a/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu +++ b/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu @@ -21,6 +21,10 @@ inline auto make_cta_tiler(int m, int group_size) { return cute::make_shape(tile_m, tile_n, tile_k); } +inline int get_quantized_batch_count(const array& w) { + return w.ndim() > 2 ? w.size() / (w.shape(-1) * w.shape(-2)) : 1; +} + } // namespace void qmm_sm80( @@ -113,4 +117,125 @@ void qmm_sm80( broadcast_b); } +bool supports_gather_qmm_rhs_sm80( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& out, + bool transpose, + int bits, + int group_size, + QuantizationMode mode, + cu::Device& device) { + int out_m = out.ndim() > 1 ? out.shape(-2) : 1; + if (out_m != 1) { + return false; + } + if (!supports_qmm_sm80( + x, + w, + scales, + biases, + out, + transpose, + bits, + group_size, + mode, + device)) { + return false; + } + + int rows = out.size() / out.shape(-1); + int input_rows = x.size() / x.shape(-1); + int group_count = get_quantized_batch_count(w); + return input_rows == rows && rows >= 16 && group_count > 0 && + rows / group_count >= 4; +} + +void gather_qmm_rhs_sm80( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + const array& rhs_indices, + array& out, + int bits, + int group_size, + QuantizationMode mode, + cu::CommandEncoder& encoder) { + int m = x.size() / x.shape(-1); + int n = out.shape(-1); + int k = x.shape(-1); + int group_count = get_quantized_batch_count(w); + auto cta_tiler = make_cta_tiler(m, group_size); + + std::string module_name = fmt::format( + "gather_qmm_rhs_sm80_tn_{}_m{}_b{}_g{}_{}", + dtype_to_string(x.dtype()), + cute::size<0>(cta_tiler), + bits, + group_size, + quantization_mode_to_string(mode)); + + auto [ctype_x, ctype_q, ctype_s] = get_qmm_cutlass_types(x, bits, mode); + std::string kernel_name = fmt::format( + "mlx::core::cu::qmm_sm80_rhs_kernel<{}, {}, {}, {}, {}>", + group_size, + ctype_x, + ctype_q, + ctype_s, + cta_tiler_to_string(cta_tiler)); + + cu::JitModule& mod = cu::get_jit_module(encoder.device(), module_name, [&]() { + return std::make_tuple( + false, jit_source_qmm_sm80, std::vector{kernel_name}); + }); + + encoder.set_input_array(x); + encoder.set_input_array(w); + encoder.set_input_array(scales); + if (biases) { + encoder.set_input_array(*biases); + } + encoder.set_input_array(rhs_indices); + encoder.set_output_array(out); + + dim3 num_blocks{ + uint32_t(cute::ceil_div(m, cute::size<0>(cta_tiler))), + uint32_t(cute::ceil_div(n, cute::size<1>(cta_tiler))), + 1}; + dim3 block_dims{uint32_t(cute::size(cu::make_tiled_mma()))}; + + auto [sA_layout, sB_layout, sC_layout] = cu::make_smem_layouts(cta_tiler); + size_t smem_bytes = std::max( + cute::cosize(sA_layout) * x.itemsize() + + cute::cosize(sB_layout) * bits / 8, + cute::cosize(sC_layout) * x.itemsize()); + + auto kernel = mod.get_kernel(kernel_name, [&](CUfunction kernel) { + if (smem_bytes > 48000) { + cuFuncSetAttribute( + kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, smem_bytes); + } + }); + + encoder.add_kernel_node_ex( + kernel, + num_blocks, + block_dims, + {}, + smem_bytes, + gpu_ptr(x), + gpu_ptr(w), + gpu_ptr(scales), + biases ? gpu_ptr(*biases) : nullptr, + gpu_ptr(rhs_indices), + gpu_ptr(out), + m, + n, + k, + group_count); +} + } // namespace mlx::core diff --git a/mlx/backend/cuda/quantized/qmm/qmm_sm90.cu b/mlx/backend/cuda/quantized/qmm/qmm_sm90.cu index 7bc5d83437..546e1755db 100644 --- a/mlx/backend/cuda/quantized/qmm/qmm_sm90.cu +++ b/mlx/backend/cuda/quantized/qmm/qmm_sm90.cu @@ -124,10 +124,10 @@ void qmm_sm90( const char* tag = "[quantized_matmul]"; auto [m, n, k, l, broadcast_b] = make_problem_shape(x, w, out); - auto dA = make_stride(int64_t(k), Int<1>{}, int64_t(m * k)); - auto dB = make_stride(int64_t(k), Int<1>{}, int64_t(n * k)); - auto dS = make_stride(Int<1>{}, int64_t(n), int64_t(n * k / group_size)); - auto dD = make_stride(Int<1>{}, int64_t(n), int64_t(m * n)); + auto dA = make_stride(int64_t(k), Int<1>{}, int64_t(m) * k); + auto dB = make_stride(int64_t(k), Int<1>{}, int64_t(n) * k); + auto dS = make_stride(Int<1>{}, int64_t(n), int64_t(n) * k / group_size); + auto dD = make_stride(Int<1>{}, int64_t(n), int64_t(m) * n); if (broadcast_b) { get<2>(dB) = 0; get<2>(dS) = 0; diff --git a/mlx/backend/cuda/quantized/qmm/qmv.cu b/mlx/backend/cuda/quantized/qmm/qmv.cu index 4ec6b95a7a..63c8478442 100644 --- a/mlx/backend/cuda/quantized/qmm/qmv.cu +++ b/mlx/backend/cuda/quantized/qmm/qmv.cu @@ -222,6 +222,7 @@ __global__ void gather_qmv_kernel( const Q* w, const S* scales, const T* biases, + const float* global_scale, T* out, const uint32_t* lhs_indices, const uint32_t* rhs_indices, @@ -244,8 +245,12 @@ __global__ void gather_qmv_kernel( x += block.group_index().y * k + m * k * x_idx; out += block.group_index().y * n + m * n * l; + // The global scale is per gathered expert. + if (global_scale) { + global_scale += w_idx; + } qmv_kernel_impl( - x, w, scales, biases, nullptr, out, row, w_idx, n, k); + x, w, scales, biases, global_scale, out, row, w_idx, n, k); } template < @@ -305,6 +310,7 @@ void gather_qmv( const Q* w, const S* scales, const T* biases, + const float* global_scale, T* out, const uint32_t* lhs_indices, const uint32_t* rhs_indices, @@ -321,7 +327,16 @@ void gather_qmv( uint32_t(cuda::ceil_div(n, rows_per_block)), uint32_t(m), uint32_t(l)}; dim3 block_dims{WARP_SIZE, rows_per_block}; void* args[] = { - &x, &w, &scales, &biases, &out, &lhs_indices, &rhs_indices, &n, &k}; + &x, + &w, + &scales, + &biases, + &global_scale, + &out, + &lhs_indices, + &rhs_indices, + &n, + &k}; dispatch_bool(k % (WARP_SIZE * elems_per_thread), [&](auto has_residue_k) { auto* kernel = &gather_qmv_kernel< @@ -464,6 +479,7 @@ void gather_qmv( const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, const array& lhs_indices, const array& rhs_indices, array& out, @@ -490,6 +506,9 @@ void gather_qmv( if (biases) { encoder.set_input_array(*biases); } + if (global_scale) { + encoder.set_input_array(*global_scale); + } encoder.set_input_array(lhs_indices); encoder.set_input_array(rhs_indices); encoder.set_output_array(out); @@ -499,6 +518,7 @@ void gather_qmv( gpu_ptr(w), gpu_ptr(scales), biases ? gpu_ptr(*biases) : nullptr, + global_scale ? gpu_ptr(*global_scale) : nullptr, gpu_ptr(out), gpu_ptr(lhs_indices), gpu_ptr(rhs_indices), diff --git a/mlx/backend/cuda/quantized/qqmm.cpp b/mlx/backend/cuda/quantized/qqmm.cpp index 196bd9c05e..5a9fba33d5 100644 --- a/mlx/backend/cuda/quantized/qqmm.cpp +++ b/mlx/backend/cuda/quantized/qqmm.cpp @@ -1,5 +1,6 @@ // Copyright © 2025 Apple Inc. +#include "mlx/backend/common/broadcasting.h" #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/quantized/qmm/qmm.h" #include "mlx/backend/cuda/quantized/qqmm_impl.h" @@ -244,6 +245,14 @@ void GatherQQMM::eval_gpu(const std::vector& inputs, array& out) { ensure_contiguous(w_pre, encoder, s), ensure_contiguous(inputs[base_size - 1], encoder, s)); + // The gather kernels take one global scale per expert. + if (global_scale_w) { + int E = w_q.size() / w_q.shape(-1) / w_q.shape(-2); + array gs_e(Shape{E}, float32, nullptr, {}); + broadcast(*global_scale_w, gs_e); + global_scale_w = ensure_row_contiguous(gs_e, encoder, s); + } + // Quantize activation. array x = quantize_dequantize_input( x_pre, global_scale_x, bits_, group_size_, encoder, s); diff --git a/mlx/backend/cuda/quantized/quantized.cpp b/mlx/backend/cuda/quantized/quantized.cpp index 4d25f3c3e0..a69c49d8f8 100644 --- a/mlx/backend/cuda/quantized/quantized.cpp +++ b/mlx/backend/cuda/quantized/quantized.cpp @@ -1,4 +1,4 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include "mlx/backend/cuda/quantized/quantized.h" #include "mlx/backend/cuda/device.h" @@ -159,9 +159,13 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { array x = ensure_row_contiguous(inputs[0], encoder, s); const array& w = inputs[1]; const array& scales = inputs[2]; + // Affine gets biases at index 3, nvfp4 an optional global scale. std::optional biases; - if (inputs.size() == 6) { + std::optional global_scale; + if (mode_ == QuantizationMode::Affine) { biases = inputs[3]; + } else if (inputs.size() == 6) { + global_scale = ensure_row_contiguous(inputs[3], encoder, s); } array lhs_indices = ensure_row_contiguous(inputs[inputs.size() - 2], encoder, s); @@ -186,9 +190,17 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { mode_, encoder.device()); }; - bool can_use_qmm_sm80 = supports(supports_qmm_sm80); + // qmm_sm80 does not apply global scales yet; route such calls to the + // naive kernel until it does. + bool can_use_qmm_sm80 = + !global_scale.has_value() && supports(supports_qmm_sm80); + bool can_use_gather_qmm_rhs_sm80 = mode_ != QuantizationMode::Affine && + right_sorted_ && !global_scale.has_value() && + supports(supports_gather_qmm_rhs_sm80); bool can_use_qmm_naive = supports(supports_qmm_naive); - bool can_use_qmv = supports(supports_qmv); + bool can_use_fp_gather_qmv = supports(supports_fp_gather_qmv); + bool can_use_qmv = supports(supports_qmv) || can_use_fp_gather_qmv; + bool prefer_qmv = can_use_fp_gather_qmv || (can_use_qmv && M * B < 8); auto call_qmm_sm80 = [&]() { out.set_data(cu::malloc_async(out.nbytes(), encoder)); @@ -212,7 +224,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, - std::nullopt, + global_scale, lhs_indices, rhs_indices, out, @@ -224,11 +236,26 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { }; auto call_qmv = [&]() { out.set_data(cu::malloc_async(out.nbytes(), encoder)); + if (can_use_fp_gather_qmv) { + fp_gather_qmv( + x, + w, + scales, + global_scale, + lhs_indices, + rhs_indices, + out, + bits_, + group_size_, + encoder); + return; + } gather_qmv( x, w, scales, biases, + global_scale, lhs_indices, rhs_indices, out, @@ -238,8 +265,24 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { encoder); }; + if (can_use_gather_qmm_rhs_sm80) { + out.set_data(cu::malloc_async(out.nbytes(), encoder)); + gather_qmm_rhs_sm80( + x, + w, + scales, + biases, + rhs_indices, + out, + bits_, + group_size_, + mode_, + encoder); + return; + } + if (can_use_qmm_sm80) { - if (can_use_qmv && (M * B < 8)) { + if (prefer_qmv) { call_qmv(); } else { call_qmm_sm80(); @@ -248,7 +291,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { } if (can_use_qmm_naive) { - if (can_use_qmv && (M * B < 8)) { + if (prefer_qmv) { call_qmv(); } else { call_qmm_naive(); diff --git a/mlx/backend/cuda/reduce/col_reduce.cu b/mlx/backend/cuda/reduce/col_reduce.cu index 8a6327bf38..3ff033f561 100644 --- a/mlx/backend/cuda/reduce/col_reduce.cu +++ b/mlx/backend/cuda/reduce/col_reduce.cu @@ -375,8 +375,7 @@ void col_reduce_two_pass( cu::malloc_async(intermediate.nbytes(), encoder), data_size, intermediate_strides, - fl, - allocator::free); + fl); encoder.add_temporary(intermediate); encoder.set_input_array(in); diff --git a/mlx/backend/cuda/reduce/reduce_utils.cuh b/mlx/backend/cuda/reduce/reduce_utils.cuh index fdbe723378..00b4d10f22 100644 --- a/mlx/backend/cuda/reduce/reduce_utils.cuh +++ b/mlx/backend/cuda/reduce/reduce_utils.cuh @@ -135,11 +135,7 @@ inline void allocate_same_layout( fl.col_contiguous = cc; fl.contiguous = true; out.set_data( - cu::malloc_async(out.nbytes(), encoder), - data_size, - final_strides, - fl, - allocator::free); + cu::malloc_async(out.nbytes(), encoder), data_size, final_strides, fl); } } // namespace mlx::core diff --git a/mlx/backend/cuda/scaled_dot_product_attention.cpp b/mlx/backend/cuda/scaled_dot_product_attention.cpp index 286d500e2c..e6c8abf122 100644 --- a/mlx/backend/cuda/scaled_dot_product_attention.cpp +++ b/mlx/backend/cuda/scaled_dot_product_attention.cpp @@ -1,4 +1,4 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include "mlx/backend/cuda/cudnn_utils.h" #include "mlx/backend/cuda/device.h" @@ -583,6 +583,7 @@ bool ScaledDotProductAttention::use_fallback( bool has_mask, bool has_arr_mask, bool do_causal, + bool has_sinks, bool is_training, bool output_logsumexp, bool force_fused, diff --git a/mlx/backend/cuda/scaled_dot_product_attention.cu b/mlx/backend/cuda/scaled_dot_product_attention.cu index 6fafb0ba98..c6996c95ef 100644 --- a/mlx/backend/cuda/scaled_dot_product_attention.cu +++ b/mlx/backend/cuda/scaled_dot_product_attention.cu @@ -460,6 +460,9 @@ void dispatch_headdim(int n, F&& f) { case 128: f(std::integral_constant{}); break; + case 256: + f(std::integral_constant{}); + break; } } @@ -674,7 +677,8 @@ bool supports_sdpa_vector( const int key_sequence_length = k.shape(2); const bool sdpa_supported_head_dim = query_head_dim == value_head_dim && - (query_head_dim == 64 || query_head_dim == 96 || query_head_dim == 128); + (query_head_dim == 64 || query_head_dim == 96 || query_head_dim == 128 || + query_head_dim == 256); const bool supported_vector_config = sdpa_supported_head_dim && query_sequence_length < 4; diff --git a/mlx/backend/cuda/scan.cu b/mlx/backend/cuda/scan.cu index a7dd2eea25..a3666d46ff 100644 --- a/mlx/backend/cuda/scan.cu +++ b/mlx/backend/cuda/scan.cu @@ -458,6 +458,11 @@ void Scan::eval_gpu(const std::vector& inputs, array& out) { auto& s = stream(); auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(out.nbytes(), encoder)); + return; + } + if (in.flags().contiguous && in.strides()[axis_] != 0) { if (in.is_donatable() && in.itemsize() == out.itemsize()) { out.copy_shared_buffer(in); @@ -469,8 +474,9 @@ void Scan::eval_gpu(const std::vector& inputs, array& out) { in.flags()); } } else { - in = contiguous_copy_gpu(in, s); - out.copy_shared_buffer(in); + // Output type can be wider than input + copy_gpu(in, out, CopyType::General, s); + in = out; } scan_gpu_inplace(in, out, reduce_type_, axis_, reverse_, inclusive_, s); diff --git a/mlx/backend/cuda/slicing.cpp b/mlx/backend/cuda/slicing.cpp index 525cccc26a..6a0b11ba59 100644 --- a/mlx/backend/cuda/slicing.cpp +++ b/mlx/backend/cuda/slicing.cpp @@ -50,6 +50,14 @@ array compute_dynamic_offset( const Strides& strides, const std::vector& axes, const Stream& s) { + auto& encoder = cu::get_command_encoder(s); + // The kernel reads the indices contiguously + if (!indices.flags().row_contiguous) { + auto copy = contiguous_copy_gpu(indices, s); + encoder.add_temporary(copy); + return compute_dynamic_offset(copy, strides, axes, s); + } + Dtype dtype = indices.dtype(); int nidx = axes.size(); @@ -60,8 +68,6 @@ array compute_dynamic_offset( dtype_to_cuda_type(dtype), nidx); - auto& encoder = cu::get_command_encoder(s); - cu::JitModule& mod = cu::get_jit_module(encoder.device(), module_name, [&]() { std::string source = R"( #include "mlx/backend/cuda/device/utils.cuh" diff --git a/mlx/backend/cuda/sort.cu b/mlx/backend/cuda/sort.cu index d9c77387ce..980cab3e30 100644 --- a/mlx/backend/cuda/sort.cu +++ b/mlx/backend/cuda/sort.cu @@ -4,6 +4,7 @@ #include #include +#include "mlx/backend/common/utils.h" #include "mlx/backend/cuda/device.h" #include "mlx/backend/cuda/device/fp16_math.cuh" #include "mlx/backend/cuda/kernel_utils.cuh" @@ -781,16 +782,24 @@ void single_block_sort( int64_t in_stride_sorted_axis = in.strides()[axis]; int64_t out_stride_sorted_axis = out.strides()[axis]; + // The contiguous kernel walks the rows with a single stride, so the axes + // that are not sorted have to collapse to a single dim. + auto single_dim = + [](const Shape& nc_shape, const Strides& nc_str, int64_t& stride) { + auto [shape, strides] = collapse_contiguous_dims(nc_shape, nc_str); + if (shape.size() > 1) { + return false; + } + if (shape.size() > 0) { + stride = strides[0]; + } + return true; + }; + int64_t in_stride_segment_axis = 0; + int64_t out_stride_segment_axis = 0; bool contiguous = in.flags().contiguous; - auto check_strides = [](const array& x, int64_t sort_stride) { - int64_t min_stride = - *std::min_element(x.strides().begin(), x.strides().end()); - int64_t max_stride = - *std::max_element(x.strides().begin(), x.strides().end()); - return sort_stride == min_stride || sort_stride == max_stride; - }; - contiguous &= check_strides(in, in_stride_sorted_axis); - contiguous &= check_strides(out, out_stride_sorted_axis); + contiguous &= single_dim(nc_shape, in_nc_str, in_stride_segment_axis); + contiguous &= single_dim(nc_shape, out_nc_str, out_stride_segment_axis); auto& encoder = cu::get_command_encoder(s); out.set_data(cu::malloc_async(out.nbytes(), encoder)); @@ -817,19 +826,9 @@ void single_block_sort( ARG_SORT, BLOCK_THREADS, N_PER_THREAD>; - int64_t in_stride_segment_axis = INT64_MAX; - int64_t out_stride_segment_axis = INT64_MAX; - for (int i = 0; i < nc_shape.size(); i++) { - if (nc_shape[i] == 1) { - continue; - } - if (in_nc_str[i] > INT32_MAX || out_nc_str[i] > INT32_MAX) { - throw std::runtime_error("[Sort::eval_gpu] Stride too large."); - } - in_stride_segment_axis = - std::min(in_stride_segment_axis, in_nc_str[i]); - out_stride_segment_axis = - std::min(out_stride_segment_axis, out_nc_str[i]); + if (in_stride_segment_axis > INT32_MAX || + out_stride_segment_axis > INT32_MAX) { + throw std::runtime_error("[Sort::eval_gpu] Stride too large."); } encoder.add_kernel_node( kernel, @@ -1084,6 +1083,10 @@ void gpu_sort( int axis, bool argsort) { auto& encoder = cu::get_command_encoder(s); + if (out.size() == 0) { + out.set_data(cu::malloc_async(out.nbytes(), encoder)); + return; + } gpu_merge_sort(s, in, out, axis, argsort); } diff --git a/mlx/backend/cuda/utils.cpp b/mlx/backend/cuda/utils.cpp index 82272b74b2..f81f589fff 100644 --- a/mlx/backend/cuda/utils.cpp +++ b/mlx/backend/cuda/utils.cpp @@ -12,6 +12,8 @@ namespace mlx::core { void check_cuda_error(const char* name, cudaError_t err) { if (err != cudaSuccess) { + // Clear the error so it does not resurface in later checks. + cudaGetLastError(); throw std::runtime_error( fmt::format("{} failed: {}", name, cudaGetErrorString(err))); } diff --git a/mlx/backend/cuda/wddm.cpp b/mlx/backend/cuda/wddm.cpp new file mode 100644 index 0000000000..71027f77c4 --- /dev/null +++ b/mlx/backend/cuda/wddm.cpp @@ -0,0 +1,107 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cuda/wddm.h" +#include "mlx/backend/cuda/utils.h" +#include "mlx/backend/gpu/device_info.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace mlx::core::cu { + +namespace { + +struct DeviceMemoryBudget { + Microsoft::WRL::ComPtr adapter; + UINT node{0}; + std::chrono::steady_clock::time_point next_query; + size_t memory_limit{std::numeric_limits::max()}; +}; + +class WddmMemoryBudget { + public: + explicit WddmMemoryBudget(size_t device_count) : budgets_(device_count) { + Microsoft::WRL::ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) { + return; + } + + for (int device = 0; device < device_count; ++device) { + cudaDeviceProp properties{}; + CHECK_CUDA_ERROR(cudaGetDeviceProperties(&properties, device)); + if (properties.integrated || properties.tccDriver || + properties.luidDeviceNodeMask == 0) { + continue; + } + + LUID luid{}; + std::memcpy(&luid, properties.luid, sizeof(luid)); + if (luid.HighPart == 0 && luid.LowPart == 0) { + continue; + } + + auto& budget = budgets_[device]; + if (FAILED(factory->EnumAdapterByLuid( + luid, IID_PPV_ARGS(&budget.adapter)))) { + continue; + } + + auto mask = properties.luidDeviceNodeMask; + while ((mask & 1) == 0) { + ++budget.node; + mask >>= 1; + } + } + } + + size_t get_memory_limit(int device, cudaMemPool_t pool) { + size_t max_size = std::numeric_limits::max(); + auto& budget = budgets_.at(device); + if (!budget.adapter || !pool) { + return max_size; + } + + auto now = std::chrono::steady_clock::now(); + std::lock_guard lock(mutex_); + if (now < budget.next_query) { + return budget.memory_limit; + } + budget.next_query = now + std::chrono::milliseconds(20); + + DXGI_QUERY_VIDEO_MEMORY_INFO info{}; + uint64_t pool_reserved = 0; + if (FAILED(budget.adapter->QueryVideoMemoryInfo( + budget.node, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &info))) { + return max_size; + } + if (info.Budget == 0) { + return max_size; + } + + CHECK_CUDA_ERROR(cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &pool_reserved)); + budget.memory_limit = + memory_limit_from_budget(info.Budget, info.CurrentUsage, pool_reserved); + return budget.memory_limit; + } + + private: + std::vector budgets_; + std::mutex mutex_; +}; + +} // namespace + +size_t get_wddm_memory_limit(int device, cudaMemPool_t pool) { + static WddmMemoryBudget budget(gpu::device_count()); + return budget.get_memory_limit(device, pool); +} + +} // namespace mlx::core::cu diff --git a/mlx/backend/cuda/wddm.h b/mlx/backend/cuda/wddm.h new file mode 100644 index 0000000000..c76224b7b6 --- /dev/null +++ b/mlx/backend/cuda/wddm.h @@ -0,0 +1,26 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include + +#include + +namespace mlx::core::cu { + +inline size_t memory_limit_from_budget( + uint64_t budget, + uint64_t usage, + uint64_t pool_reserved) { + auto non_pool_usage = usage > pool_reserved ? usage - pool_reserved : 0; + auto margin = budget / 20; + if ((non_pool_usage >= budget) || (margin >= budget - non_pool_usage)) { + return 0; + } + uint64_t size_limit = std::numeric_limits::max(); + return std::min(budget - non_pool_usage - margin, size_limit); +} + +size_t get_wddm_memory_limit(int device, cudaMemPool_t pool); + +} // namespace mlx::core::cu diff --git a/mlx/backend/cuda/worker.cpp b/mlx/backend/cuda/worker.cpp index de38a06e51..6266d6099b 100644 --- a/mlx/backend/cuda/worker.cpp +++ b/mlx/backend/cuda/worker.cpp @@ -57,14 +57,17 @@ void Worker::commit(cudaStream_t stream) { } void Worker::thread_fn() { - while (!stop_) { - uint64_t current_batch = 0; + uint64_t current_batch = 0; + while (true) { Tasks tasks; { std::unique_lock lk(mtx_); - cond_.wait(lk, [this, ¤t_batch] { + cond_.wait(lk, [this, current_batch] { return this->signaled_batch_ > current_batch || this->stop_; }); + if (stop_) { + return; + } current_batch = signaled_batch_; auto end = worker_tasks_.upper_bound(current_batch); for (auto it = worker_tasks_.begin(); it != end; ++it) { diff --git a/mlx/backend/gpu/primitives.cpp b/mlx/backend/gpu/primitives.cpp index 268d6290bf..6df6ab3e09 100644 --- a/mlx/backend/gpu/primitives.cpp +++ b/mlx/backend/gpu/primitives.cpp @@ -8,6 +8,9 @@ #if defined(MLX_USE_CUDA) #include +#include "mlx/backend/cuda/device.h" +#else +#include "mlx/backend/metal/device.h" #endif #include @@ -22,7 +25,18 @@ namespace mlx::core { void AsStrided::eval_gpu(const std::vector& inputs, array& out) { MLX_PROFILER_RANGE("AsStrided::eval_gpu"); - eval(inputs, out); + assert(inputs.size() == 1); + if (inputs[0].flags().row_contiguous) { + eval(inputs[0], out); + } else { + auto copy = contiguous_copy_gpu(inputs[0], stream()); +#if defined(MLX_USE_CUDA) + cu::get_command_encoder(stream()).add_temporary(copy); +#else + metal::get_command_encoder(stream()).add_temporary(copy); +#endif + eval(copy, out); + } } void AsType::eval_gpu(const std::vector& inputs, array& out) { @@ -246,15 +260,29 @@ void View::eval_gpu(const std::vector& inputs, array& out) { // - type size is the same // - type size is smaller and the last axis is contiguous // - the entire array is row contiguous - if (ibytes == obytes || (obytes < ibytes && in.strides().back() == 1) || - in.flags().row_contiguous) { + // and the offset is a multiple of the output type size + if (in.offset() % obytes == 0 && + (ibytes == obytes || (obytes < ibytes && in.strides().back() == 1) || + in.flags().row_contiguous)) { auto strides = in.strides(); for (int i = 0; i < static_cast(strides.size()) - 1; ++i) { strides[i] *= ibytes; strides[i] /= obytes; } + // Last axis can have any stride + if (obytes < ibytes) { + strides.back() = 1; + } + auto flags = in.flags(); + if (ibytes != obytes) { + // Last axis size can change contiguity + auto [_, row_contiguous, col_contiguous] = + check_contiguity(out.shape(), strides); + flags.row_contiguous = row_contiguous; + flags.col_contiguous = col_contiguous; + } out.copy_shared_buffer( - in, strides, in.flags(), in.data_size() * ibytes / obytes); + in, strides, flags, in.data_size() * ibytes / obytes); } else { auto tmp = array(in.shape(), in.dtype(), nullptr, {}); tmp.set_data(allocator::malloc(tmp.nbytes())); diff --git a/mlx/backend/gpu/slicing.cpp b/mlx/backend/gpu/slicing.cpp index 7f0fec27bb..2a8f401b9b 100644 --- a/mlx/backend/gpu/slicing.cpp +++ b/mlx/backend/gpu/slicing.cpp @@ -25,17 +25,16 @@ void pad_gpu( // Fill output with val fill_gpu(val, out, s); - // Find offset for start of input values - size_t data_offset = 0; + // Find start of input values + Shape start(out.ndim(), 0); for (int i = 0; i < axes.size(); i++) { auto ax = axes[i] < 0 ? out.ndim() + axes[i] : axes[i]; - data_offset += out.strides()[ax] * low_pad_size[i]; + start[ax] += low_pad_size[i]; } // Extract slice from output where input will be pasted array out_slice(in.shape(), out.dtype(), nullptr, {}); - out_slice.copy_shared_buffer( - out, out.strides(), out.flags(), out_slice.size(), data_offset); + slice(out, out_slice, start, Shape(out.ndim(), 1)); // Copy input values into the slice copy_gpu_inplace(in, out_slice, CopyType::GeneralGeneral, s); diff --git a/mlx/backend/metal/CMakeLists.txt b/mlx/backend/metal/CMakeLists.txt index ea4a995ade..cccaad8a5c 100644 --- a/mlx/backend/metal/CMakeLists.txt +++ b/mlx/backend/metal/CMakeLists.txt @@ -44,6 +44,7 @@ if(MLX_METAL_JIT) make_jit_source(binary_two) make_jit_source(fft kernels/fft/radix.h kernels/fft/readwrite.h) make_jit_source(logsumexp) + make_jit_source(cross_entropy) make_jit_source(ternary) make_jit_source(softmax) make_jit_source(scan) @@ -96,12 +97,15 @@ if(MLX_METAL_JIT) make_jit_source(steel/gemm/kernels/steel_gemm_gather_nax) make_jit_source(steel/gemm/kernels/steel_gemm_splitk_nax) make_jit_source(steel/gemm/kernels/steel_gemm_segmented_nax) + make_jit_source(steel/gemm/kernels/steel_gemm_thin_nax) make_jit_source(quantized_nax kernels/quantized_utils.h) make_jit_source(fp_quantized_nax kernels/quantized_utils.h kernels/fp8.h kernels/fp4.h) make_jit_source(steel/attn/kernels/steel_attention_nax) + make_jit_source(gated_delta_update_nax kernels/gated_delta_nax_ops.h) + make_jit_source(gated_delta_update_nax_vjp kernels/gated_delta_nax_ops.h) else() message( @@ -134,8 +138,10 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/hadamard.cpp ${CMAKE_CURRENT_SOURCE_DIR}/indexing.cpp ${CMAKE_CURRENT_SOURCE_DIR}/logsumexp.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cross_entropy.cpp ${CMAKE_CURRENT_SOURCE_DIR}/matmul.cpp ${CMAKE_CURRENT_SOURCE_DIR}/scaled_dot_product_attention.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/gated_delta_update.cpp ${CMAKE_CURRENT_SOURCE_DIR}/metal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/primitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/quantized.cpp diff --git a/mlx/backend/metal/binary.cpp b/mlx/backend/metal/binary.cpp index 7d6b2a7131..a3b3e47d57 100644 --- a/mlx/backend/metal/binary.cpp +++ b/mlx/backend/metal/binary.cpp @@ -220,6 +220,7 @@ BINARY_GPU(Divide) BINARY_GPU_MULTI(DivMod) BINARY_GPU(Remainder) BINARY_GPU(Equal) +BINARY_GPU(FloorDivide) BINARY_GPU(Greater) BINARY_GPU(GreaterEqual) BINARY_GPU(Less) diff --git a/mlx/backend/metal/conv.cpp b/mlx/backend/metal/conv.cpp index 5095522616..59acdc6ae9 100644 --- a/mlx/backend/metal/conv.cpp +++ b/mlx/backend/metal/conv.cpp @@ -350,8 +350,13 @@ void implicit_gemm_conv_2D_gpu( wn = 1; } + // The 8 channel loader reads one row per thread, so it needs bm = 64 + if (C_per_group == 8) { + bm = 64; + } + int tn = (implicit_N + bn - 1) / bn; - int tm = (implicit_M + bm - 1) / bm; + int tm = (static_cast(implicit_M) + bm - 1) / bm; int swizzle_log = 0; // Fix small channel specialization @@ -365,6 +370,9 @@ void implicit_gemm_conv_2D_gpu( } else if (C_per_group <= 4) { gemm_k_iters = ((conv_params.wS[0] * conv_params.wS[1] * 4) + bk - 1) / bk; n_channel_specialization = C_per_group; + } else if (C_per_group == 8) { + gemm_k_iters = ((conv_params.wS[0] * conv_params.wS[1] * 8) + bk - 1) / bk; + n_channel_specialization = 8; } bool small_filter = (!n_channel_specialization) && @@ -546,7 +554,7 @@ void implicit_gemm_conv_2D_general_gpu( int bk = 16; int tn = (implicit_N + bn - 1) / bn; - int tm = (adj_implicit_m + bm - 1) / bm; + int tm = (static_cast(adj_implicit_m) + bm - 1) / bm; int swizzle_log = 0; // Get channel iteration info @@ -670,7 +678,7 @@ void implicit_gemm_conv_3D_gpu( } int tn = (implicit_N + bn - 1) / bn; - int tm = (implicit_M + bm - 1) / bm; + int tm = (static_cast(implicit_M) + bm - 1) / bm; int swizzle_log = 0; bool small_filter = @@ -782,6 +790,7 @@ void pad_and_slice_conv_3D_gpu( array x_copy(xshape, x.dtype(), nullptr, {}); array zero(0, x.dtype()); pad_gpu(x, zero, x_copy, {0, -1}, {0, 0}, s); + metal::get_command_encoder(s).add_temporary(zero); metal::get_command_encoder(s).add_temporary(x_copy); return x_copy; @@ -1385,6 +1394,7 @@ void pad_in_channels_conv_2D_gpu( array x_copy(xshape, x.dtype(), nullptr, {}); array zero(0, x.dtype()); pad_gpu(x, zero, x_copy, {-1}, {0}, s); + metal::get_command_encoder(s).add_temporary(zero); metal::get_command_encoder(s).add_temporary(x_copy); return x_copy; @@ -1421,11 +1431,11 @@ void dispatch_conv_2D_gpu( conv_params.wS[0] <= 7 && conv_params.wS[1] <= 7 && conv_params.str[0] <= 2 && conv_params.str[1] <= 2 && conv_params.wt_strides[1] == conv_params.wS[1] && - conv_params.C % 16 == 0 && conv_params.C == conv_params.O) { + conv_params.C % 8 == 0 && conv_params.C == conv_params.O) { return depthwise_conv_2D_gpu(s, d, in, wt, out, conv_params); } - if ((C_per_group <= 4 || C_per_group % 16 == 0) && + if ((C_per_group <= 4 || C_per_group == 8 || C_per_group % 16 == 0) && (O_per_group <= 16 || O_per_group % 16 == 0)) { return implicit_gemm_conv_2D_gpu(s, d, in, wt, out, conv_params); } else { @@ -1442,7 +1452,7 @@ void dispatch_conv_2D_gpu( if (!conv_params.flip && is_stride_one && is_kdil_one && is_idil_one && conv_params.wS[0] == 3 && conv_params.wS[1] == 3 && conv_params.C % 32 == 0 && conv_params.O % 32 == 0 && inp_large && - channels_large) { + channels_large && env::get_var("MLX_CONV_WINOGRAD", 1)) { // Only use winograd conv when having enough memory. if (int n_step = winograd_batch_step(d, in, conv_params); n_step > 0) { return winograd_conv_2D_gpu( @@ -1558,7 +1568,8 @@ void conv_1D_gpu( const int O_per_group = O / groups; // Direct to implicit gemm conv - if (is_idil_one && (C_per_group <= 4 || C_per_group % 16 == 0) && + if (is_idil_one && + (C_per_group <= 4 || C_per_group == 8 || C_per_group % 16 == 0) && (O_per_group <= 16 || O_per_group % 16 == 0)) { MLXConvParams<2> conv_params{ /* const int N = */ static_cast(in.shape(0)), diff --git a/mlx/backend/metal/cross_entropy.cpp b/mlx/backend/metal/cross_entropy.cpp new file mode 100644 index 0000000000..cc6f0e1711 --- /dev/null +++ b/mlx/backend/metal/cross_entropy.cpp @@ -0,0 +1,125 @@ +// Copyright © 2026 Apple Inc. +#include + +#include "mlx/backend/gpu/copy.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/kernels.h" +#include "mlx/backend/metal/kernels/defines.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/fast_primitives.h" + +namespace mlx::core::fast { + +namespace { + +// Threadgroup shrinks with the axis so a small vocabulary needs one iteration. +inline std::pair cross_entropy_dims( + MTL::ComputePipelineState* kernel, + int axis_size, + int n_rows) { + constexpr size_t simd_size = 32; + size_t tg_max = + (kernel->maxTotalThreadsPerThreadgroup() / simd_size) * simd_size; + size_t needed = + (axis_size + CROSS_ENTROPY_N_READS - 1) / CROSS_ENTROPY_N_READS; + size_t threadgroup_size = std::clamp( + ((needed + simd_size - 1) / simd_size) * simd_size, simd_size, tg_max); + return { + MTL::Size(n_rows * threadgroup_size, 1, 1), + MTL::Size(threadgroup_size, 1, 1)}; +} + +array ensure_row_contiguous( + const array& x, + metal::CommandEncoder& encoder, + const Stream& s) { + if (x.flags().row_contiguous) { + return x; + } + array x_copy = contiguous_copy_gpu(x, s); + encoder.add_temporary(x_copy); + return x_copy; +} + +} // namespace + +bool CrossEntropy::use_fallback(Stream s) { + return s.device == Device::cpu; +} + +void CrossEntropy::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + assert(inputs.size() == 2); + auto& in_pre = inputs[0]; + auto& out = outputs[0]; + if (in_pre.size() == 0) { + throw std::invalid_argument("[cross_entropy] Received empty array."); + } + + auto& s = stream(); + auto& d = metal::device(s.device); + auto& compute_encoder = metal::get_command_encoder(s); + + auto in = ensure_row_contiguous(in_pre, compute_encoder, s); + auto targets = ensure_row_contiguous(inputs[1], compute_encoder, s); + out.set_data(allocator::malloc(out.nbytes())); + + int axis_size = in.shape().back(); + int n_rows = in.data_size() / axis_size; + + std::string kernel_name = "cross_entropy_" + type_to_name(in); + auto kernel = get_cross_entropy_kernel(d, kernel_name, in); + auto [grid_dims, group_dims] = cross_entropy_dims(kernel, axis_size, n_rows); + + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(in, 0); + compute_encoder.set_input_array(targets, 1); + compute_encoder.set_output_array(out, 2); + compute_encoder.set_bytes(axis_size, 3); + compute_encoder.dispatch_threads(grid_dims, group_dims); +} + +void CrossEntropyVJP::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + assert(inputs.size() == 4); + auto& in_pre = inputs[0]; + auto& out = outputs[0]; + if (in_pre.size() == 0) { + throw std::invalid_argument("[cross_entropy] Received empty array."); + } + + auto& s = stream(); + auto& d = metal::device(s.device); + auto& compute_encoder = metal::get_command_encoder(s); + + bool donate_in = in_pre.is_donatable() || !in_pre.flags().row_contiguous; + auto in = ensure_row_contiguous(in_pre, compute_encoder, s); + auto targets = ensure_row_contiguous(inputs[1], compute_encoder, s); + auto loss = ensure_row_contiguous(inputs[2], compute_encoder, s); + auto cotan = ensure_row_contiguous(inputs[3], compute_encoder, s); + if (donate_in) { + out.copy_shared_buffer(in); + } else { + out.set_data(allocator::malloc(out.nbytes())); + } + + int axis_size = in.shape().back(); + int n_rows = in.data_size() / axis_size; + + std::string kernel_name = "cross_entropy_vjp_" + type_to_name(in); + auto kernel = get_cross_entropy_kernel(d, kernel_name, in); + auto [grid_dims, group_dims] = cross_entropy_dims(kernel, axis_size, n_rows); + + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(in, 0); + compute_encoder.set_input_array(targets, 1); + compute_encoder.set_input_array(loss, 2); + compute_encoder.set_input_array(cotan, 3); + compute_encoder.set_output_array(out, 4); + compute_encoder.set_bytes(axis_size, 5); + compute_encoder.dispatch_threads(grid_dims, group_dims); +} + +} // namespace mlx::core::fast diff --git a/mlx/backend/metal/device.cpp b/mlx/backend/metal/device.cpp index 27c74ee397..22a23db6df 100644 --- a/mlx/backend/metal/device.cpp +++ b/mlx/backend/metal/device.cpp @@ -210,7 +210,7 @@ MTL::Library* load_default_library(MTL::Device* device) { return lib; } - NS::Error* error[5]; + NS::Error* error[6]; MTL::Library* lib; // First try the colocated mlx.metallib std::tie(lib, error[0]) = load_colocated_library(device, "mlx"); @@ -223,6 +223,22 @@ MTL::Library* load_default_library(MTL::Device* device) { return lib; } +#ifdef SWIFTPM_BUNDLE + // `swift test` with the default Swift Build build system nests resource + // bundles inside the .xctest and runs tests via the toolchain's + // swiftpm-testing-helper, so the running binary is the toolchain helper: + // neither Bundle.main nor Bundle.allBundles names the test bundle, and the + // SwiftPM bundle search below cannot reach it. In that layout the metallib + // sits at a fixed offset from the binary. + std::tie(lib, error[5]) = load_colocated_library( + device, + std::string("../Resources/") + SWIFTPM_BUNDLE + + ".bundle/Contents/Resources/default"); + if (lib) { + return lib; + } +#endif + // Then try default.metallib in a SwiftPM bundle if we have one std::tie(lib, error[2]) = load_swiftpm_library(device, "default"); if (lib) { @@ -241,7 +257,7 @@ MTL::Library* load_default_library(MTL::Device* device) { if (!lib) { std::ostringstream msg; msg << "Failed to load the default metallib. "; - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 6; i++) { if (error[i] != nullptr) { msg << error[i]->localizedDescription()->utf8String() << " "; } @@ -428,7 +444,7 @@ void CommandEncoder::barrier() { get_command_encoder()->memoryBarrier(MTL::BarrierScopeBuffers); } -void CommandEncoder::end_encoding() { +void CommandEncoder::end_encoding(bool wait_in_flight) { // Each command encoder has a unique fence. We also store a map of // all previous outputs of command encoders to their corresponding fence. // - The command encoder records its inputs and outputs. @@ -465,6 +481,16 @@ void CommandEncoder::end_encoding() { } } } + // A spin wait must start after all earlier encoders, as it might block + // earlier operations to be finished. + // See https://github.com/ml-explore/mlx/pull/4689 + if (wait_in_flight) { + for (auto& [_, fence] : prev_ce_outputs_) { + if (waiting_on.insert(fence).second) { + encoder_->waitForFence(fence.get()); + } + } + } for (auto& out : all_outputs_) { prev_ce_outputs_[out] = fence_; } @@ -1010,8 +1036,13 @@ CommandEncoder& get_command_encoder(Stream s) { } std::unordered_map& get_command_encoders() { - static thread_local std::unordered_map encoders; - return encoders; + if (is_main_thread()) { + static auto* encoders = new std::unordered_map(); + return *encoders; + } else { + static thread_local std::unordered_map encoders; + return encoders; + } } std::unordered_map& get_global_command_encoders() { diff --git a/mlx/backend/metal/device.h b/mlx/backend/metal/device.h index 3f2fd3f4ef..929458471f 100644 --- a/mlx/backend/metal/device.h +++ b/mlx/backend/metal/device.h @@ -63,8 +63,13 @@ class MLX_API CommandEncoder { template >> void set_vector_bytes(const Vec& vec, size_t nelems, int idx) { - get_command_encoder()->setBytes( - vec.data(), nelems * sizeof(typename Vec::value_type), idx); + using T = typename Vec::value_type; + if (nelems > 0) { + get_command_encoder()->setBytes(vec.data(), nelems * sizeof(T), idx); + } else { + T val{}; + get_command_encoder()->setBytes(&val, sizeof(T), idx); + } } template >> void set_vector_bytes(const Vec& vec, int idx) { @@ -90,7 +95,7 @@ class MLX_API CommandEncoder { } void barrier(); - void end_encoding(); + void end_encoding(bool wait_in_flight = false); void wait_event(Event event, uint64_t value); void signal_event(Event event, uint64_t value); bool needs_commit() const; diff --git a/mlx/backend/metal/fence.cpp b/mlx/backend/metal/fence.cpp index 70dd0e33bd..819e2bb1b2 100644 --- a/mlx/backend/metal/fence.cpp +++ b/mlx/backend/metal/fence.cpp @@ -1,5 +1,8 @@ // Copyright © 2024 Apple Inc. #include "mlx/fence.h" + +#include + #include "mlx/backend/metal/device.h" #include "mlx/scheduler.h" #include "mlx/utils.h" @@ -18,25 +21,22 @@ struct FenceImpl { if (!use_fast) { event = std::make_unique(stream); } else { - auto buf = allocator::malloc(sizeof(uint32_t)).ptr(); - fence = static_cast(buf); + fence.emplace(allocator::malloc(sizeof(uint32_t))); cpu_value()[0] = 0; } } - ~FenceImpl() { - if (use_fast) { - allocator::free(allocator::Buffer{static_cast(fence)}); - } - } bool use_fast{false}; uint32_t count{0}; - void* fence; + std::optional fence; std::unique_ptr event; + MTL::Buffer* buffer() { + return static_cast(fence->buffer().ptr()); + } + std::atomic_uint* cpu_value() { - return static_cast( - static_cast(fence)->contents()); + return static_cast(buffer()->contents()); } }; @@ -44,18 +44,20 @@ Fence::Fence(Stream stream) { fence_ = std::make_shared(stream); } -void Fence::wait(Stream stream, const array& x) { +void Fence::wait(Stream stream, const array& x, uint32_t value) { auto& f = *static_cast(fence_.get()); if (!f.use_fast) { - f.event->wait(stream); + auto& event = *f.event; + event.set_value(value); + event.wait(stream); return; } if (stream.device == Device::cpu) { - scheduler::enqueue(stream, [fence_ = fence_, count = f.count]() mutable { + scheduler::enqueue(stream, [fence_ = fence_, value]() mutable { auto& f = *static_cast(fence_.get()); - while (f.cpu_value()[0] < count) { + while (f.cpu_value()[0] < value) { } }); return; @@ -64,6 +66,8 @@ void Fence::wait(Stream stream, const array& x) { auto& d = metal::device(stream.device); auto& compute_encoder = metal::get_command_encoder(stream); + compute_encoder.end_encoding(); + // Register outputs to ensure that no kernels which depends on the // output starts before this one is done compute_encoder.register_output_array(x); @@ -72,23 +76,23 @@ void Fence::wait(Stream stream, const array& x) { MTL::Size kernel_dims = MTL::Size(1, 1, 1); compute_encoder.set_compute_pipeline_state(kernel); - auto buf = static_cast(f.fence); - compute_encoder.set_buffer(buf, 0); - compute_encoder.set_bytes(f.count, 1); + compute_encoder.set_buffer(f.buffer(), 0); + compute_encoder.set_bytes(value, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims); + compute_encoder.end_encoding(true); compute_encoder.get_command_buffer()->addCompletedHandler( [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); } -void Fence::update(Stream stream, const array& x, bool cross_device) { +uint32_t Fence::update(Stream stream, const array& x, bool cross_device) { auto& f = *static_cast(fence_.get()); f.count++; if (!f.use_fast) { f.event->set_value(f.count); f.event->signal(stream); - return; + return f.count; } if (stream.device == Device::cpu) { @@ -96,7 +100,7 @@ void Fence::update(Stream stream, const array& x, bool cross_device) { auto& f = *static_cast(fence_.get()); f.cpu_value()[0] = count; }); - return; + return f.count; } auto& d = metal::device(stream.device); @@ -123,13 +127,13 @@ void Fence::update(Stream stream, const array& x, bool cross_device) { MTL::Size kernel_dims = MTL::Size(1, 1, 1); compute_encoder.set_compute_pipeline_state(kernel); - auto buf = static_cast(f.fence); - compute_encoder.set_buffer(buf, 0); + compute_encoder.set_buffer(f.buffer(), 0); compute_encoder.set_bytes(f.count, 1); compute_encoder.dispatch_threads(kernel_dims, kernel_dims); compute_encoder.get_command_buffer()->addCompletedHandler( [fence_ = fence_](MTL::CommandBuffer* cbuf) {}); + return f.count; } } // namespace mlx::core diff --git a/mlx/backend/metal/fft.cpp b/mlx/backend/metal/fft.cpp index 3c9195f8ea..c3c214ac80 100644 --- a/mlx/backend/metal/fft.cpp +++ b/mlx/backend/metal/fft.cpp @@ -542,7 +542,11 @@ void fft_op( size_t n = out.dtype() == float32 ? out.shape(axis) : in.shape(axis); if (n == 1) { - out.copy_shared_buffer(in); + if (in.dtype() == out.dtype()) { + out.copy_shared_buffer(in); + } else { + copy_gpu(in, out, CopyType::General, s); + } return; } diff --git a/mlx/backend/metal/gated_delta_update.cpp b/mlx/backend/metal/gated_delta_update.cpp new file mode 100644 index 0000000000..2a3c3b1f35 --- /dev/null +++ b/mlx/backend/metal/gated_delta_update.cpp @@ -0,0 +1,520 @@ +// Copyright © 2026 Apple Inc. +#include + +#include "mlx/backend/common/compiled.h" +#include "mlx/backend/gpu/copy.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/kernels.h" +#include "mlx/backend/metal/kernels/defines.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/fast_primitives.h" +#include "mlx/utils.h" + +namespace mlx::core::fast { + +namespace { + +inline int gated_delta_chunk_size(int T) { + const bool nax = metal::is_nax_available(); + const int C = env::get_var("GATED_DELTA_CHUNK", T > 8 ? (nax ? 16 : 8) : 1); + return (C == 16 && !nax) ? 8 : C; +} + +inline int gated_delta_chunk_size_vjp() { + const bool nax = metal::is_nax_available(); + return nax ? env::get_var("GATED_DELTA_CHUNK_VJP", 16) : 1; +} + +inline int gated_delta_ckpt(int chunk) { + int c = env::get_var("GATED_DELTA_CKPT", 16); + if (c != 1 && c != 4 && c != 8 && c != 16) { + c = 16; + } + return (chunk == 16) ? c : 1; +} + +inline int gated_delta_n_ckpt(int n_chunks, int ckpt) { + return (n_chunks + ckpt - 1) / ckpt; +} + +bool supported_gated_delta_shape(int Hk, int Dk, int Hv, int Dv) { + if (Dk != 128 || Dv != 128) { + return false; + } + return (Hk == 24 && Hv == 24) || (Hk == 32 && Hv == 32) || + (Hk == 16 && Hv == 32) || (Hk == 16 && Hv == 48) || + (Hk == 16 && Hv == 16) || (Hk == 16 && Hv == 64); +} + +array ensure_row_contiguous(const array& x, metal::Device& d, const Stream& s) { + if (!x.flags().row_contiguous) { + array x_copy = contiguous_copy_gpu(x, s); + metal::get_command_encoder(s).add_temporary(x_copy); + return x_copy; + } else { + return x; + } +} + +array scratch_alloc(Shape shape, Dtype dt, const Stream& s) { + array a(std::move(shape), dt, nullptr, {}); + a.set_data(allocator::malloc(a.nbytes())); + metal::get_command_encoder(s).add_temporary(a); + return a; +} + +} // namespace + +bool GatedDeltaUpdate::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + const bool has_mask, + Stream s) { + if (s.device == Device::cpu) { + return true; + } + if (has_mask) { + return true; + } + return !supported_gated_delta_shape(Hk, Dk, Hv, Dv); +} + +void GatedDeltaUpdate::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + auto& s = stream(); + auto& d = metal::device(s.device); + + auto q = ensure_row_contiguous(inputs[0], d, s); + auto k = ensure_row_contiguous(inputs[1], d, s); + auto v = ensure_row_contiguous(inputs[2], d, s); + auto g = ensure_row_contiguous(inputs[3], d, s); + auto beta = ensure_row_contiguous(inputs[4], d, s); + auto h0 = ensure_row_contiguous(inputs[5], d, s); + + auto& out = outputs[0]; + auto& hf = outputs[1]; + + int B = q.shape(0); + int T = q.shape(1); + int Hk = q.shape(2); + int Dk = q.shape(3); + int Hv = v.shape(2); + int Dv = v.shape(3); + + int C = gated_delta_chunk_size(T); + const int ckpt = gated_delta_ckpt(C); + + std::string suffix = get_type_string(q.dtype()) + "_" + std::to_string(Dk) + + "_" + std::to_string(Dv) + "_" + std::to_string(Hk) + "_" + + std::to_string(Hv); + + auto& compute_encoder = metal::get_command_encoder(s); + + out.set_data(allocator::malloc(out.nbytes())); + hf.set_data(allocator::malloc(hf.nbytes())); + + array zero(0, out.dtype()); + compute_encoder.add_temporary(zero); + fill_gpu(zero, out, s); + + // The forward is inference-only here: the vjp runs its own save pass. The + // kernel declares buffers 9, 10 and 11 unconditionally, so bind a placeholder + // and turn the stores off with the function constant. + bool save_state = false; + metal::MTLFCList func_consts = { + {&save_state, MTL::DataType::DataTypeBool, 200}, + }; + + array dummy = scratch_alloc({1}, float32, s); + + switch (C) { + case 16: { + std::string base_name = "gated_delta_fused_nax_" + suffix + "_" + + std::to_string(C) + "_" + std::to_string(ckpt); + + auto delta_kernel = get_gated_delta_nax_kernel( + d, base_name, base_name, func_consts, q, Dk, Dv, Hk, Hv, C, ckpt); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(h0, 3); // initial state in + compute_encoder.set_input_array(g, 4); + compute_encoder.set_input_array(beta, 5); + compute_encoder.set_output_array(out, 6); + compute_encoder.set_output_array(hf, 7); // final state out + compute_encoder.set_bytes(T, 8); + compute_encoder.set_output_array(dummy, 9); // state_cache + compute_encoder.set_output_array(dummy, 10); // chunk_mats + compute_encoder.set_output_array(dummy, 11); // chunk_delta + + auto grid = MTL::Size(32, Dv / 16, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + break; + } + case 8: { + std::string base_name = + "gated_delta_fused_chunk_" + suffix + "_" + std::to_string(C); + + auto delta_kernel = + get_gated_delta_kernel(d, base_name, base_name, func_consts); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(h0, 3); // initial state in + compute_encoder.set_input_array(g, 4); + compute_encoder.set_input_array(beta, 5); + compute_encoder.set_output_array(out, 6); + compute_encoder.set_output_array(hf, 7); // final state out + compute_encoder.set_bytes(T, 8); + + auto grid = MTL::Size(32, Dv / 8, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + break; + } + case 1: + case 0: { + // Ckpt is a template parameter now, so even the inference path has to + // name one; it just never stores. + std::string base_name = + "seq_gated_delta_" + suffix + "_" + std::to_string(ckpt); + + auto delta_kernel = + get_gated_delta_kernel(d, base_name, base_name, func_consts); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + + // Order must match the kernel signature: state_in is slot 3, g is 4. + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(h0, 3); + compute_encoder.set_input_array(g, 4); + compute_encoder.set_input_array(beta, 5); + compute_encoder.set_output_array(out, 6); + compute_encoder.set_output_array(hf, 7); + compute_encoder.set_bytes(T, 8); + // Slot 9 is gated off by the function constant, so it stays unbound. + + auto grid = MTL::Size(32, Dv, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + break; + } + default: { + throw std::runtime_error( + "NYI: Only sequential and chunk size 8,16 are supported"); + } + } +} + +///////////////////////// +// BACKWARD PASS STUFF // +///////////////////////// +bool GatedDeltaUpdateVJP::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + Stream s) { + if (s.device == Device::cpu) { + return true; + } + if (env::get_var("GATED_DELTA_VJP_FALLBACK", 0) != 0) { + return true; + } + return !supported_gated_delta_shape(Hk, Dk, Hv, Dv); +} + +void GatedDeltaUpdateVJP::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + // Inputs are q, k, v, g, b, h0, cot_o, cot_h + // Outputs are dq, dk, dv, dg, db, dh0 + auto& s = stream(); + auto& d = metal::device(s.device); + + auto q = ensure_row_contiguous(inputs[0], d, s); + auto k = ensure_row_contiguous(inputs[1], d, s); + auto v = ensure_row_contiguous(inputs[2], d, s); + auto g = ensure_row_contiguous(inputs[3], d, s); + auto beta = ensure_row_contiguous(inputs[4], d, s); + auto h0 = ensure_row_contiguous(inputs[5], d, s); + auto cot_o = ensure_row_contiguous(inputs[6], d, s); + auto cot_h = ensure_row_contiguous(inputs[7], d, s); + + int B = q.shape(0); + int T = q.shape(1); + int Hk = q.shape(2); + int Dk = q.shape(3); + int Hv = v.shape(2); + int Dv = v.shape(3); + + // 16 = chunked NAX, anything else = sequential. + int C = gated_delta_chunk_size_vjp(); + const bool chunked = (C == 16); + + const int n_chunks = (T + 15) / 16; + const int ckpt = gated_delta_ckpt(C); + const int n_states = chunked ? gated_delta_n_ckpt(n_chunks, ckpt) : T; + + auto& dq = outputs[0]; + auto& dk = outputs[1]; + auto& dv = outputs[2]; + auto& dg = outputs[3]; + auto& db = outputs[4]; + auto& dh = outputs[5]; + + auto& compute_encoder = metal::get_command_encoder(s); + + dq.set_data(allocator::malloc(dq.nbytes())); + dk.set_data(allocator::malloc(dk.nbytes())); + dv.set_data(allocator::malloc(dv.nbytes())); + dg.set_data(allocator::malloc(dg.nbytes())); + db.set_data(allocator::malloc(db.nbytes())); + dh.set_data(allocator::malloc(dh.nbytes())); + + // The kernels accumulate their gradients as fp32, so we may need a cast. + const bool stage_fp32 = (q.dtype() != float32); + + auto dq_acc = stage_fp32 ? scratch_alloc(dq.shape(), float32, s) : dq; + auto dk_acc = stage_fp32 ? scratch_alloc(dk.shape(), float32, s) : dk; + auto dv_acc = stage_fp32 ? scratch_alloc(dv.shape(), float32, s) : dv; + auto dg_acc = stage_fp32 ? scratch_alloc(dg.shape(), float32, s) : dg; + auto db_acc = stage_fp32 ? scratch_alloc(db.shape(), float32, s) : db; + + array zero(0, float32); + array zero_h(0, dh.dtype()); + compute_encoder.add_temporary(zero); + compute_encoder.add_temporary(zero_h); + fill_gpu(zero, dq_acc, s); + fill_gpu(zero, dk_acc, s); + fill_gpu(zero, dv_acc, s); + fill_gpu(zero, dg_acc, s); + fill_gpu(zero, db_acc, s); + fill_gpu(zero_h, dh, s); + + array state_cache = scratch_alloc({B, Hv, n_states, Dv, Dk}, float32, s); + array seg_states = scratch_alloc( + chunked ? Shape({B, Hv, ckpt, Dv, Dk}) : Shape({1}), float32, s); + array chunk_mats = scratch_alloc( + chunked ? Shape({B, Hv, n_chunks, 3, 16, 16}) : Shape({1}), float32, s); + array chunk_delta = scratch_alloc( + chunked ? Shape({B, Hv, n_chunks, 16, Dv}) : Shape({1}), float32, s); + + if (chunked) { + fill_gpu(zero, state_cache, s); + fill_gpu(zero, chunk_mats, s); + fill_gpu(zero, chunk_delta, s); + } + + array y_scratch = scratch_alloc({B, T, Hv, Dv}, q.dtype(), s); + array hf_scratch = scratch_alloc({B, Hv, Dv, Dk}, float32, s); + + std::string suffix = get_type_string(q.dtype()) + "_" + std::to_string(Dk) + + "_" + std::to_string(Dv) + "_" + std::to_string(Hk) + "_" + + std::to_string(Hv); + + bool save_state = true; + metal::MTLFCList save_consts = { + {&save_state, MTL::DataType::DataTypeBool, 200}, + }; + metal::MTLFCList no_consts = {}; + + switch (C) { + case 16: { + const std::string ckpt_suffix = + "_" + std::to_string(C) + "_" + std::to_string(ckpt); + + // Forward save pass. + { + std::string base_name = "gated_delta_fused_nax_" + suffix + ckpt_suffix; + + auto delta_kernel = get_gated_delta_nax_kernel( + d, + base_name, + base_name + "_save", + save_consts, + q, + Dk, + Dv, + Hk, + Hv, + C, + ckpt); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(h0, 3); + compute_encoder.set_input_array(g, 4); + compute_encoder.set_input_array(beta, 5); + compute_encoder.set_output_array(y_scratch, 6); + compute_encoder.set_output_array(hf_scratch, 7); + compute_encoder.set_bytes(T, 8); + compute_encoder.set_output_array(state_cache, 9); + compute_encoder.set_output_array(chunk_mats, 10); + compute_encoder.set_output_array(chunk_delta, 11); + + auto grid = MTL::Size(32, Dv / 16, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + } + + { + std::string base_name = + "gated_delta_vjp_fused_nax_" + suffix + ckpt_suffix; + + auto delta_kernel = get_gated_delta_vjp_nax_kernel( + d, + base_name, + base_name, + no_consts, + q, + Dk, + Dv, + Hk, + Hv, + C, + ckpt, + false); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(g, 3); + compute_encoder.set_input_array(beta, 4); + compute_encoder.set_input_array(cot_o, 5); + compute_encoder.set_input_array(cot_h, 6); + compute_encoder.set_input_array(state_cache, 7); + compute_encoder.set_bytes(T, 8); + compute_encoder.set_output_array(dq_acc, 9); + compute_encoder.set_output_array(dk_acc, 10); + compute_encoder.set_output_array(dv_acc, 11); + compute_encoder.set_output_array(dg_acc, 12); + compute_encoder.set_output_array(db_acc, 13); + compute_encoder.set_output_array(dh, 14); + compute_encoder.set_input_array(chunk_mats, 15); + compute_encoder.set_input_array(chunk_delta, 16); + compute_encoder.set_output_array(seg_states, 17); + + auto grid = MTL::Size(32, Dv / 16, B * Hv); + auto threads = MTL::Size(32, Dv / 16, 1); + compute_encoder.dispatch_threads(grid, threads); + } + + { + int n_total = B * Hv; + + std::string base_name = "gated_delta_dgamma_to_dg_" + + get_type_string(q.dtype()) + "_" + std::to_string(C); + + auto dgamma_kernel = get_gated_delta_vjp_nax_kernel( + d, + base_name, + base_name, + no_consts, + q, + Dk, + Dv, + Hk, + Hv, + C, + ckpt, + true); + + compute_encoder.set_compute_pipeline_state(dgamma_kernel); + compute_encoder.set_input_array(g, 0); + compute_encoder.set_output_array(dg_acc, 1); + compute_encoder.set_bytes(T, 2); + compute_encoder.set_bytes(Hv, 3); + compute_encoder.set_bytes(n_total, 4); + + auto grid = MTL::Size(n_total, n_chunks, 1); + auto threads = MTL::Size(std::min(n_total, 32), 1, 1); + compute_encoder.dispatch_threads(grid, threads); + } + break; + } + case 1: + case 0: { + const std::string ckpt_suffix = "_" + std::to_string(ckpt); + + { + std::string base_name = "seq_gated_delta_" + suffix + ckpt_suffix; + + auto delta_kernel = get_gated_delta_kernel( + d, base_name, base_name + "_save", save_consts); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(h0, 3); + compute_encoder.set_input_array(g, 4); + compute_encoder.set_input_array(beta, 5); + compute_encoder.set_output_array(y_scratch, 6); + compute_encoder.set_output_array(hf_scratch, 7); + compute_encoder.set_bytes(T, 8); + compute_encoder.set_output_array(state_cache, 9); + + auto grid = MTL::Size(32, Dv, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + } + + { + std::string base_name = "seq_gated_delta_vjp_" + suffix + ckpt_suffix; + + auto delta_kernel = + get_gated_delta_vjp_kernel(d, base_name, base_name, no_consts); + + compute_encoder.set_compute_pipeline_state(delta_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_input_array(g, 3); + compute_encoder.set_input_array(beta, 4); + compute_encoder.set_input_array(cot_o, 5); + compute_encoder.set_input_array(cot_h, 6); + compute_encoder.set_input_array(state_cache, 7); + compute_encoder.set_bytes(T, 8); + compute_encoder.set_output_array(dq_acc, 9); + compute_encoder.set_output_array(dk_acc, 10); + compute_encoder.set_output_array(dv_acc, 11); + compute_encoder.set_output_array(dg_acc, 12); + compute_encoder.set_output_array(db_acc, 13); + compute_encoder.set_output_array(dh, 14); + + auto grid = MTL::Size(32, Dv, B * Hv); + auto threads = MTL::Size(32, 4, 1); + compute_encoder.dispatch_threads(grid, threads); + } + break; + } + default: { + throw std::runtime_error( + "NYI: Only sequential and chunk size 16 are supported for vjp"); + } + } + + if (stage_fp32) { + copy_gpu(dq_acc, dq, CopyType::General, s); + copy_gpu(dk_acc, dk, CopyType::General, s); + copy_gpu(dv_acc, dv, CopyType::General, s); + copy_gpu(dg_acc, dg, CopyType::General, s); + copy_gpu(db_acc, db, CopyType::General, s); + } +} + +} // namespace mlx::core::fast diff --git a/mlx/backend/metal/indexing.cpp b/mlx/backend/metal/indexing.cpp index 117e402f7b..2a74576664 100644 --- a/mlx/backend/metal/indexing.cpp +++ b/mlx/backend/metal/indexing.cpp @@ -38,6 +38,12 @@ std::pair make_index_args( return {idx_args.str(), idx_arr.str()}; } +// The 64-bit path must cover both the logical size and the span reachable +// through the strides (views) or a smaller span (broadcast arrays). +inline bool exceeds_int32(const array& a) { + return a.size() > INT32_MAX || a.data_size() > INT32_MAX; +} + template inline std::string make_op(typename T::ReduceType r, const std::string& dt) { switch (r) { @@ -78,8 +84,11 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { slice_size *= s; } - bool large_index = nidx && inputs[1].size() > INT32_MAX; - bool large_src = src.size() > INT32_MAX; + bool large_index = false; + for (int i = 1; i <= nidx; ++i) { + large_index |= exceeds_int32(inputs[i]); + } + bool large_src = exceeds_int32(src); bool large_out = out.size() > INT32_MAX; bool large = large_index || large_src || large_out; @@ -212,9 +221,6 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { compute_encoder.set_vector_bytes(axes_, 6); // Set index info - // - // We don't need to check for empty idx_shapes because gather has a - // idx_ndim == 0 specialization compute_encoder.set_vector_bytes(idx_shapes, 7); compute_encoder.set_vector_bytes(idx_strides, 8); compute_encoder.set_vector_bytes(idx_contigs, 9); @@ -305,8 +311,11 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { } auto upd_contig = upd.flags().row_contiguous; bool large_out = out.size() > INT32_MAX; - bool large_idx = nidx && (inputs[1].size() > INT32_MAX); - bool large_upd = upd.size() > INT32_MAX; + bool large_idx = false; + for (int i = 1; i <= nidx; ++i) { + large_idx |= exceeds_int32(inputs[i]); + } + bool large_upd = exceeds_int32(upd); bool large = large_out || large_idx || large_upd; std::string kernel_name = fmt::format( "scatter{0}{1}_{2}_{3}_{4}_nwork{5}_{6}", @@ -379,42 +388,19 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { idx_contigs.push_back(inputs[i + 1].flags().row_contiguous); } - if (upd_ndim == 0) { - // Need placeholders so Metal doesn't complain - int shape_ = 0; - int64_t stride_ = 0; - compute_encoder.set_bytes(shape_, 3); - compute_encoder.set_bytes(stride_, 4); - } else { - compute_encoder.set_vector_bytes(upd.shape(), 3); - compute_encoder.set_vector_bytes(upd.strides(), 4); - } + compute_encoder.set_vector_bytes(upd.shape(), 3); + compute_encoder.set_vector_bytes(upd.strides(), 4); compute_encoder.set_bytes(upd_ndim, 5); compute_encoder.set_bytes(upd_size, 6); // Set output info size_t out_ndim = out.ndim(); - if (out_ndim == 0) { - // Need placeholders so Metal doesn't complain - int shape_ = 0; - int64_t stride_ = 0; - compute_encoder.set_bytes(shape_, 7); - compute_encoder.set_bytes(stride_, 8); - } else { - compute_encoder.set_vector_bytes(out.shape(), 7); - compute_encoder.set_vector_bytes(out.strides(), 8); - } + compute_encoder.set_vector_bytes(out.shape(), 7); + compute_encoder.set_vector_bytes(out.strides(), 8); compute_encoder.set_bytes(out_ndim, 9); - compute_encoder.set_vector_bytes(axes_, 10); // Set index info - if (idx_ndim == 0) { - // Add a 0 in idx_shapes and strides to avoid the missing buffer binding - // error in the metal API. - idx_shapes.push_back(0); - idx_strides.push_back(0); - idx_contigs.push_back(false); - } + compute_encoder.set_vector_bytes(axes_, 10); compute_encoder.set_vector_bytes(idx_shapes, 11); compute_encoder.set_vector_bytes(idx_strides, 12); compute_encoder.set_vector_bytes(idx_contigs, 13); @@ -452,7 +438,7 @@ void GatherAxis::eval_gpu(const std::vector& inputs, array& out) { size_t ndim = src.ndim(); - bool large = idx.size() > INT32_MAX || src.size() > INT32_MAX; + bool large = exceeds_int32(idx) || exceeds_int32(src); std::string kernel_name = fmt::format( "gather_axis{0}{1}_{2}", @@ -552,7 +538,8 @@ void ScatterAxis::eval_gpu(const std::vector& inputs, array& out) { size_t ndim = src.ndim(); - bool large = idx.size() > INT32_MAX || src.size() > INT32_MAX; + bool large = + exceeds_int32(idx) || src.size() > INT32_MAX || exceeds_int32(upd); std::string op_name; switch (reduce_type_) { @@ -668,7 +655,9 @@ void MaskedScatter::eval_gpu(const std::vector& inputs, array& out) { return; } - array mask_flat = flatten_in_eval(mask, 1, -1, s); + array mask_flat = (mask.ndim() == 1) + ? reshape_in_eval(mask, {mask.shape(0), 1}, s) + : flatten_in_eval(mask, 1, -1, s); if (mask_flat.data() != mask.data()) { compute_encoder.add_temporary(mask_flat); } @@ -813,7 +802,7 @@ void SliceUpdate::eval_gpu(const std::vector& inputs, array& out) { auto [ds, rc, cc] = check_contiguity(shape, strides[1]); bool out_contiguous = rc; - bool large = upd.size() > INT32_MAX; + bool large = exceeds_int32(upd); std::string kernel_name = fmt::format( "slice_update_{0}_{1}{2}_{3}_{4}_{5}_nw{6}_nd{7}", op_name, diff --git a/mlx/backend/metal/jit/includes.h b/mlx/backend/metal/jit/includes.h index 4fb1be1110..8ad0a9ca7c 100644 --- a/mlx/backend/metal/jit/includes.h +++ b/mlx/backend/metal/jit/includes.h @@ -18,6 +18,7 @@ const char* unary(); const char* binary(); const char* binary_two(); const char* copy(); +const char* cross_entropy(); const char* fft(); const char* gather_axis(); const char* gather_front(); @@ -53,10 +54,15 @@ const char* steel_gemm_fused_nax(); const char* steel_gemm_gather_nax(); const char* steel_gemm_splitk_nax(); const char* steel_gemm_segmented_nax(); +const char* steel_gemm_thin_nax(); const char* quantized_nax(); const char* fp_quantized_nax(); const char* steel_attention_nax(); +const char* gated_delta_update(); +const char* gated_delta_update_nax(); +const char* gated_delta_update_nax_vjp(); + } // namespace mlx::core::metal diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index 8dfe30a15c..aad94eba1e 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -30,6 +30,9 @@ const char* steel_gemm_splitk_nax() { const char* steel_gemm_segmented_nax() { return ""; } +const char* steel_gemm_thin_nax() { + return ""; +} const char* quantized_nax() { return ""; } @@ -39,6 +42,12 @@ const char* fp_quantized_nax() { const char* steel_attention_nax() { return ""; } +const char* gated_delta_update_nax() { + return ""; +} +const char* gated_delta_update_nax_vjp() { + return ""; +} } // namespace metal #endif // MLX_METAL_NO_NAX @@ -360,6 +369,26 @@ MTL::ComputePipelineState* get_logsumexp_kernel( return d.get_kernel(kernel_name, lib); } +MTL::ComputePipelineState* get_cross_entropy_kernel( + metal::Device& d, + const std::string& kernel_name, + const array& in) { + // Both kernels live in one library, so the name is not derived from + // kernel_name. + std::string lib_name = "cross_entropy_" + type_to_name(in); + auto lib = d.get_library(lib_name, [&] { + auto t_str = get_type_string(in.dtype()); + std::string kernel_source = metal::utils(); + kernel_source += metal::cross_entropy(); + kernel_source += get_template_definition( + "cross_entropy_" + type_to_name(in), "cross_entropy", t_str); + kernel_source += get_template_definition( + "cross_entropy_vjp_" + type_to_name(in), "cross_entropy_vjp", t_str); + return kernel_source; + }); + return d.get_kernel(kernel_name, lib); +} + MTL::ComputePipelineState* get_scan_kernel( metal::Device& d, const std::string& kernel_name, @@ -1054,28 +1083,44 @@ MTL::ComputePipelineState* get_gather_qmm_kernel( int bk, int wm, int wn, - bool transpose) { + bool transpose, + bool has_global_scale) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { std::string kernel_source; concatenate( kernel_source, metal::utils(), metal::quantized_utils(), metal::gemm()); bool is_affine = mode == "affine"; + // Only the fp kernel takes a global scale. + auto template_def = is_affine ? get_template_definition( + lib_name, + "affine_gather_qmm_rhs", + get_type_string(x.dtype()), + group_size, + bits, + bm, + bn, + bk, + wm, + wn, + transpose) + : get_template_definition( + lib_name, + "fp_gather_qmm_rhs", + get_type_string(x.dtype()), + group_size, + bits, + bm, + bn, + bk, + wm, + wn, + transpose, + has_global_scale); concatenate( kernel_source, is_affine ? metal::quantized() : metal::fp_quantized(), - get_template_definition( - lib_name, - (is_affine ? "affine" : "fp") + std::string("_gather_qmm_rhs"), - get_type_string(x.dtype()), - group_size, - bits, - bm, - bn, - bk, - wm, - wn, - transpose)); + template_def); return kernel_source; }); return d.get_kernel(kernel_name, lib, hash_name, func_consts); @@ -1221,6 +1266,25 @@ MTL::ComputePipelineState* get_steel_gemm_segmented_nax_kernel( return d.get_kernel(kernel_name, lib, hash_name, func_consts); } +MTL::ComputePipelineState* get_steel_gemm_thin_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const std::string& template_def) { + auto lib = d.get_library(kernel_name, [&]() { + std::string kernel_source; + concatenate( + kernel_source, + metal::utils(), + metal::gemm_nax(), + metal::steel_gemm_thin_nax(), + template_def); + return kernel_source; + }); + return d.get_kernel(kernel_name, lib, hash_name, func_consts); +} + MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, @@ -1255,7 +1319,8 @@ MTL::ComputePipelineState* get_gather_qmm_nax_kernel( int bk, int wm, int wn, - bool transpose) { + bool transpose, + bool has_global_scale) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { std::string kernel_source; @@ -1265,21 +1330,36 @@ MTL::ComputePipelineState* get_gather_qmm_nax_kernel( metal::gemm_nax(), metal::quantized_utils()); bool is_affine = mode == "affine"; + // Only the fp kernel takes a global scale. + auto template_def = is_affine ? get_template_definition( + lib_name, + "affine_gather_qmm_rhs_nax", + get_type_string(x.dtype()), + group_size, + bits, + bm, + bn, + bk, + wm, + wn, + transpose) + : get_template_definition( + lib_name, + "fp_gather_qmm_rhs_nax", + get_type_string(x.dtype()), + group_size, + bits, + bm, + bn, + bk, + wm, + wn, + transpose, + has_global_scale); concatenate( kernel_source, is_affine ? metal::quantized_nax() : metal::fp_quantized_nax(), - get_template_definition( - lib_name, - (is_affine ? "affine" : "fp") + std::string("_gather_qmm_rhs_nax"), - get_type_string(x.dtype()), - group_size, - bits, - bm, - bn, - bk, - wm, - wn, - transpose)); + template_def); return kernel_source; }); return d.get_kernel(kernel_name, lib, hash_name, func_consts); @@ -1294,6 +1374,7 @@ MTL::ComputePipelineState* get_steel_attention_kernel( int bq, int bk, int bd, + int bv, int wm, int wn, const array& m) { @@ -1311,6 +1392,7 @@ MTL::ComputePipelineState* get_steel_attention_kernel( bq, bk, bd, + bv, wm, wn, get_type_string(m.dtype()))); @@ -1328,6 +1410,7 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( int bq, int bk, int bd, + int bv, int wm, int wn, const array& m, @@ -1346,6 +1429,7 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( bq, bk, bd, + bv, wm, wn, get_type_string(m.dtype()))); @@ -1354,4 +1438,105 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( return d.get_kernel(kernel_name, lib, hash_name, func_consts); } +MTL::ComputePipelineState* get_sdpa_vjp_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_sdpa_vjp_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_vjp_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const array& q, + int dk, + int dv, + int hk, + int hv, + int c, + int ckpt) { + const auto& lib_name = kernel_name; + auto lib = d.get_library(lib_name, [&]() { + std::string kernel_source; + concatenate(kernel_source, metal::utils(), metal::gated_delta_update_nax()); + kernel_source += get_template_definition( + lib_name, + "gated_delta_fused_nax", + get_type_string(q.dtype()), + dk, + dv, + hk, + hv, + c, + ckpt); + return kernel_source; + }); + return d.get_kernel(kernel_name, lib, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_vjp_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const array& q, + int dk, + int dv, + int hk, + int hv, + int c, + int ckpt, + bool dgamma) { + const auto& lib_name = kernel_name; + auto lib = d.get_library(lib_name, [&]() { + std::string kernel_source; + concatenate( + kernel_source, metal::utils(), metal::gated_delta_update_nax_vjp()); + if (dgamma) { + kernel_source += get_template_definition( + lib_name, "gated_delta_dgamma_to_dg", get_type_string(q.dtype()), c); + } else { + kernel_source += get_template_definition( + lib_name, + "gated_delta_vjp_fused_nax", + get_type_string(q.dtype()), + dk, + dv, + hk, + hv, + c, + ckpt); + } + return kernel_source; + }); + return d.get_kernel(kernel_name, lib, hash_name, func_consts); +} + } // namespace mlx::core diff --git a/mlx/backend/metal/kernels.h b/mlx/backend/metal/kernels.h index 18a56ebf1b..ded6c834ab 100644 --- a/mlx/backend/metal/kernels.h +++ b/mlx/backend/metal/kernels.h @@ -64,6 +64,11 @@ MTL::ComputePipelineState* get_logsumexp_kernel( const std::string& kernel_name, const array& out); +MTL::ComputePipelineState* get_cross_entropy_kernel( + metal::Device& d, + const std::string& kernel_name, + const array& in); + MTL::ComputePipelineState* get_scan_kernel( metal::Device& d, const std::string& kernel_name, @@ -321,7 +326,8 @@ MTL::ComputePipelineState* get_gather_qmm_kernel( int bk, int wm, int wn, - bool transpose); + bool transpose, + bool has_global_scale); MTL::ComputePipelineState* get_steel_gemm_fused_nax_kernel( metal::Device& d, @@ -380,6 +386,13 @@ MTL::ComputePipelineState* get_steel_gemm_segmented_nax_kernel( int wm, int wn); +MTL::ComputePipelineState* get_steel_gemm_thin_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const std::string& template_def); + MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, @@ -400,7 +413,8 @@ MTL::ComputePipelineState* get_gather_qmm_nax_kernel( int bk, int wm, int wn, - bool transpose); + bool transpose, + bool has_global_scale); MTL::ComputePipelineState* get_steel_attention_kernel( metal::Device& d, @@ -411,6 +425,7 @@ MTL::ComputePipelineState* get_steel_attention_kernel( int bq, int bk, int bd, + int bv, int wm, int wn, const array& m); @@ -424,11 +439,51 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( int bq, int bk, int bd, + int bv, int wm, int wn, const array& m, bool split_d); +MTL::ComputePipelineState* get_gated_delta_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts); + +MTL::ComputePipelineState* get_gated_delta_vjp_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts); + +MTL::ComputePipelineState* get_gated_delta_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const array& q, + int dk, + int dv, + int hk, + int hv, + int c, + int ckpt); + +MTL::ComputePipelineState* get_gated_delta_vjp_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const array& q, + int dk, + int dv, + int hk, + int hv, + int c, + int ckpt, + bool dgamma); + // Create a GPU kernel template definition for JIT compilation template std::string get_template_definition( diff --git a/mlx/backend/metal/kernels/CMakeLists.txt b/mlx/backend/metal/kernels/CMakeLists.txt index 680e8f1b61..355c763a3a 100644 --- a/mlx/backend/metal/kernels/CMakeLists.txt +++ b/mlx/backend/metal/kernels/CMakeLists.txt @@ -55,7 +55,10 @@ build_kernel(layer_norm) build_kernel(random) build_kernel(rms_norm) build_kernel(rope) -build_kernel(scaled_dot_product_attention sdpa_vector.h) +build_kernel(scaled_dot_product_attention sdpa_blocked.h sdpa_vector.h) +build_kernel(scaled_dot_product_attention_vjp) +build_kernel(gated_delta_update gated_delta_update.h) +build_kernel(gated_delta_update_vjp gated_delta_update_vjp.h) if(MLX_METAL_VERSION GREATER_EQUAL 320) build_kernel(fence) endif() @@ -112,7 +115,8 @@ set(STEEL_NAX_HEADERS steel/gemm/kernels/steel_gemm_fused_nax.h steel/gemm/kernels/steel_gemm_gather_nax.h steel/gemm/kernels/steel_gemm_splitk_nax.h - steel/gemm/kernels/steel_gemm_segmented_nax.h) + steel/gemm/kernels/steel_gemm_segmented_nax.h + steel/gemm/kernels/steel_gemm_thin_nax.h) set(STEEL_NAX_ATTN_HEADERS steel/defines.h @@ -143,6 +147,7 @@ if(NOT MLX_METAL_JIT) build_kernel(scan scan.h) build_kernel(softmax softmax.h) build_kernel(logsumexp logsumexp.h) + build_kernel(cross_entropy cross_entropy.h) build_kernel(searchsorted searchsorted.h sort.h) build_kernel(sort sort.h) build_kernel(ternary ternary.h ternary_ops.h) @@ -168,8 +173,13 @@ if(NOT MLX_METAL_JIT) build_kernel(steel/gemm/kernels/steel_gemm_splitk_nax ${STEEL_NAX_HEADERS}) build_kernel(steel/gemm/kernels/steel_gemm_segmented_nax ${STEEL_NAX_HEADERS}) + build_kernel(steel/gemm/kernels/steel_gemm_thin_nax ${STEEL_NAX_HEADERS}) build_kernel(quantized_nax quantized_nax.h ${STEEL_NAX_HEADERS}) + build_kernel(gated_delta_update_nax gated_delta_update_nax.h + gated_delta_nax_ops.h ${STEEL_NAX_HEADERS}) + build_kernel(gated_delta_update_nax_vjp gated_delta_update_nax_vjp.h + gated_delta_nax_ops.h ${STEEL_NAX_HEADERS}) build_kernel(fp_quantized_nax fp4.h fp8.h fp_quantized_nax.h ${STEEL_NAX_HEADERS}) diff --git a/mlx/backend/metal/kernels/arg_reduce.metal b/mlx/backend/metal/kernels/arg_reduce.metal index 6ce20555f7..3ac51f1c93 100644 --- a/mlx/backend/metal/kernels/arg_reduce.metal +++ b/mlx/backend/metal/kernels/arg_reduce.metal @@ -1,11 +1,17 @@ // Copyright © 2023 Apple Inc. +#include #include #include "mlx/backend/metal/kernels/utils.h" using namespace metal; +template , bool> = true> +inline bool isnan(T) { + return false; +} + template struct IndexValPair { uint32_t index; @@ -17,8 +23,11 @@ struct ArgMin { static constexpr constant U init = Limits::max; IndexValPair reduce(IndexValPair best, IndexValPair current) thread { - if (best.val > current.val || - (best.val == current.val && best.index > current.index)) { + if ((isnan(current.val) && + (!isnan(best.val) || best.index > current.index)) || + (!isnan(best.val) && + (best.val > current.val || + (best.val == current.val && best.index > current.index)))) { return current; } else { return best; @@ -29,7 +38,7 @@ struct ArgMin { IndexValPair reduce_many(IndexValPair best, thread U* vals, uint32_t offset) thread { for (int i = 0; i < N; i++) { - if (vals[i] < best.val) { + if ((!isnan(best.val) && isnan(vals[i])) || vals[i] < best.val) { best.val = vals[i]; best.index = offset + i; } @@ -43,8 +52,11 @@ struct ArgMax { static constexpr constant U init = Limits::min; IndexValPair reduce(IndexValPair best, IndexValPair current) thread { - if (best.val < current.val || - (best.val == current.val && best.index > current.index)) { + if ((isnan(current.val) && + (!isnan(best.val) || best.index > current.index)) || + (!isnan(best.val) && + (best.val < current.val || + (best.val == current.val && best.index > current.index)))) { return current; } else { return best; @@ -55,7 +67,7 @@ struct ArgMax { IndexValPair reduce_many(IndexValPair best, thread U* vals, uint32_t offset) thread { for (int i = 0; i < N; i++) { - if (vals[i] > best.val) { + if ((!isnan(best.val) && isnan(vals[i])) || vals[i] > best.val) { best.val = vals[i]; best.index = offset + i; } diff --git a/mlx/backend/metal/kernels/binary.metal b/mlx/backend/metal/kernels/binary.metal index 17ed13c57f..475fd45ad6 100644 --- a/mlx/backend/metal/kernels/binary.metal +++ b/mlx/backend/metal/kernels/binary.metal @@ -73,6 +73,7 @@ instantiate_binary_types(Add) instantiate_binary_types(Divide) +instantiate_binary_types(FloorDivide) instantiate_binary_types_bool(Equal) instantiate_binary_types_bool(Greater) instantiate_binary_types_bool(GreaterEqual) diff --git a/mlx/backend/metal/kernels/binary_ops.h b/mlx/backend/metal/kernels/binary_ops.h index 3b8d2ebe4e..968087f8ef 100644 --- a/mlx/backend/metal/kernels/binary_ops.h +++ b/mlx/backend/metal/kernels/binary_ops.h @@ -41,19 +41,8 @@ struct FloorDivide { }; struct Divide { - // Integer Divide is floor_divide: round down, keep x / 0 unchanged. template - metal::enable_if_t & metal::is_signed_v, T> - operator()(T x, T y) thread { - auto q = x / y; - if (y != 0 && x % y != 0 && (x < 0) != (y < 0)) { - q -= 1; - } - return q; - } - template - metal::enable_if_t & metal::is_signed_v), T> - operator()(T x, T y) thread { + T operator()(T x, T y) thread { return x / y; } }; @@ -272,7 +261,7 @@ struct Power { return {0.0, 0.0}; } auto x_theta = metal::atan2(x.imag, x.real); - auto x_ln_r = 0.5 * metal::log(x.real * x.real + x.imag * x.imag); + auto x_ln_r = metal::log(hypot(x.real, x.imag)); auto mag = metal::exp(y.real * x_ln_r - y.imag * x_theta); auto phase = y.imag * x_ln_r + y.real * x_theta; return {mag * metal::cos(phase), mag * metal::sin(phase)}; diff --git a/mlx/backend/metal/kernels/complex.h b/mlx/backend/metal/kernels/complex.h index fe78e0050f..71a5fa4390 100644 --- a/mlx/backend/metal/kernels/complex.h +++ b/mlx/backend/metal/kernels/complex.h @@ -264,10 +264,20 @@ constexpr complex_t operator*(complex_t a, complex_t b) { template constexpr complex_t operator/(complex_t a, complex_t b) { - auto denom = b.real * b.real + b.imag * b.imag; - auto x = a.real * b.real + a.imag * b.imag; - auto y = a.imag * b.real - a.real * b.imag; - return {x / denom, y / denom}; + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; } template < @@ -275,11 +285,7 @@ template < typename U, enable_if_t && is_lane_convertible_v, bool> = true> constexpr complex_t operator/(U a, complex_t b) { - auto scalar = static_cast(a); - auto denom = b.real * b.real + b.imag * b.imag; - auto x = scalar * b.real; - auto y = -scalar * b.imag; - return {x / denom, y / denom}; + return complex_t(a) / b; } template diff --git a/mlx/backend/metal/kernels/conv.metal b/mlx/backend/metal/kernels/conv.metal index 6f3ce0cd43..a16ae8a275 100644 --- a/mlx/backend/metal/kernels/conv.metal +++ b/mlx/backend/metal/kernels/conv.metal @@ -418,8 +418,8 @@ winograd_conv_2d_weight_transform( // wt_out is stored transposed (A x A x C x O) short ohw_0 = sm * 8 + sn; short ohw_1 = sm * 8 + sn + 1; - device T* wt_out_0 = wt_out + ohw_0 * C * O + ko; - device T* wt_out_1 = wt_out + ohw_1 * C * O + ko; + device T* wt_out_0 = wt_out + size_t(ohw_0) * C * O + ko; + device T* wt_out_1 = wt_out + size_t(ohw_1) * C * O + ko; // Prepare shared memory threadgroup T Ws[BO][R][R][BC]; diff --git a/mlx/backend/metal/kernels/cross_entropy.h b/mlx/backend/metal/kernels/cross_entropy.h new file mode 100644 index 0000000000..bef0bce5f8 --- /dev/null +++ b/mlx/backend/metal/kernels/cross_entropy.h @@ -0,0 +1,133 @@ +// Copyright © 2026 Apple Inc. + +template < + typename T, + typename AccT = float, + int N_READS = CROSS_ENTROPY_N_READS> +[[kernel]] void cross_entropy( + const device T* in, + const device int32_t* targets, + device float* out, + constant int& axis_size, + uint gid [[threadgroup_position_in_grid]], + uint lid [[thread_position_in_threadgroup]], + uint lsize [[threads_per_threadgroup]], + uint simd_lane_id [[thread_index_in_simdgroup]], + uint simd_group_id [[simdgroup_index_in_threadgroup]]) { + in += gid * size_t(axis_size); + + constexpr int SIMD_SIZE = 32; + + threadgroup AccT local_max[SIMD_SIZE]; + threadgroup AccT local_normalizer[SIMD_SIZE]; + + int y_n = targets[gid]; + y_n = (y_n < 0) ? y_n + axis_size : y_n; + AccT x_t = AccT(in[y_n]); + + AccT prevmax; + AccT maxval = Limits::finite_min; + AccT normalizer = 0; + for (int r = 0; r < static_cast(ceildiv(axis_size, N_READS * lsize)); + r++) { + int offset = r * lsize * N_READS + lid * N_READS; + AccT vals[N_READS]; + if (offset + N_READS <= axis_size) { + for (int i = 0; i < N_READS; i++) { + vals[i] = AccT(in[offset + i]); + } + } else { + for (int i = 0; i < N_READS; i++) { + vals[i] = + (offset + i < axis_size) ? AccT(in[offset + i]) : Limits::min; + } + } + prevmax = maxval; + for (int i = 0; i < N_READS; i++) { + maxval = (maxval < vals[i]) ? vals[i] : maxval; + } + normalizer *= fast::exp(prevmax - maxval); + for (int i = 0; i < N_READS; i++) { + normalizer += fast::exp(vals[i] - maxval); + } + } + + prevmax = maxval; + maxval = simd_max(maxval); + normalizer *= fast::exp(prevmax - maxval); + normalizer = simd_sum(normalizer); + + uint n_simdgroups = ceildiv(lsize, uint(SIMD_SIZE)); + prevmax = maxval; + if (simd_lane_id == 0) { + local_max[simd_group_id] = maxval; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + maxval = (simd_lane_id < n_simdgroups) ? local_max[simd_lane_id] + : Limits::finite_min; + maxval = simd_max(maxval); + normalizer *= fast::exp(prevmax - maxval); + if (simd_lane_id == 0) { + local_normalizer[simd_group_id] = normalizer; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + normalizer = + (simd_lane_id < n_simdgroups) ? local_normalizer[simd_lane_id] : AccT(0); + normalizer = simd_sum(normalizer); + + if (lid == 0) { + // Subtract the two logits first; they are the same magnitude, so less is + // lost than in logsumexp - x_t. + AccT gap = maxval - x_t; + out[gid] = isinf(maxval) ? float(gap) : float(log(normalizer) + gap); + } +} + +template < + typename T, + typename AccT = float, + int N_READS = CROSS_ENTROPY_N_READS> +[[kernel]] void cross_entropy_vjp( + const device T* in, + const device int32_t* targets, + const device float* loss, + const device float* cotan, + device T* out, + constant int& axis_size, + uint gid [[threadgroup_position_in_grid]], + uint lid [[thread_position_in_threadgroup]], + uint lsize [[threads_per_threadgroup]]) { + size_t row_offset = gid * size_t(axis_size); + in += row_offset; + out += row_offset; + + int y_n = targets[gid]; + y_n = (y_n < 0) ? y_n + axis_size : y_n; + AccT x_t = AccT(in[y_n]); + AccT g = AccT(cotan[gid]); + AccT l = AccT(loss[gid]); + + // out aliases in when the input is donated, so every thread must read the + // target column before any thread writes. + threadgroup_barrier(mem_flags::mem_device); + + for (int r = 0; r < static_cast(ceildiv(axis_size, N_READS * lsize)); + r++) { + int offset = r * lsize * N_READS + lid * N_READS; + if (offset + N_READS <= axis_size) { + for (int i = 0; i < N_READS; i++) { + int col = offset + i; + AccT p = fast::exp((AccT(in[col]) - x_t) - l); + out[col] = T(g * (p - ((col == y_n) ? AccT(1) : AccT(0)))); + } + } else { + for (int i = 0; i < N_READS; i++) { + int col = offset + i; + if (col < axis_size) { + AccT p = fast::exp((AccT(in[col]) - x_t) - l); + out[col] = T(g * (p - ((col == y_n) ? AccT(1) : AccT(0)))); + } + } + } + } +} diff --git a/mlx/backend/metal/kernels/cross_entropy.metal b/mlx/backend/metal/kernels/cross_entropy.metal new file mode 100644 index 0000000000..f35fbe0609 --- /dev/null +++ b/mlx/backend/metal/kernels/cross_entropy.metal @@ -0,0 +1,18 @@ +// Copyright © 2026 Apple Inc. + +#include +#include + +using namespace metal; + +// clang-format off +#include "mlx/backend/metal/kernels/utils.h" +#include "mlx/backend/metal/kernels/cross_entropy.h" + +#define instantiate_cross_entropy(name, itype) \ + instantiate_kernel("cross_entropy_" #name, cross_entropy, itype) \ + instantiate_kernel("cross_entropy_vjp_" #name, cross_entropy_vjp, itype) + +instantiate_cross_entropy(float32, float) +instantiate_cross_entropy(float16, half) +instantiate_cross_entropy(bfloat16, bfloat16_t) // clang-format on diff --git a/mlx/backend/metal/kernels/defines.h b/mlx/backend/metal/kernels/defines.h index c369adb7e8..0e65906164 100644 --- a/mlx/backend/metal/kernels/defines.h +++ b/mlx/backend/metal/kernels/defines.h @@ -14,6 +14,7 @@ static MTL_CONST constexpr int REDUCE_N_WRITES = 4; static MTL_CONST constexpr int SOFTMAX_N_READS = 4; static MTL_CONST constexpr int RMS_N_READS = 4; static MTL_CONST constexpr int RMS_LOOPED_LIMIT = 4096; +static MTL_CONST constexpr int CROSS_ENTROPY_N_READS = 4; // Instantiate a templated kernel. // Extra args are used as template parameters: diff --git a/mlx/backend/metal/kernels/fp8.h b/mlx/backend/metal/kernels/fp8.h index 42c5ec128a..00efdeb792 100644 --- a/mlx/backend/metal/kernels/fp8.h +++ b/mlx/backend/metal/kernels/fp8.h @@ -30,11 +30,11 @@ struct fp8_e4m3 { } operator float16_t() thread { - uint16_t v = (bits & 127) << 7; - half converted = as_type(v); - converted *= 256.0; - auto sign = bits & 128; - return (sign ? -converted : converted); + uint16_t v = bits & 127; + uint16_t sign_bit = ((uint16_t)((bits >> 7) & 1)) << 15; + uint16_t u = (v << 7) | (((v + 1) >> 7) << 14) | sign_bit; + half converted = as_type(u); + return converted * 256.0; } operator bfloat16_t() thread { diff --git a/mlx/backend/metal/kernels/fp_quantized.h b/mlx/backend/metal/kernels/fp_quantized.h index 35dc88961f..136e14999f 100644 --- a/mlx/backend/metal/kernels/fp_quantized.h +++ b/mlx/backend/metal/kernels/fp_quantized.h @@ -136,13 +136,12 @@ inline void qouter(const thread uint8_t* w, U x, U scale, thread U* result) { } template -inline void dequantize(uint8_t w, U scale, threadgroup U* w_local) { - const float s = float(scale); +inline void dequantize(uint8_t w, float scale, threadgroup U* w_local) { if constexpr (bits == 4) { - w_local[0] = static_cast(s * Dequantize<4, float>{}(w)); - w_local[1] = static_cast(s * Dequantize<4, float>{}(w >> 4)); + w_local[0] = static_cast(scale * Dequantize<4, float>{}(w)); + w_local[1] = static_cast(scale * Dequantize<4, float>{}(w >> 4)); } else { - w_local[0] = static_cast(s * Dequantize<8, float>{}(w)); + w_local[0] = static_cast(scale * Dequantize<8, float>{}(w)); } } @@ -154,7 +153,8 @@ template < short reduction_dim, short tgp_size, short group_size, - short bits> + short bits, + bool has_global_scale = false> struct FPQuantizedBlockLoader { MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -164,9 +164,14 @@ struct FPQuantizedBlockLoader { MLX_MTL_CONST short group_steps = group_size < BCOLS ? 1 : group_size / BCOLS; MLX_MTL_CONST short scale_step = group_size < BCOLS ? BCOLS / group_size : 1; + MLX_MTL_CONST bool partial_cols = group_size % BCOLS != 0; + static_assert( (n_reads * pack_factor) <= group_size, "The number of reads per thread must be less than the group size."); + static_assert( + group_size % (n_reads * pack_factor) == 0, + "The group size must be a multiple of the columns read per thread."); const int src_ld; const int tile_stride; @@ -180,6 +185,9 @@ struct FPQuantizedBlockLoader { threadgroup T* dst; const device uint8_t* src; const device uint8_t* scales; + // nvfp4 tensor scale, folded into the group scale as fp_dequantize does. + // Kept in float: it is ~1e-5, so in fp16 small scales lose most bits. + float inv_scale_enc = 1.0f; FPQuantizedBlockLoader( const device uint8_t* src_, @@ -187,7 +195,8 @@ struct FPQuantizedBlockLoader { const int src_ld_, threadgroup T* dst_, ushort simd_group_id [[simdgroup_index_in_threadgroup]], - ushort simd_lane_id [[thread_index_in_simdgroup]]) thread + ushort simd_lane_id [[thread_index_in_simdgroup]], + const device float* global_scale = nullptr) thread : src_ld(src_ld_), tile_stride( reduction_dim ? BCOLS_PACKED* bytes_per_pack @@ -202,14 +211,19 @@ struct FPQuantizedBlockLoader { bj * bytes_per_pack), scales( scales_ + bi * src_ld / group_size + - (bj * pack_factor) / group_size) {} + (bj * pack_factor) / group_size) { + if constexpr (has_global_scale) { + inv_scale_enc = *global_scale / (F8E4M3_MAX * F4E2M1_MAX); + } + } void load_unsafe() const thread { if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; } - T scale = dequantize_scale(*scales); + float scale = + float(dequantize_scale(*scales)) * inv_scale_enc; for (int i = 0; i < n_reads; i++) { dequantize( src[i * bytes_per_pack], scale, dst + i * pack_factor); @@ -228,7 +242,8 @@ struct FPQuantizedBlockLoader { return; } - T scale = dequantize_scale(*scales); + float scale = + float(dequantize_scale(*scales)) * inv_scale_enc; for (int i = 0; i < n_reads; i++) { if ((bj + i) * pack_factor < src_tile_dim.x) { dequantize( @@ -259,6 +274,95 @@ struct FPQuantizedBlockLoader { } }; +template < + short BROWS, + short BCOLS, + short dst_ld, + short tgp_size, + short group_size> +struct Fp4HalfLoader { + MLX_MTL_CONST short BCOLS_PACKED = BCOLS / 2; + MLX_MTL_CONST short n_reads = (BCOLS_PACKED * BROWS) / tgp_size; + MLX_MTL_CONST short n_words = n_reads / 4; + + static_assert( + n_reads == 4 || n_reads == 8, + "Each thread reads one or two words of one group"); + static_assert(BCOLS % group_size == 0, "The block holds whole groups"); + + const int src_ld; + const short bi; + const short bj; + + threadgroup half* dst; + const device uint8_t* src; + const device uint8_t* scales; + + Fp4HalfLoader( + const device uint8_t* src_, + const device uint8_t* scales_, + const int src_ld_, + threadgroup half* dst_, + ushort simd_group_id [[simdgroup_index_in_threadgroup]], + ushort simd_lane_id [[thread_index_in_simdgroup]], + const device float* global_scale = nullptr) thread + : src_ld(src_ld_), + bi(n_reads*(simd_group_id * 32 + simd_lane_id) / BCOLS_PACKED), + bj((n_reads * (simd_group_id * 32 + simd_lane_id)) % BCOLS_PACKED), + dst(dst_ + bi * dst_ld + 2 * bj), + src(src_ + bi * src_ld / 2 + bj), + scales(scales_ + bi * src_ld / group_size + 2 * bj / group_size) { + (void)global_scale; + } + + void load_unsafe() const thread { + const half2 s = half2(dequantize_scale(*scales)); + for (short i = 0; i < n_words; i++) { + const uint q = ((const device uint*)src)[i]; + half2 v0 = + as_type(((q & 0x00070007) << 9) | ((q & 0x00080008) << 12)); + half2 v1 = + as_type(((q & 0x00700070) << 5) | ((q & 0x00800080) << 8)); + half2 v2 = + as_type(((q & 0x07000700) << 1) | ((q & 0x08000800) << 4)); + half2 v3 = as_type(((q & 0x70007000) >> 3) | (q & 0x80008000)); + v0 = (v0 * half2(16384.0h)) * s; + v1 = (v1 * half2(16384.0h)) * s; + v2 = (v2 * half2(16384.0h)) * s; + v3 = (v3 * half2(16384.0h)) * s; + *(threadgroup uint4*)(dst + 8 * i) = uint4( + as_type(half2(v0.x, v1.x)), + as_type(half2(v2.x, v3.x)), + as_type(half2(v0.y, v1.y)), + as_type(half2(v2.y, v3.y))); + } + } + + void load_safe(short2 src_tile_dim) const thread { + if (bi < src_tile_dim.y && 2 * bj < src_tile_dim.x) { + load_unsafe(); + } else { + for (short i = 0; i < n_words; i++) { + *(threadgroup uint4*)(dst + 8 * i) = uint4(0); + } + } + } + + void next() thread { + src += BCOLS_PACKED; + scales += BCOLS / group_size; + } +}; + +// Use Fp4HalfLoader when dequantizing fp4 into half. Also use it for +// dequantizing nvfp4 into bfloat16, which has no loss. +template +inline constexpr bool use_fp4_half_loader() { + return !has_global_scale && + ((metal::is_same_v && bits == 4) || + (metal::is_same_v && bits == 4 && group_size == 16)); +} + template METAL_FUNC void fp_qmv_quad_impl( const device uint32_t* w, @@ -325,6 +429,7 @@ template < typename T, int group_size, int bits, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4, bool allow_aligned_tail = false> @@ -359,6 +464,15 @@ METAL_FUNC void fp_qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // Reuse the last valid row for reads beyond the output tile. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; @@ -371,8 +485,12 @@ METAL_FUNC void fp_qmv_fast_impl( load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device auto* sl = scales + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device auto* sl = scales + src * in_vec_size_g; U s = dequantize_scale(sl[0]); result[row] += qdot(wl, x_thread, s); @@ -389,8 +507,12 @@ METAL_FUNC void fp_qmv_fast_impl( if (int(simd_lid) * values_per_thread < tail_values) { load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - const device uint8_t* wl = ws + row * in_vec_size_w; - const device uint8_t* sl = scales + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + const device uint8_t* wl = ws + src * in_vec_size_w; + const device uint8_t* sl = scales + src * in_vec_size_g; U scale = dequantize_scale(sl[0]); result[row] += qdot(wl, x_thread, scale); } @@ -404,7 +526,7 @@ METAL_FUNC void fp_qmv_fast_impl( for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { if constexpr (has_global_scale) { y[row] = static_cast(result[row] * inv_scale_enc); } else { @@ -805,16 +927,20 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, + const bool has_global_scale = false, const int BM = 32, const int BK = 32, - const int BN = 32> + const int BN = 32, + typename TW> METAL_FUNC void fp_qmm_t_impl( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, - threadgroup T* Ws, + threadgroup TW* Ws, const constant int& K, const constant int& N, const constant int& M, @@ -837,18 +963,23 @@ METAL_FUNC void fp_qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; - using loader_w_t = FPQuantizedBlockLoader< - T, - BN, - BK, - BK_padded, - 1, - WM * WN * SIMD_SIZE, - group_size, - bits>; + // Use shortcut when loading fp4 quants to half weights + using loader_w_t = metal::conditional_t< + metal::is_same_v && (bits == 4) && !has_global_scale, + Fp4HalfLoader, + FPQuantizedBlockLoader< + T, + BN, + BK, + BK_padded, + 1, + WM * WN * SIMD_SIZE, + group_size, + bits, + has_global_scale>>; // Set the block const int K_w = K * bytes_per_pack / pack_factor; @@ -867,12 +998,15 @@ METAL_FUNC void fp_qmm_t_impl( const short num_els = min(BM, M - y_row); const short num_outs = min(BN, N - y_col); loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid); - loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid, global_scale); mma_t mma_op(simd_gid, simd_lid); + constexpr bool partial_k = group_size % BK != 0; + const int k_blocks = K_eff / BK; + const short num_k = partial_k ? short(K_eff - k_blocks * BK) : short(0); if (num_els < BM) { if (!aligned_N && num_outs < BN) { - for (int k = 0; k < K_eff; k += BK) { + for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_safe(short2(BK, num_els)); loader_w.load_safe(short2(BK, num_outs)); @@ -882,7 +1016,7 @@ METAL_FUNC void fp_qmm_t_impl( loader_w.next(); } } else { - for (int k = 0; k < K_eff; k += BK) { + for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_safe(short2(BK, num_els)); loader_w.load_unsafe(); @@ -892,9 +1026,18 @@ METAL_FUNC void fp_qmm_t_impl( loader_w.next(); } } + if constexpr (partial_k) { + if (num_k > 0) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(num_k, num_els)); + loader_w.load_safe(short2(num_k, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + } + } } else { if (!aligned_N && num_outs < BN) { - for (int k = 0; k < K_eff; k += BK) { + for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_unsafe(); loader_w.load_safe(short2(BK, num_outs)); @@ -904,7 +1047,7 @@ METAL_FUNC void fp_qmm_t_impl( loader_w.next(); } } else { - for (int k = 0; k < K_eff; k += BK) { + for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_unsafe(); loader_w.load_unsafe(); @@ -915,6 +1058,15 @@ METAL_FUNC void fp_qmm_t_impl( loader_w.next(); } } + if constexpr (partial_k) { + if (num_k > 0) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(num_k, BM)); + loader_w.load_safe(short2(num_k, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + } + } } // Store results to device memory @@ -930,12 +1082,14 @@ template < typename T, int group_size, int bits, + bool has_global_scale = false, int BM = 32, int BK = 32, int BN = 32> METAL_FUNC void fp_qmm_n_impl( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, device T* y, threadgroup T* Xs, @@ -973,7 +1127,8 @@ METAL_FUNC void fp_qmm_n_impl( 0, WM * WN * SIMD_SIZE, group_size, - bits>; + bits, + has_global_scale>; auto wl = (const device uint8_t*)w; @@ -988,16 +1143,23 @@ METAL_FUNC void fp_qmm_n_impl( // Make the x loader and mma operation const short num_els = min(BM, M - y_row); loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid); - loader_w_t loader_w(wl, scales, N, Ws, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, N, Ws, simd_gid, simd_lid, global_scale); mma_t mma_op(simd_gid, simd_lid); + constexpr bool partial_n = group_size % BN != 0; + const short num_outs = partial_n ? short(min(BN, N - y_col)) : short(BN); + if (num_els < BM) { if ((K % BK) != 0) { const int k_blocks = K / BK; for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_safe(short2(BK, num_els)); - loader_w.load_unsafe(); + if constexpr (partial_n) { + loader_w.load_safe(short2(num_outs, BK)); + } else { + loader_w.load_unsafe(); + } threadgroup_barrier(mem_flags::mem_threadgroup); mma_op.mma(Xs, Ws); loader_x.next(); @@ -1006,9 +1168,19 @@ METAL_FUNC void fp_qmm_n_impl( const short num_k = K - k_blocks * BK; threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_safe(short2(num_k, num_els)); - loader_w.load_safe(short2(BN, num_k)); + loader_w.load_safe(short2(num_outs, num_k)); threadgroup_barrier(mem_flags::mem_threadgroup); mma_op.mma(Xs, Ws); + } else if (num_outs < BN) { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_safe(short2(num_outs, BK)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } } else { for (int k = 0; k < K; k += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); @@ -1026,7 +1198,11 @@ METAL_FUNC void fp_qmm_n_impl( for (int k = 0; k < k_blocks; k++) { threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_unsafe(); - loader_w.load_unsafe(); + if constexpr (partial_n) { + loader_w.load_safe(short2(num_outs, BK)); + } else { + loader_w.load_unsafe(); + } threadgroup_barrier(mem_flags::mem_threadgroup); mma_op.mma(Xs, Ws); loader_x.next(); @@ -1035,9 +1211,19 @@ METAL_FUNC void fp_qmm_n_impl( const short num_k = K - k_blocks * BK; threadgroup_barrier(mem_flags::mem_threadgroup); loader_x.load_safe(short2(num_k, BM)); - loader_w.load_safe(short2(BN, num_k)); + loader_w.load_safe(short2(num_outs, num_k)); threadgroup_barrier(mem_flags::mem_threadgroup); mma_op.mma(Xs, Ws); + } else if (num_outs < BN) { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_safe(short2(num_outs, BK)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } } else { for (int k = 0; k < K; k += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); @@ -1053,8 +1239,8 @@ METAL_FUNC void fp_qmm_n_impl( // Store results to device memory threadgroup_barrier(mem_flags::mem_threadgroup); - if (num_els < BM) { - mma_op.store_result_safe(y, N, short2(BN, num_els)); + if (num_els < BM || num_outs < BN) { + mma_op.store_result_safe(y, N, short2(num_outs, num_els)); } else { mma_op.store_result(y, N); } @@ -1095,11 +1281,12 @@ METAL_FUNC void adjust_matrix_offsets( y += tid.z * output_stride; } -template +template METAL_FUNC void adjust_matrix_offsets( const device T*& x, const device uint32_t*& w, const device uint8_t*& scales, + const device float*& global_scale, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, device T*& y, @@ -1142,6 +1329,10 @@ METAL_FUNC void adjust_matrix_offsets( w += idx.x; scales += idx.y; } + // One global scale per expert, contiguous over the batch dims of w. + if constexpr (has_global_scale) { + global_scale += w_idx; + } y += tid.z * output_stride; } @@ -1189,6 +1380,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv_fast( @@ -1230,6 +1422,7 @@ template < T, group_size, bits, + partial_rows, has_global_scale, results_per_simdgroup>( w, @@ -1249,6 +1442,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void fp_qmv( @@ -1344,6 +1538,201 @@ template < w, scales, x, y, in_vec_size, out_vec_size, M, tid, simd_gid, simd_lid); } +template < + typename T, + int group_size, + int bits, + int WK = 8, + int BN = 32, + int TM = 1> +[[kernel]] void fp_qmv_mma( + const device uint32_t* w, + const device uint8_t* scales, + const device T* x, + device T* y, + const constant int& K, + const constant int& N, + const constant int& M, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BN % 8 == 0, "BN should be divisible by 8"); + static_assert(TM == 1 || TM == 2, "qmv_mma takes at most 16 rows"); + static_assert( + (group_size == 16 && bits == 4) || + (group_size == 32 && (bits == 4 || bits == 8)), + "qmv_mma reads nvfp4, mxfp4 and mxfp8"); + + using Frag = mlx::steel::BaseMMAFrag; + using frag_t = typename Frag::frag_type; + using scale_t = metal::conditional_t; + constexpr int BK = 128; + constexpr short TN = BN / 8; + constexpr int pack_factor = 8 / bits; + constexpr short loads = bits / 4; + + const short2 coord = Frag::get_coord(simd_lid); + const short fn = coord.x; + const short fm = coord.y; + const int row_bytes = K / pack_factor; + const int row_scales = K / group_size; + + const int y_col = tid.x * BN; + auto wl = (const device uint8_t*)w + + (y_col + fm) * static_cast(row_bytes) + 16 * fn / pack_factor; + scales += + (y_col + fm) * static_cast(row_scales) + 16 * fn / group_size; + x += fn * static_cast(K) + 16 * fm; + + bool x_rows[TM][2]; + frag_t C[TN][TM]; + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 2; j++) { + x_rows[mt][j] = 8 * mt + fn + j < M; + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + C[t][mt] = frag_t(0); + } + } + + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec xs[TM][2][2]; + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 2; j++) { + const device T* xr = x + (8 * mt + j) * static_cast(K) + k; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + xs[mt][j][h] = x_rows[mt][j] ? *(const device vec*)(xr + 8 * h) + : vec(0); + } + } + } + uint4 ws[TN][loads]; + scale_t sc[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + const device uint8_t* wt = + wl + 8 * t * static_cast(row_bytes) + k / pack_factor; + STEEL_PRAGMA_UNROLL + for (short l = 0; l < loads; l++) { + ws[t][l] = *(const device uint4*)(wt + 16 * l); + } + const device uint8_t* st = + scales + 8 * t * static_cast(row_scales) + k / group_size; + if constexpr (group_size == 16) { + const ushort s = *(const device ushort*)st; + sc[t] = half2( + dequantize_scale(s & 0xff), + dequantize_scale(s >> 8)); + } else { + sc[t] = dequantize_scale(*st) * + (bits == 4 ? 16384.0f : 256.0f); + } + } + + STEEL_PRAGMA_UNROLL + for (short g = 0; g < 4; g++) { + frag_t b[4][TM]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + const short f = 4 * g + i; + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + b[i][mt] = frag_t( + float(xs[mt][0][f / 8][f % 8]), float(xs[mt][1][f / 8][f % 8])); + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + uint p[4]; + if constexpr (bits == 4) { + const uint lo = ws[t][0][g / 2]; + const uint hi = ws[t][0][2 + g / 2]; + const uint q = (g % 2) == 0 ? (lo & 0xffff) | (hi << 16) + : (lo >> 16) | (hi & 0xffff0000); + p[0] = ((q & 0x00070007) << 9) | ((q & 0x00080008) << 12); + p[1] = ((q & 0x00700070) << 5) | ((q & 0x00800080) << 8); + p[2] = ((q & 0x07000700) << 1) | ((q & 0x08000800) << 4); + p[3] = ((q & 0x70007000) >> 3) | (q & 0x80008000); + } else { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + const uint q = ((ws[t][0][g] >> (8 * i)) & 0xff) | + (((ws[t][1][g] >> (8 * i)) & 0xff) << 16); + p[i] = ((q & 0x00800080) << 8) | ((q & 0x007f007f) << 7); + } + } + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + frag_t a; + if constexpr (group_size == 16) { + const half2 v = (as_type(p[i]) * half2(16384.0h)) * sc[t]; + a = frag_t(float(v.x), float(v.y)); + } else { + const half2 v = as_type(p[i]); + a = frag_t(float(v.x) * sc[t], float(v.y) * sc[t]); + } + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + Frag::mma(C[t][mt], a, b[i][mt], C[t][mt]); + } + } + } + } + } + + constexpr int tile_elems = TN * TM * 2; + threadgroup float Ps[(WK - 1) * tile_elems * 32]; + if (simd_gid > 0) { + threadgroup float* p = Ps + (simd_gid - 1) * tile_elems * 32 + simd_lid; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 2; j++) { + p[((t * TM + mt) * 2 + j) * 32] = C[t][mt][j]; + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_gid == 0) { + for (int s = 0; s < WK - 1; s++) { + const threadgroup float* p = Ps + s * tile_elems * 32 + simd_lid; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 2; j++) { + C[t][mt][j] += p[((t * TM + mt) * 2 + j) * 32]; + } + } + } + } + STEEL_PRAGMA_UNROLL + for (short mt = 0; mt < TM; mt++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 2; j++) { + if (x_rows[mt][j]) { + device T* yr = + y + (8 * mt + fn + j) * static_cast(N) + y_col + fm; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + yr[8 * t] = static_cast(C[t][mt][j]); + } + } + } + } + } +} + template < typename T, int group_size, @@ -1457,16 +1846,18 @@ template template < typename T, - const int group_size, - const int bits, - const bool aligned_N, - const bool batched, - const int BM = 32, - const int BK = 32, - const int BN = 32> + int group_size, + int bits, + bool aligned_N, + bool batched, + bool has_global_scale = false, + int BM = 32, + int BK = 32, + int BN = 32> [[kernel]] void fp_qmm_t( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, device T* y, const constant int& K, @@ -1486,9 +1877,13 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(T)); + using TW = metal::conditional_t< + use_fp4_half_loader(), + half, + T>; threadgroup T Xs[BM * BK_padded]; - threadgroup T Ws[BN * BK_padded]; + threadgroup TW Ws[BN * BK_padded]; if (batched) { adjust_matrix_offsets( @@ -1506,8 +1901,31 @@ template < s_strides, tid); } - fp_qmm_t_impl( - w, scales, x, y, Xs, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( + w, + scales, + global_scale, + x, + y, + Xs, + Ws, + K, + N, + M, + K, + tid, + lid, + simd_gid, + simd_lid); } template < @@ -1563,8 +1981,8 @@ template < tid); } - fp_qmm_n_impl( - w, scales, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_n_impl( + w, scales, nullptr, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } template @@ -1593,10 +2011,11 @@ template uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { int M = x_shape[x_batch_ndims]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1613,7 +2032,7 @@ template w_strides, s_strides, tid); - fp_qmv_fast_impl( + fp_qmv_fast_impl( w, scales, global_scale, @@ -1652,10 +2071,11 @@ template uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { int M = x_shape[x_batch_ndims]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1672,7 +2092,7 @@ template w_strides, s_strides, tid); - fp_qmv_fast_impl( + fp_qmv_fast_impl( w, scales, global_scale, @@ -1711,10 +2131,11 @@ template uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { int M = x_shape[x_batch_ndims]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1770,10 +2191,11 @@ template uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { int M = x_shape[x_batch_ndims]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1809,12 +2231,14 @@ template < const int group_size, const int bits, const bool aligned_N, + const bool has_global_scale = false, const int BM = 32, const int BK = 32, const int BN = 32> [[kernel]] void fp_gather_qmm_t( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, @@ -1844,10 +2268,11 @@ template < threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BN * BK_padded]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1864,8 +2289,31 @@ template < w_strides, s_strides, tid); - fp_qmm_t_impl( - w, scales, x, y, Xs, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + T, + has_global_scale, + BM, + BK, + BN>( + w, + scales, + global_scale, + x, + y, + Xs, + Ws, + K, + N, + M, + K, + tid, + lid, + simd_gid, + simd_lid); } template < @@ -1880,7 +2328,7 @@ template < const device uint32_t* w [[buffer(0)]], const device uint8_t* scales [[buffer(1)]], const device T* x [[buffer(2)]], - device T* y [[buffer(3)]], + device float* y [[buffer(3)]], const constant int& K [[buffer(4)]], const constant int& N [[buffer(5)]], const constant int& M [[buffer(6)]], @@ -1895,8 +2343,14 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(T)); constexpr int pack_factor = get_fp_pack_factor<8, bits>(); constexpr int bytes_per_pack = get_bytes_per_pack(); + using TW = metal::conditional_t< + use_fp4_half_loader(), + half, + T>; + threadgroup T Xs[BM * BK_padded]; - threadgroup T Ws[BN * BK_padded]; + threadgroup TW Ws[BN * BK_padded]; + const int k_start = tid.z * k_partition_size; x += k_start; @@ -1905,9 +2359,10 @@ template < scales += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - fp_qmm_t_impl( + fp_qmm_t_impl( (const device uint32_t*)wl, scales, + nullptr, x, y, Xs, @@ -1933,6 +2388,7 @@ template < [[kernel]] void fp_gather_qmm_n( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, @@ -1963,10 +2419,11 @@ template < threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BK * BN_padded]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -1983,8 +2440,21 @@ template < w_strides, s_strides, tid); - fp_qmm_n_impl( - w, scales, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_n_impl( + w, + scales, + global_scale, + x, + y, + Xs, + Ws, + K, + N, + M, + tid, + lid, + simd_gid, + simd_lid); } template < @@ -1996,11 +2466,13 @@ template < int BK, int WM, int WN, - bool transpose> + bool transpose, + bool has_global_scale = false> [[kernel]] void fp_gather_qmm_rhs( const device T* x, const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device int32_t* offsets, device T* y, const constant int& M, @@ -2037,7 +2509,8 @@ template < transpose, WM * WN * SIMD_SIZE, group_size, - bits>; + bits, + has_global_scale>; threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[transpose ? BN * BK_padded : BK * BN_padded]; @@ -2088,7 +2561,8 @@ template < transpose ? K : N, Ws, simd_group_id, - simd_lane_id); + simd_lane_id, + global_scale + group); // Tile aligned so check outside of the hot loop if (tgp_bm == BM && (align_N || tgp_bn == BN)) { diff --git a/mlx/backend/metal/kernels/fp_quantized.metal b/mlx/backend/metal/kernels/fp_quantized.metal index ea12ae9afb..c9ca81e20c 100644 --- a/mlx/backend/metal/kernels/fp_quantized.metal +++ b/mlx/backend/metal/kernels/fp_quantized.metal @@ -21,7 +21,7 @@ bits, \ true) -#define instantiate_quantized_batched(mode, name, type, batched, group_size, bits) \ +#define instantiate_quantized_batched(mode, name, type, group_size, bits, batched) \ instantiate_kernel( \ #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_batch_" #batched, \ fp_ ## name, \ @@ -38,6 +38,18 @@ batched, \ true) +#define instantiate_quantized_qmv(mode, name, type, group_size, bits, batched, partial_rows, has_global_scale, results) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_batch_" #batched "_pr_" #partial_rows "_hgs_" #has_global_scale "_r_" #results, \ + fp_ ## name, \ + type, \ + group_size, \ + bits, \ + batched, \ + partial_rows, \ + has_global_scale, \ + results) + #define instantiate_quantized_aligned(mode, name, type, aligned, group_size, bits) \ instantiate_kernel( \ #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned, \ @@ -47,6 +59,17 @@ bits, \ aligned) +#define instantiate_quantized_aligned_hgs(mode, name, type, aligned, group_size, bits) \ + instantiate_quantized_aligned(mode, name, type, aligned, group_size, bits) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned "_hgs", \ + fp_ ## name, \ + type, \ + group_size, \ + bits, \ + aligned, \ + true) + #define instantiate_quantized_aligned_batched(mode, name, type, aligned, batched, group_size, bits) \ instantiate_kernel( \ #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned "_batch_" #batched, \ @@ -57,29 +80,30 @@ aligned, \ batched) -#define instantiate_quantized_qmv_fast(mode, type, results, batched, group_size, bits) \ +#define instantiate_quantized_aligned_batched_hgs(mode, name, type, aligned, batched, group_size, bits) \ instantiate_kernel( \ - #mode "_qmv_fast_" #type "_gs_" #group_size "_b_" #bits "_r_" #results "_batch_" #batched, \ - fp_qmv_fast, \ - type, \ - group_size, \ - bits, \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned "_batch_" #batched "_hgs", \ + fp_ ## name, \ + type, \ + group_size, \ + bits, \ + aligned, \ batched, \ - false, \ - results) \ + true) + +#define instantiate_quantized_aligned_batched_bm_bn(mode, name, type, group_size, bits, aligned, batched, bm, bn) \ instantiate_kernel( \ - #mode "_qmv_fast_" #type "_gs_" #group_size "_b_" #bits "_r_" #results "_batch_" #batched "_hgs", \ - fp_qmv_fast, \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned "_batch_" #batched "_bm_" #bm "_bn_" #bn, \ + fp_qmm_t, \ type, \ group_size, \ bits, \ + aligned, \ batched, \ - true, \ - results) - -#define instantiate_quantized_qmv_fast_r2(mode, type, group_size, bits) \ - instantiate_quantized_qmv_fast(mode, type, 2, 1, group_size, bits) \ - instantiate_quantized_qmv_fast(mode, type, 2, 0, group_size, bits) + false, \ + bm, \ + 32, \ + bn) #define instantiate_quantized_quad(mode, name, type, D, batched, group_size, bits) \ instantiate_kernel( \ @@ -123,16 +147,36 @@ bk, \ wm, \ wn, \ - transpose) + transpose) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_bm_" #bm "_bn_" #bn "_bk_" #bk "_wm_" #wm "_wn_" #wn "_hgs", \ + func, \ + type, \ + group_size, \ + bits, \ + bm, \ + bn, \ + bk, \ + wm, \ + wn, \ + transpose, \ + true) #define instantiate_quantized_batched_wrap(name, type, mode, group_size, bits) \ - instantiate_quantized_batched(mode, name, type, 1, group_size, bits) \ - instantiate_quantized_batched(mode, name, type, 0, group_size, bits) + instantiate_quantized_batched(mode, name, type, group_size, bits, 1) \ + instantiate_quantized_batched(mode, name, type, group_size, bits, 0) -#define instantiate_quantized_all_batched(type, mode, group_size, bits) \ - instantiate_quantized_batched_wrap(qmv_fast, type, mode, group_size, bits) \ - instantiate_quantized_batched_wrap(qmv, type, mode, group_size, bits) \ - instantiate_quantized_batched_wrap(qvm, type, mode, group_size, bits) \ +#define instantiate_quantized_qmv_wrap(name, type, mode, group_size, bits, partial_rows, results) \ + instantiate_quantized_qmv(mode, name, type, group_size, bits, 1, partial_rows, 1, results) \ + instantiate_quantized_qmv(mode, name, type, group_size, bits, 1, partial_rows, 0, results) \ + instantiate_quantized_qmv(mode, name, type, group_size, bits, 0, partial_rows, 1, results) \ + instantiate_quantized_qmv(mode, name, type, group_size, bits, 0, partial_rows, 0, results) + +#define instantiate_quantized_all_batched(type, mode, group_size, bits) \ + instantiate_quantized_qmv_wrap(qmv_fast, type, mode, group_size, bits, 1, 4) \ + instantiate_quantized_qmv_wrap(qmv_fast, type, mode, group_size, bits, 0, 4) \ + instantiate_quantized_qmv_wrap(qmv, type, mode, group_size, bits, 0, 4) \ + instantiate_quantized_batched_wrap(qvm, type, mode, group_size, bits) \ instantiate_quantized_batched_wrap(qmm_n, type, mode, group_size, bits) #define instantiate_quantized_all_single(type, mode, group_size, bits) \ @@ -142,13 +186,17 @@ instantiate_quantized(mode, gather_qmm_n, type, group_size, bits) #define instantiate_quantized_all_aligned(type, mode, group_size, bits) \ - instantiate_quantized_aligned(mode, gather_qmm_t, type, true, group_size, bits) \ - instantiate_quantized_aligned(mode, gather_qmm_t, type, false, group_size, bits) \ + instantiate_quantized_aligned_hgs(mode, gather_qmm_t, type, true, group_size, bits) \ + instantiate_quantized_aligned_hgs(mode, gather_qmm_t, type, false, group_size, bits) \ instantiate_quantized_aligned_batched(mode, qmm_t, type, true, 1, group_size, bits) \ instantiate_quantized_aligned_batched(mode, qmm_t, type, true, 0, group_size, bits) \ instantiate_quantized_aligned_batched(mode, qmm_t, type, false, 1, group_size, bits) \ instantiate_quantized_aligned_batched(mode, qmm_t, type, false, 0, group_size, bits) +#define instantiate_quantized_qmm_hgs(type) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t, type, true, 0, 16, 4) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t, type, false, 0, 16, 4) + #define instantiate_quantized_all_quad(type, mode, group_size, bits) \ instantiate_quantized_quad(mode, qmv_quad, type, 64, 1, group_size, bits) \ instantiate_quantized_quad(mode, qmv_quad, type, 64, 0, group_size, bits) \ @@ -209,18 +257,56 @@ instantiate_quantized_all_rhs(type, mode, group_size, bits) #define instantiate_quantized_types(type) \ - instantiate_quantized_modes(type, nvfp4, 16, 4) \ - instantiate_quantized_modes(type, mxfp8, 32, 8) \ - instantiate_quantized_modes(type, mxfp4, 32, 4) \ - instantiate_quantize_dequantize(type, nvfp4, 16, 4, false) \ - instantiate_quantize_dequantize(type, nvfp4, 16, 4, true) \ - instantiate_quantize_dequantize(type, mxfp8, 32, 8, false) \ - instantiate_quantize_dequantize(type, mxfp4, 32, 4, false) \ - instantiate_quantized_qmv_fast_r2(nvfp4, type, 16, 4) + instantiate_quantized_modes(type, nvfp4, 16, 4) \ + instantiate_quantized_modes(type, mxfp8, 32, 8) \ + instantiate_quantized_modes(type, mxfp4, 32, 4) \ + instantiate_quantize_dequantize(type, nvfp4, 16, 4, false) \ + instantiate_quantize_dequantize(type, nvfp4, 16, 4, true) \ + instantiate_quantize_dequantize(type, mxfp8, 32, 8, false) \ + instantiate_quantize_dequantize(type, mxfp4, 32, 4, false) \ + instantiate_quantized_qmv_wrap(qmv_fast, type, nvfp4, 16, 4, 1, 2) \ + instantiate_quantized_qmv_wrap(qmv_fast, type, nvfp4, 16, 4, 0, 2) + +#define instantiate_quantized_qmm_t_bm64_bn64(type, mode, group_size, bits) \ + instantiate_quantized_aligned_batched_bm_bn(mode, qmm_t, type, group_size, bits, true, 0, 64, 64) \ + instantiate_quantized_aligned_batched_bm_bn(mode, qmm_t, type, group_size, bits, true, 1, 64, 64) \ + instantiate_quantized_aligned_batched_bm_bn(mode, qmm_t, type, group_size, bits, false, 0, 64, 64) \ + instantiate_quantized_aligned_batched_bm_bn(mode, qmm_t, type, group_size, bits, false, 1, 64, 64) + +#define instantiate_qmv_mma(type, mode, group_size, bits, wk, bn, tm) \ + instantiate_kernel( \ + #mode "_qmv_mma_" #type "_gs_" #group_size "_b_" #bits "_wk" #wk "_bn" #bn "_tm" #tm, \ + fp_qmv_mma, \ + type, \ + group_size, \ + bits, \ + wk, \ + bn, \ + tm) + +#define instantiate_qmv_mma_rows(type, mode, group_size, bits, wk, bn) \ + instantiate_qmv_mma(type, mode, group_size, bits, wk, bn, 1) \ + instantiate_qmv_mma(type, mode, group_size, bits, wk, bn, 2) + +#define instantiate_qmv_mma_modes(type, wk, bn) \ + instantiate_qmv_mma_rows(type, nvfp4, 16, 4, wk, bn) \ + instantiate_qmv_mma_rows(type, mxfp8, 32, 8, wk, bn) \ + instantiate_qmv_mma_rows(type, mxfp4, 32, 4, wk, bn) + +#define instantiate_qmv_mma_types(type) \ + instantiate_qmv_mma_modes(type, 8, 16) \ + instantiate_qmv_mma_modes(type, 4, 16) instantiate_quantized_types(float) instantiate_quantized_types(bfloat16_t) instantiate_quantized_types(float16_t) +instantiate_quantized_qmm_hgs(bfloat16_t) +instantiate_quantized_qmm_t_bm64_bn64(bfloat16_t, nvfp4, 16, 4) +instantiate_quantized_qmm_t_bm64_bn64(float16_t, nvfp4, 16, 4) +instantiate_quantized_qmm_t_bm64_bn64(float16_t, mxfp4, 32, 4) +instantiate_qmv_mma_types(float) +instantiate_qmv_mma_types(bfloat16_t) +instantiate_qmv_mma_types(float16_t) // clang-format on // Exact GPT-OSS MXFP4 gathered-vector tail experiment. diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index 45e1bfebd3..e4e554865e 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -1,4 +1,4 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #include #include @@ -60,13 +60,12 @@ struct Dequantize { }; template -inline void dequantize(uint8_t w, U scale, threadgroup U* w_local) { - const float s = float(scale); +inline void dequantize(uint8_t w, float scale, threadgroup U* w_local) { if constexpr (bits == 4) { - w_local[0] = static_cast(s * Dequantize<4, float>{}(w)); - w_local[1] = static_cast(s * Dequantize<4, float>{}(w >> 4)); + w_local[0] = static_cast(scale * Dequantize<4, float>{}(w)); + w_local[1] = static_cast(scale * Dequantize<4, float>{}(w >> 4)); } else { - w_local[0] = static_cast(s * Dequantize<8, float>{}(w)); + w_local[0] = static_cast(scale * Dequantize<8, float>{}(w)); } } @@ -78,7 +77,8 @@ template < short reduction_dim, short tgp_size, short group_size, - short bits> + short bits, + bool has_global_scale = false> struct FPQuantizedNAXBlockLoader { MLX_MTL_CONST short pack_factor = get_fp_pack_factor<8, bits>(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -106,6 +106,9 @@ struct FPQuantizedNAXBlockLoader { threadgroup T* dst; const device uint8_t* src; const device uint8_t* scales; + // nvfp4 tensor scale, folded into the group scale as fp_dequantize does. + // Kept in float: it is ~1e-5, so in fp16 small scales lose most bits. + float inv_scale_enc = 1.0f; FPQuantizedNAXBlockLoader( const device uint8_t* src_, @@ -113,7 +116,8 @@ struct FPQuantizedNAXBlockLoader { const int src_ld_, threadgroup T* dst_, ushort simd_group_id [[simdgroup_index_in_threadgroup]], - ushort simd_lane_id [[thread_index_in_simdgroup]]) thread + ushort simd_lane_id [[thread_index_in_simdgroup]], + const device float* global_scale = nullptr) thread : src_ld(src_ld_), tile_stride( reduction_dim ? BCOLS_PACKED* bytes_per_pack @@ -126,7 +130,11 @@ struct FPQuantizedNAXBlockLoader { dst(dst_ + bi * dst_ld + bj * pack_factor), src(src_ + bi * src_ld * bytes_per_pack / pack_factor + bj * bytes_per_pack), - scales(scales_ + bi * src_ld / group_size + group_id) {} + scales(scales_ + bi * src_ld / group_size + group_id) { + if constexpr (has_global_scale) { + inv_scale_enc = *global_scale / (F8E4M3_MAX * F4E2M1_MAX); + } + } void load_unsafe() const thread { if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { @@ -135,7 +143,8 @@ struct FPQuantizedNAXBlockLoader { int k = 0; for (int i = 0; i < n_steps_per_read; i++) { - T scale = dequantize_scale(scales[i]); + float scale = + float(dequantize_scale(scales[i])) * inv_scale_enc; for (int j = 0; j < n_reads_per_scale; j++) { dequantize( src[k * bytes_per_pack], scale, dst + k * pack_factor); @@ -159,8 +168,9 @@ struct FPQuantizedNAXBlockLoader { int k = 0; for (int i = 0; i < n_steps_per_read; i++) { const bool scale_in_bounds = (bj + k) * pack_factor < src_tile_dim.x; - T scale = - scale_in_bounds ? dequantize_scale(scales[i]) : T(0); + float scale = scale_in_bounds + ? float(dequantize_scale(scales[i])) * inv_scale_enc + : 0.0f; for (int j = 0; j < n_reads_per_scale; j++) { if ((bj + k) * pack_factor < src_tile_dim.x) { dequantize( @@ -192,6 +202,7 @@ template < const int group_size, const int bits, const bool aligned_N, + const bool has_global_scale = false, const int BM = 64, const int BK = 64, const int BN = 64, @@ -201,6 +212,7 @@ template < METAL_FUNC void fp_qmm_t_impl( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, device T* y, threadgroup Wtype* Ws, @@ -230,7 +242,8 @@ METAL_FUNC void fp_qmm_t_impl( 1, WM * WN * SIMD_SIZE, group_size, - bits>; + bits, + has_global_scale>; // Set the block const int K_w = K * bytes_per_pack / pack_factor; @@ -246,7 +259,7 @@ METAL_FUNC void fp_qmm_t_impl( y += y_row * static_cast(N) + y_col; // Make the weight loader - loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid, global_scale); constexpr short SM = BM / WM; constexpr short SN = BN / WN; @@ -332,10 +345,42 @@ METAL_FUNC void fp_qmm_t_impl( }); } +template +METAL_FUNC vec dequantize_fp_x4(uint q, uint8_t s) { + half2 a; + half2 b; + if constexpr (bits == 4) { + const uint lo = (q & 0x000f) | ((q & 0x00f0) << 12); + const uint hi = ((q >> 8) & 0x000f) | ((q & 0xf000) << 4); + a = as_type(((lo & 0x00070007) << 9) | ((lo & 0x00080008) << 12)); + b = as_type(((hi & 0x00070007) << 9) | ((hi & 0x00080008) << 12)); + } else { + const uint lo = (q & 0x000000ff) | ((q & 0x0000ff00) << 8); + const uint hi = ((q >> 16) & 0x000000ff) | ((q >> 8) & 0x00ff0000); + a = as_type(((lo & 0x00800080) << 8) | ((lo & 0x007f007f) << 7)); + b = as_type(((hi & 0x00800080) << 8) | ((hi & 0x007f007f) << 7)); + } + if constexpr (group_size == 16) { + const half scale = dequantize_scale(s); + a = (a * half2(16384.0h)) * scale; + b = (b * half2(16384.0h)) * scale; + return vec(Wtype(a.x), Wtype(a.y), Wtype(b.x), Wtype(b.y)); + } else { + const float scale = dequantize_scale(s) * + (bits == 4 ? 16384.0f : 256.0f); + return vec( + Wtype(float(a.x) * scale), + Wtype(float(a.y) * scale), + Wtype(float(b.x) * scale), + Wtype(float(b.y) * scale)); + } +} + template < typename T, const int group_size, const int bits, + const bool has_global_scale = false, const int BM = 64, const int BK = 64, const int BN = 64, @@ -345,6 +390,7 @@ template < METAL_FUNC void fp_qmm_n_impl( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, device T* y, threadgroup T* Ws, @@ -374,7 +420,8 @@ METAL_FUNC void fp_qmm_n_impl( 0, WM * WN * SIMD_SIZE, group_size, - bits>; + bits, + has_global_scale>; // Set the block const int K_w = K * bytes_per_pack / pack_factor; @@ -392,7 +439,7 @@ METAL_FUNC void fp_qmm_n_impl( // Make the x loader and mma operation // const short num_els = min(BM, M - y_row); // const short num_outs = min(BN, N - y_col); - loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, K, Ws, simd_gid, simd_lid, global_scale); constexpr short SM = BM / WM; constexpr short SN = BN / WN; @@ -487,11 +534,12 @@ METAL_FUNC void adjust_matrix_offsets( y += tid.z * output_stride; } -template +template METAL_FUNC void adjust_matrix_offsets( const device T*& x, const device uint32_t*& w, const device S*& scales, + const device float*& global_scale, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, device T*& y, @@ -534,6 +582,10 @@ METAL_FUNC void adjust_matrix_offsets( w += idx.x; scales += idx.y; } + // One global scale per expert, contiguous over the batch dims of w. + if constexpr (has_global_scale) { + global_scale += w_idx; + } y += tid.z * output_stride; } @@ -548,10 +600,12 @@ template < const int BN = 64, const int WM = 2, const int WN = 2, + const bool has_global_scale = false, typename Wtype = bfloat> [[kernel]] void fp_qmm_t_nax( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, device T* y, const constant int& K, @@ -590,8 +644,19 @@ template < s_strides, tid); } - fp_qmm_t_impl( - w, scales, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + has_global_scale, + BM, + BK, + BN, + WM, + WN, + Wtype>( + w, scales, global_scale, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } template < @@ -649,8 +714,8 @@ template < tid); } - fp_qmm_n_impl( - w, scales, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_n_impl( + w, scales, nullptr, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } template < @@ -663,10 +728,12 @@ template < const int BN = 64, const int WM = 2, const int WN = 2, + const bool has_global_scale = false, typename Wtype = bfloat> [[kernel]] void fp_gather_qmm_t_nax( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, @@ -695,10 +762,11 @@ template < threadgroup Wtype Ws[BN * BK_padded]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -715,8 +783,19 @@ template < w_strides, s_strides, tid); - fp_qmm_t_impl( - w, scales, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_t_impl< + T, + group_size, + bits, + aligned_N, + has_global_scale, + BM, + BK, + BN, + WM, + WN, + Wtype>( + w, scales, global_scale, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } template < @@ -728,10 +807,12 @@ template < const int BN = 64, const int WM = 2, const int WN = 2, + const bool has_global_scale = false, typename Wtype = bfloat> [[kernel]] void fp_gather_qmm_n_nax( const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device T* x, const device uint32_t* lhs_indices, const device uint32_t* rhs_indices, @@ -762,10 +843,11 @@ template < threadgroup T Xs[BM * BK_padded]; threadgroup T Ws[BK * BN_padded]; - adjust_matrix_offsets( + adjust_matrix_offsets( x, w, scales, + global_scale, lhs_indices, rhs_indices, y, @@ -782,8 +864,8 @@ template < w_strides, s_strides, tid); - fp_qmm_n_impl( - w, scales, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + fp_qmm_n_impl( + w, scales, nullptr, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } template < @@ -796,11 +878,13 @@ template < int WM, int WN, bool transpose, + bool has_global_scale = false, typename Wtype = bfloat> [[kernel]] void fp_gather_qmm_rhs_nax( const device T* x, const device uint32_t* w, const device uint8_t* scales, + const device float* global_scale, const device int32_t* offsets, device T* y, const constant int& M, @@ -823,7 +907,8 @@ template < transpose, WM * WN * SIMD_SIZE, group_size, - bits>; + bits, + has_global_scale>; threadgroup Wtype Ws[transpose ? BN * BK_padded : BK * BN_padded]; @@ -895,7 +980,8 @@ template < transpose ? K : N, Ws, simd_group_id, - simd_lane_id); + simd_lane_id, + global_scale + group); dispatch_bool(rows_in_bounds, [&](auto kAlignedM) { dispatch_bool(align_N || !is_unaligned_bn, [&](auto kAlignedN) { @@ -992,3 +1078,148 @@ template < }); }); } + +template < + typename T, + int group_size, + int bits, + int WK = 8, + int BN = 32, + typename Wtype = bfloat> +[[kernel]] void fp_qmv_nax( + const device uint32_t* w, + const device uint8_t* scales, + const device T* x, + device T* y, + const constant int& K, + const constant int& N, + const constant int& M, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]]) { + static_assert(BN % 32 == 0, "BN should be divisible by 32"); + static_assert( + (group_size == 16 && bits == 4) || + (group_size == 32 && (bits == 4 || bits == 8)), + "qmv_nax reads nvfp4, mxfp4 and mxfp8"); + + using Frag = BaseNAXFrag; + using scale_bits_t = metal::conditional_t; + constexpr int BK = 128; + constexpr short TK = BK / 16; + constexpr short TN = BN / 16; + constexpr int pack_factor = 8 / bits; + constexpr short loads = bits / 4; + + const short2 coord = Frag::get_coord(); + const short fm = coord.y; + const int k_lane = 8 * coord.x; + const int row_bytes = K / pack_factor; + const int row_scales = K / group_size; + + const int y_col = tid.x * BN; + auto wl = (const device uint8_t*)w + + (y_col + fm) * static_cast(row_bytes) + k_lane / pack_factor; + scales += + (y_col + fm) * static_cast(row_scales) + k_lane / group_size; + x += fm * static_cast(K) + k_lane; + y += y_col; + const bool x_rows[2] = {fm < M, fm + 8 < M}; + + NAXTile Dtile; + Dtile.clear(); + + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec xs[2][4]; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + xs[r][i] = x_rows[r] + ? *(const device vec*)(x + r * 8 * static_cast(K) + + k + 8 * i) + : vec(0); + } + } + uint4 ws[TN][2][loads]; + scale_bits_t ss[TN][2]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + const device uint8_t* wt = + wl + row * static_cast(row_bytes) + k / pack_factor; + const device uint8_t* st = + scales + row * static_cast(row_scales) + k / group_size; + STEEL_PRAGMA_UNROLL + for (short l = 0; l < loads; l++) { + ws[t][r][l] = *(const device uint4*)(wt + 16 * l); + } + ss[t][r] = *(const device scale_bits_t*)st; + } + } + + STEEL_PRAGMA_UNROLL + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t a; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + } + } + typename Frag::template dtype_frag_t b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + uint q; + if constexpr (bits == 4) { + q = ws[t][r][0][f / 2] >> (16 * (f % 2)); + } else { + q = ws[t][r][f / 4][f % 4]; + } + uint8_t s = ss[t][r]; + if constexpr (group_size == 16) { + s = ss[t][r] >> (8 * (f / 4)); + } + const vec v = + dequantize_fp_x4(q, s); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant{}, + b[t], + b[t + 1], + metal::bool_constant{}); + } + } + } + + threadgroup float Ps[(WK - 1) * 16 * BN]; + if (simd_gid > 0) { + Dtile.template store(Ps + (simd_gid - 1) * 16 * BN); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_gid == 0) { + for (int i = 0; i < WK - 1; i++) { + NAXTile Ptile; + Ptile.template load(Ps + i * 16 * BN); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < Dtile.kNumFrags; j++) { + Dtile.val_frags[j] += Ptile.val_frags[j]; + } + } + Dtile.store_rows(y, N, M); + } +} diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.metal b/mlx/backend/metal/kernels/fp_quantized_nax.metal index 771b2a963a..5e008eec70 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.metal +++ b/mlx/backend/metal/kernels/fp_quantized_nax.metal @@ -1,4 +1,4 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. // clang-format off #include "mlx/backend/metal/kernels/utils.h" @@ -24,7 +24,14 @@ type, \ group_size, \ bits, \ - aligned, bm, bk, bn, wm, wn) + aligned, bm, bk, bn, wm, wn) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn "_alN_" #aligned "_hgs", \ + fp_ ## name, \ + type, \ + group_size, \ + bits, \ + aligned, bm, bk, bn, wm, wn, true) #define instantiate_quantized_aligned_batched(mode, name, type, bm, bn, bk, wm, wn, aligned, batched, group_size, bits) \ instantiate_kernel( \ @@ -36,6 +43,16 @@ aligned, \ batched, bm, bk, bn, wm, wn) +#define instantiate_quantized_aligned_batched_hgs(mode, name, type, bm, bn, bk, wm, wn, aligned, batched, group_size, bits) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn "_alN_" #aligned "_batch_" #batched "_hgs", \ + fp_ ## name, \ + type, \ + group_size, \ + bits, \ + aligned, \ + batched, bm, bk, bn, wm, wn, true) + #define instantiate_gather_qmm_rhs(func, name, type, bm, bn, bk, wm, wn, transpose, mode, group_size, bits) \ instantiate_kernel( \ #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_bm_" #bm "_bn_" #bn "_bk_" #bk "_wm_" #wm "_wn_" #wn, \ @@ -48,7 +65,20 @@ bk, \ wm, \ wn, \ - transpose) + transpose) \ + instantiate_kernel( \ + #mode "_" #name "_" #type "_gs_" #group_size "_b_" #bits "_bm_" #bm "_bn_" #bn "_bk_" #bk "_wm_" #wm "_wn_" #wn "_hgs", \ + func, \ + type, \ + group_size, \ + bits, \ + bm, \ + bn, \ + bk, \ + wm, \ + wn, \ + transpose, \ + true) #define instantiate_quantized_all_aligned(type, mode, group_size, bits) \ @@ -63,6 +93,12 @@ instantiate_quantized_aligned_batched(mode, qmm_t_nax, type, 32, 64, 64, 2, 2, false, 1, group_size, bits) \ instantiate_quantized_aligned_batched(mode, qmm_t_nax, type, 32, 64, 64, 2, 2, false, 0, group_size, bits) +#define instantiate_quantized_qmm_hgs(type) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t_nax, type, 64, 64, 64, 2, 2, true, 0, 16, 4) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t_nax, type, 64, 64, 64, 2, 2, false, 0, 16, 4) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t_nax, type, 32, 64, 64, 2, 2, true, 0, 16, 4) \ + instantiate_quantized_aligned_batched_hgs(nvfp4, qmm_t_nax, type, 32, 64, 64, 2, 2, false, 0, 16, 4) + #define instantiate_quantized_all_rhs(type, mode, group_size, bits) \ instantiate_gather_qmm_rhs(fp_gather_qmm_rhs_nax, gather_qmm_rhs_nax_nt, type, 64, 64, 64, 2, 2, true, mode, group_size, bits) \ @@ -79,7 +115,26 @@ instantiate_quantized_modes(type, mxfp8, 32, 8) \ instantiate_quantized_modes(type, mxfp4, 32, 4) +#define instantiate_qmv_nax(type, mode, group_size, bits, wk, bn) \ + instantiate_kernel( \ + #mode "_qmv_nax_" #type "_gs_" #group_size "_b_" #bits "_wk" #wk "_bn" #bn, \ + fp_qmv_nax, \ + type, \ + group_size, \ + bits, \ + wk, \ + bn) + +#define instantiate_qmv_nax_modes(type) \ + instantiate_qmv_nax(type, nvfp4, 16, 4, 8, 32) \ + instantiate_qmv_nax(type, mxfp8, 32, 8, 8, 32) \ + instantiate_qmv_nax(type, mxfp4, 32, 4, 8, 32) + instantiate_quantized_types(float) instantiate_quantized_types(bfloat16_t) instantiate_quantized_types(float16_t) +instantiate_quantized_qmm_hgs(bfloat16_t) +instantiate_qmv_nax_modes(float) +instantiate_qmv_nax_modes(bfloat16_t) +instantiate_qmv_nax_modes(float16_t) // clang-format on diff --git a/mlx/backend/metal/kernels/gated_delta_nax_ops.h b/mlx/backend/metal/kernels/gated_delta_nax_ops.h new file mode 100644 index 0000000000..e8e4069f6d --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_nax_ops.h @@ -0,0 +1,588 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include + +#include +#include + +#include "mlx/backend/metal/kernels/steel/gemm/nax.h" + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +typedef mlx::steel::NAXTile _M16x16; +typedef mlx::steel::NAXTile _M16x32; + +// NAX MACROS +#define AT_NAX(TILE, IDX) TILE.elems()[IDX] + +// out = a - b +template +METAL_FUNC T operator-(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) - b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator-(const thread T& a) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = -a.frag_at(0, f); + } + return out; +} + +// out = a + b +template +METAL_FUNC T operator+(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator+(const thread T& a, float addend) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) + addend; + } + return out; +} + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +// out = a * b, elementwise. Not a matmul. +template +METAL_FUNC T operator*(const thread T& a, const thread T& b) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T operator*(const thread T& a, float s) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * s; + } + return out; +} + +template +METAL_FUNC T fmadd(const thread T& a, const thread T& b, const thread T& c) { + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = a.frag_at(0, f) * b.frag_at(0, f) + c.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC _M16x16 reduce(const thread T& a) { + _M16x16 out; + out.frag_at(0, 0) = a.frag_at(0, 0); + STEEL_PRAGMA_UNROLL + for (short f = 1; f < T::kNumFrags; f++) { + out.frag_at(0, 0) += a.frag_at(0, f); + } + return out; +} + +template +METAL_FUNC T scale_rows(const thread T& tile, const thread float* s) { + typename T::frag_type sv; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + sv[i] = s[i >> 2]; + } + + T out; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + out.frag_at(0, f) = tile.frag_at(0, f) * sv; + } + return out; +} + +template +METAL_FUNC void row_sum(thread float* dst, const thread T& tile) { + STEEL_PRAGMA_UNROLL + for (short f = 0; f < T::kNumFrags; f++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < T::kElemsPerFrag; i++) { + dst[i >> 2] += tile.frag_at(0, f)[i]; + } + } +} + +// Scales row i by DEC2[group(i)] == exp(gamma_{C-1} - gamma_i). +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } + +#define SUB_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) - AT_NAX(TILE2, _i); \ + } \ + } + +#define ADD_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) + AT_NAX(TILE2, _i); \ + } \ + } + +#define FMA_NAX(TILE0, S, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { \ + (TILE0)[_i] = (S) * (TILE1)[_i] + (TILE2)[_i]; \ + } \ + } + +#define SCALE_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) *= (S); \ + } \ + } + +#define SCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define TRIL_NAX(TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) = (_c.x >= _c.y) ? 0.f : AT_NAX(TILE1, _i); \ + } \ + } + +#define SCALE_BETA_NAX(TILE0, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (BETA2)[_w >> 2]; \ + } \ + } + +#define SCALE2_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + const short _fm = mlx::steel::BaseNAXFrag::get_coord(_w).y; \ + AT_NAX(TILE0, _i) *= metal::fast::exp((GAMMA)[(C) - 1] - (GAMMA)[_fm]); \ + } \ + } + +#define SCALE_TRI_NAX(TILE0, GAMMA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x > _c.y) \ + ? 0.f \ + : metal::fast::exp((GAMMA)[_c.y] - (GAMMA)[_c.x]); \ + } \ + } + +#define SCALE_TRIEQ_NAX1(TILE0, BETA) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerFrag; _i++) { \ + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ \ + AT_NAX(TILE0, _i) *= (_c.x >= _c.y) ? 0.f : (BETA)[_i >> 2]; \ + } \ + } + +namespace mlx { +namespace steel { +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A0, + const thread BaseNAXFrag::dtype_frag_t& A1, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B0, + const thread BaseNAXFrag::dtype_frag_t& B1, + metal::bool_constant) { + // M=16, N=16, K=32: A and B each two K-fragments, single 16x16 C. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 16, 32, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A0[i]; + ct_a[BaseNAXFrag::kElemsPerFrag + i] = A1[i]; + ct_b[i] = B0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = B1[i]; + ct_c[i] = C[i]; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a, + bool transpose_b, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mma( + thread BaseNAXFrag::dtype_frag_t& C, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& B, + metal::bool_constant) { + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = B[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + ct_c[i] = C[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = 0.0; + } + + gemm_op.run(ct_a, ct_b, ct_c); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + C[i] = ct_c[i]; + } +} + +template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false, + mpp::tensor_ops::matmul2d_descriptor::mode Mode = + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate> +METAL_FUNC static constexpr void mman( + thread BaseNAXFrag::dtype_frag_t& Cn0, + thread BaseNAXFrag::dtype_frag_t& Cn1, + const thread BaseNAXFrag::dtype_frag_t& A, + metal::bool_constant, + const thread BaseNAXFrag::dtype_frag_t& Bn0, + const thread BaseNAXFrag::dtype_frag_t& Bn1, + metal::bool_constant) { + // M=16, N=32, K=16: single A (K=16), B and C two N-fragments each. + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, 32, 16, transpose_a, transpose_b, true, Mode); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + using ct_a_t = decltype(gemm_op.template get_left_input_cooperative_tensor< + AType, + BType, + CType>()); + using ct_b_t = decltype(gemm_op.template get_right_input_cooperative_tensor< + AType, + BType, + CType>()); + + // Create matmul operands in registers + auto ct_a = + gemm_op.template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = + gemm_op + .template get_destination_cooperative_tensor(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + ct_a[i] = A[i]; + ct_b[i] = Bn0[i]; + ct_b[BaseNAXFrag::kElemsPerFrag + i] = Bn1[i]; + ct_c[i] = Cn0[i]; + ct_c[BaseNAXFrag::kElemsPerFrag + i] = Cn1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BaseNAXFrag::kElemsPerFrag; i++) { + Cn0[i] = ct_c[i]; + Cn1[i] = ct_c[BaseNAXFrag::kElemsPerFrag + i]; + } +} + +} // namespace steel +} // namespace mlx + +#define MM16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + metal::bool_constant{}); + +#define MMA16x16x32(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mma< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + A.frag_at(0, (AO)), \ + A.frag_at(0, (AO) + 1), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MM16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +#define MMA16x32x16(C, CO, A, TA, AO, B, TB, BO) \ + mlx::steel::mman< \ + typename decltype(C)::elem_type, \ + typename decltype(A)::elem_type, \ + typename decltype(B)::elem_type, \ + TA, \ + TB, \ + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate>( \ + C.frag_at(0, (CO)), \ + C.frag_at(0, (CO) + 1), \ + A.frag_at(0, (AO)), \ + metal::bool_constant{}, \ + B.frag_at(0, (BO)), \ + B.frag_at(0, (BO) + 1), \ + metal::bool_constant{}); + +// Row sum of an elementwise product, reduced over the fragment's column axis. +// DST[0] is the fm row group, DST[1] the fm + kElemRowsJump group. +#define ROWSUM_NAX(DST, TILE0, TILE1) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i) * AT_NAX(TILE1, _i); \ + } \ + } + +// already generic +#define SCALE_BETA_NAX_O(DST, TILE, BETA2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(DST, _i) = AT_NAX(TILE, _i) * (BETA2)[_w >> 2]; \ + } \ + } + +#define ROWSUM1_NAX(DST, TILE0) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + (DST)[_w >> 2] += AT_NAX(TILE0, _i); \ + } \ + } + +#define MUL_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) = AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULA_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) += AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define MULS_NAX(TILE0, TILE1, TILE2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + AT_NAX(TILE0, _i) -= AT_NAX(TILE1, _i) * AT_NAX(TILE2, _i); \ + } \ + } + +#define NSCALE_ROW_NAX(TILE0, S) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * \ + metal::fast::exp((S)[mlx::steel::BaseNAXFrag::get_coord(_w).y]); \ + } \ + } + +#define SCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (ROW2)[_w >> 2]; \ + } \ + } + +// As SCALE_ROW_P but also negates, in one pass. +#define NSCALE_ROW_P(TILE0, ROW2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) = -AT_NAX(TILE0, _i) * (ROW2)[_w >> 2]; \ + } \ + } + +#define SCALE2_P(TILE0, DEC2) \ + { \ + STEEL_PRAGMA_UNROLL \ + for (short _i = 0; _i < decltype(TILE0)::kElemsPerTile; _i++) { \ + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; \ + AT_NAX(TILE0, _i) *= (DEC2)[_w >> 2]; \ + } \ + } \ No newline at end of file diff --git a/mlx/backend/metal/kernels/gated_delta_update.h b/mlx/backend/metal/kernels/gated_delta_update.h new file mode 100644 index 0000000000..78171e4b48 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update.h @@ -0,0 +1,366 @@ +#pragma once + +#include +#include "mlx/backend/metal/kernels/utils.h" + +constant bool save_state [[function_constant(200)]]; + +#define AT(TILE, IDX) TILE.thread_elements()[IDX] +#define SUB(TILE0, TILE1, TILE2) \ + { \ + AT(TILE0, 0) = AT(TILE1, 0) - AT(TILE2, 0); \ + AT(TILE0, 1) = AT(TILE1, 1) - AT(TILE2, 1); \ + } +#define ADD(TILE0, TILE1, TILE2) \ + { \ + AT(TILE0, 0) = AT(TILE1, 0) + AT(TILE2, 0); \ + AT(TILE0, 1) = AT(TILE1, 1) + AT(TILE2, 1); \ + } +#define FMA(TILE0, S, TILE1, TILE2) \ + { \ + AT(TILE0, 0) = S * AT(TILE1, 0) + AT(TILE2, 0); \ + AT(TILE0, 1) = S * AT(TILE1, 1) + AT(TILE2, 1); \ + } + +#define SCALE(TILE0, S) \ + { \ + AT(TILE0, 0) *= S; \ + AT(TILE0, 1) *= S; \ + } +#define SCALE2(TILE0, S0, S1) \ + { \ + AT(TILE0, 0) *= S0; \ + AT(TILE0, 1) *= S1; \ + } +#define SCALE_TRI(TILE0, S0, S1) \ + { \ + AT(TILE0, 0) *= fn > fm ? 0.f : S0; \ + AT(TILE0, 1) *= fn + 1 > fm ? 0.f : S1; \ + } +#define SCALE_TRIEQ(TILE0, S0, S1) \ + { \ + AT(TILE0, 0) *= fn >= fm ? 0.f : S0; \ + AT(TILE0, 1) *= fn + 1 >= fm ? 0.f : S1; \ + } + +// lambdas are not supported in metal 14 so porting to macros. + +// non transposed +#define LOAD_M(M, SRC, LD, B) \ + if constexpr (B) { \ + AT(M, 0) = \ + static_cast((fm < valid_rows) ? ((SRC)[fm * (LD) + fn]) : 0.f); \ + AT(M, 1) = static_cast( \ + (fm < valid_rows) ? ((SRC)[fm * (LD) + fn + 1]) : 0.f); \ + } else { \ + AT(M, 0) = static_cast((SRC)[fm * (LD) + fn]); \ + AT(M, 1) = static_cast((SRC)[fm * (LD) + fn + 1]); \ + } + +// transposed load: sequence is the column -> mask fn / fn+1 +#define LOAD_MT(M, SRC, LD, B) \ + if constexpr (B) { \ + AT(M, 0) = \ + static_cast((fn < valid_rows) ? ((SRC)[fn * (LD) + fm]) : 0.f); \ + AT(M, 1) = static_cast( \ + (fn + 1 < valid_rows) ? ((SRC)[(fn + 1) * (LD) + fm]) : 0.f); \ + } else { \ + AT(M, 0) = static_cast((SRC)[fn * (LD) + fm]); \ + AT(M, 1) = static_cast((SRC)[(fn + 1) * (LD) + fm]); \ + } + +#define PROCESS_CHUNK_SG(B, S_tile, VALID) \ + { \ + const short valid_rows = (VALID); \ + \ + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) \ + ? metal::fast::log( \ + metal::max( \ + static_cast( \ + g_[thread_index_in_simdgroup * Hv + hv_idx]), \ + 1e-6f)) \ + : 0.0f; \ + \ + float gamma_val = simd_prefix_inclusive_sum(g_val); \ + \ + if (thread_index_in_simdgroup < C) { \ + gamma[thread_index_in_simdgroup] = gamma_val; \ + } \ + simdgroup_barrier(mem_flags::mem_threadgroup); \ + \ + float gamma_fm = metal::fast::exp(gamma[fm]); \ + float gamma_fmdfn = metal::fast::exp(gamma[fm] - gamma[fn]); \ + float gamma_fmdfn1 = metal::fast::exp(gamma[fm] - gamma[fn + 1]); \ + float gamma_Cdfn = metal::fast::exp(gamma[C - 1] - gamma[fn]); \ + float gamma_Cdfn1 = metal::fast::exp(gamma[C - 1] - gamma[fn + 1]); \ + float gamma_C = metal::fast::exp(gamma[C - 1]); \ + \ + float beta_fm = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; \ + \ + KKt_tile = make_filled_simdgroup_matrix(0.f); \ + MLX_MTL_PRAGMA_UNROLL \ + for (int kk = 0; kk < Dk; kk += 8) { \ + LOAD_M(K_tile, k_ + kk, Dk * Hk, B) \ + LOAD_MT(KT_tile, k_ + kk, Dk * Hk, B) \ + simdgroup_multiply_accumulate(KKt_tile, K_tile, KT_tile, KKt_tile); \ + } \ + \ + KKtK_tile = KKt_tile; \ + SCALE_TRIEQ(KKtK_tile, beta_fm, beta_fm) \ + \ + simdgroup_float8x8 Tinv, P; \ + AT(P, 0) = AT(KKtK_tile, 0); \ + AT(P, 1) = AT(KKtK_tile, 1); \ + SUB(Tinv, I_tile, KKtK_tile) \ + \ + MLX_MTL_PRAGMA_UNROLL \ + for (int step = 1; (1 << step) < C; step++) { \ + simdgroup_multiply(P, P, P); \ + simdgroup_multiply_accumulate(Tinv, Tinv, P, Tinv); \ + } \ + \ + WS_tile = make_filled_simdgroup_matrix(0.f); \ + MLX_MTL_PRAGMA_UNROLL \ + for (int kk = 0; kk < Dk; kk += 8) { \ + LOAD_M(K_tile, k_ + kk, Dk * Hk, B) \ + SCALE(K_tile, beta_fm) \ + simdgroup_multiply(W_tile, Tinv, K_tile); \ + SCALE(W_tile, gamma_fm) \ + simdgroup_multiply_accumulate(WS_tile, W_tile, S_tile[kk / 8], WS_tile); \ + } \ + \ + SCALE_TRI(Tinv, gamma_fmdfn, gamma_fmdfn1) \ + \ + LOAD_M(V_tile, v_ + dv_idx, Dv * Hv, B) \ + SCALE(V_tile, beta_fm) \ + simdgroup_multiply(U_tile, Tinv, V_tile); \ + SUB(delta_tile, U_tile, WS_tile) \ + \ + tmp_tile = make_filled_simdgroup_matrix(0.f); \ + QKt_tile = make_filled_simdgroup_matrix(0.f); \ + MLX_MTL_PRAGMA_UNROLL \ + for (int kk = 0; kk < Dk; kk += 8) { \ + LOAD_M(Q_tile, q_ + kk, Hk * Dk, B) \ + LOAD_MT(K_tile, k_ + kk, Hk * Dk, B) \ + simdgroup_multiply_accumulate(QKt_tile, Q_tile, K_tile, QKt_tile); \ + SCALE(Q_tile, gamma_fm) \ + simdgroup_multiply_accumulate( \ + tmp_tile, Q_tile, S_tile[kk / 8], tmp_tile); \ + } \ + \ + SCALE_TRI(QKt_tile, gamma_fmdfn, gamma_fmdfn1) \ + \ + simdgroup_multiply_accumulate(out_tile, QKt_tile, delta_tile, tmp_tile); \ + \ + if (fm < valid_rows) { \ + y[fm * Hv * Dv + dv_idx + fn] = static_cast(AT(out_tile, 0)); \ + y[fm * Hv * Dv + dv_idx + fn + 1] = static_cast(AT(out_tile, 1)); \ + } \ + \ + MLX_MTL_PRAGMA_UNROLL \ + for (int kk = 0; kk < Dk; kk += 8) { \ + LOAD_MT(K_tile, k_ + kk, Hk * Dk, B) \ + SCALE2(K_tile, gamma_Cdfn, gamma_Cdfn1) \ + simdgroup_multiply(KD_tile, K_tile, delta_tile); \ + FMA(S_tile[kk / 8], gamma_C, S_tile[kk / 8], KD_tile) \ + } \ + } + +template +[[kernel]] void gated_delta_fused_chunk( + const device InT* q [[buffer(0)]], + const device InT* k [[buffer(1)]], + const device InT* v [[buffer(2)]], + const device float* state_in [[buffer(3)]], + const device InT* g [[buffer(4)]], + const device InT* beta [[buffer(5)]], + device InT* y [[buffer(6)]], + device float* state_out [[buffer(7)]], + constant int& T [[buffer(8)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + const short qid = thread_index_in_simdgroup / 4; + const short fm = (qid & 4) + + ((thread_index_in_simdgroup / 2) % 4); // row coordinate of the held tile + const short fn = (qid & 2) * 2 + + (thread_index_in_simdgroup % 2) * 2; // column coordinate of the held tile + + auto dv_idx = thread_position_in_grid.y * 8; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + +#define OUTPUT(T) \ + if (true) { \ + simdgroup_store(T, y); \ + return; \ + } + // set up pointers + // g: [B, T, Hv] + auto g_ = g + b_idx * T * Hv; + + // q, k: [B, T, Hk, Dk] + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk; + + // v, y: [B, T, Hv, Dv] + y += b_idx * T * Hv * Dv + hv_idx * Dv; + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv; + auto beta_ = beta + b_idx * T * Hv; + + // state_in, state_out: [B, Hv, Dv, Dk] + auto i_state = state_in + (n * Dv + dv_idx) * Dk; + auto o_state = state_out + (n * Dv + dv_idx) * Dk; + + simdgroup_float8x8 S_tile[Dk / 8]; + + // simdgroup matrices + simdgroup_float8x8 V_tile, K_tile, KT_tile, Q_tile; + simdgroup_float8x8 W_tile, U_tile; + simdgroup_float8x8 WS_tile; + simdgroup_float8x8 delta_tile; + simdgroup_float8x8 tmp_tile; + simdgroup_float8x8 QKt_tile; + simdgroup_float8x8 out_tile; + simdgroup_float8x8 KD_tile; + + // tiles for WY form computation + simdgroup_float8x8 KKtK_tile, KKt_tile; + + threadgroup float gamma_all[C * 4]; + threadgroup float* gamma = gamma_all + sg_id * C; + + simdgroup_float8x8 I_tile = make_filled_simdgroup_matrix(0.f); + AT(I_tile, 0) = (fm == fn) ? 1.0f : 0.0f; + AT(I_tile, 1) = (fm == fn + 1) ? 1.0f : 0.0f; + + // load initial state into registers + for (int kk = 0; kk < Dk; kk += 8) { + simdgroup_load(S_tile[kk / 8], i_state + kk, Dk, ulong2(0, 0), true); + } + + int t = 0; + MLX_MTL_PRAGMA_UNROLL + for (; t + C <= T; t += C) { + PROCESS_CHUNK_SG(false, S_tile, C); + q_ += C * Hk * Dk; + k_ += C * Hk * Dk; + v_ += C * Hv * Dv; + beta_ += C * Hv; + y += C * Hv * Dv; + g_ += C * Hv; + } + if (t < T) { + PROCESS_CHUNK_SG(true, S_tile, short(T - t)); + } + + MLX_MTL_PRAGMA_UNROLL + for (int kk = 0; kk < Dk; kk += 8) { + simdgroup_store(S_tile[kk / 8], o_state + kk, Dk, ulong2(0, 0), true); + } +} + +/* + auto grid = MTL::Size(32, Dv, B * Hv); + auto threads = MTL::Size(32, 4, 1); + */ +template +[[kernel]] void gated_delta_seq( + const device InT* q [[buffer(0)]], + const device InT* k [[buffer(1)]], + const device InT* v [[buffer(2)]], + const device float* state_in [[buffer(3)]], + const device InT* g [[buffer(4)]], // [B, T, Hv] + const device InT* beta [[buffer(5)]], // [B, T, Hv] + device InT* y [[buffer(6)]], // [B, T, Hv, Dv] + device float* state_out [[buffer(7)]], // [B, Hv, Dv, Dk] + constant int& T [[buffer(8)]], + device float* state_cache [[buffer(9), function_constant(save_state)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + constexpr int n_per_t = Dk / 32; + + // q, k: [B, T, Hk, Dk] + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk; + + // v, y: [B, T, Hv, Dv] + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv; + y += b_idx * T * Hv * Dv + hv_idx * Dv; + + auto dk_idx = thread_position_in_threadgroup.x; + auto dv_idx = thread_position_in_grid.y; + + // state_in, state_out: [B, Hv, Dv, Dk] + auto i_state = state_in + (n * Dv + dv_idx) * Dk; + auto o_state = state_out + (n * Dv + dv_idx) * Dk; + + float state[n_per_t]; + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + state[i] = static_cast(i_state[s_idx]); + } + + // g: [B, T, Hv] + auto g_ = g + b_idx * T * Hv; + auto beta_ = beta + b_idx * T * Hv; + + // Checkpoint every Ckpt-th step rather than every step: at T = 4096 with + // B = 4, Hv = 32 a dense cache is 34 GB, which the backward's replay makes + // unnecessary. + const int n_ckpt = (T + Ckpt - 1) / Ckpt; + auto c_state_base = state_cache + n * n_ckpt * Dv * Dk + dv_idx * Dk; + + for (int t = 0; t < T; ++t) { + // Stored before the decay, so slot t/Ckpt holds the state at *entry* to + // step t. The backward replays forward from here, so it must be the entry + // state and not the exit state. + if (save_state && (t % Ckpt) == 0) { + auto c_state = c_state_base + (t / Ckpt) * Dv * Dk; + for (int i = 0; i < n_per_t; ++i) { + c_state[n_per_t * dk_idx + i] = state[i]; + } + } + + float kv_mem = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + state[i] = state[i] * g_[hv_idx]; + kv_mem += state[i] * k_[s_idx]; + } + kv_mem = simd_sum(kv_mem); + + auto delta = (v_[dv_idx] - kv_mem) * beta_[hv_idx]; + + float out = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + state[i] = state[i] + k_[s_idx] * delta; + out += state[i] * q_[s_idx]; + } + out = simd_sum(out); + if (thread_index_in_simdgroup == 0) { + y[dv_idx] = static_cast(out); + } + // Increment data pointers to next time step + q_ += Hk * Dk; + k_ += Hk * Dk; + v_ += Hv * Dv; + y += Hv * Dv; + g_ += Hv; + beta_ += Hv; + } + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + o_state[s_idx] = static_cast(state[i]); + } +} \ No newline at end of file diff --git a/mlx/backend/metal/kernels/gated_delta_update.metal b/mlx/backend/metal/kernels/gated_delta_update.metal new file mode 100644 index 0000000000..f0797e80b6 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update.metal @@ -0,0 +1,50 @@ +#include "mlx/backend/metal/kernels/gated_delta_update.h" +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +#define instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, ckpt) \ + instantiate_kernel( \ + "seq_gated_delta_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv \ + "_" #ckpt, \ + gated_delta_seq, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + ckpt) + +#define instantiate_gated_delta_update_fused_chunk(in_type, dk, dv, hk, hv, c) \ + instantiate_kernel( \ + "gated_delta_fused_chunk_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv \ + "_" #c, \ + gated_delta_fused_chunk, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + c) + +// Ckpt is a template parameter of the sequential kernel, so the inference path +// has to name one even though it never stores. These must cover every value +// gated_delta_ckpt() can return, since the host puts it in the kernel name. +#define instantiate_gated_delta_dims(in_type, dk, dv, hk, hv) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 1) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 4) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 8) \ + instantiate_gated_delta_update_seq(in_type, dk, dv, hk, hv, 16) \ + instantiate_gated_delta_update_fused_chunk(in_type, dk, dv, hk, hv, 8) + +#define instantiate_gated_delta(in_type) \ + instantiate_gated_delta_dims(in_type, 128, 128, 24, 24) \ + instantiate_gated_delta_dims(in_type, 128, 128, 32, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 48) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 16) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 64) + +instantiate_gated_delta(float); +instantiate_gated_delta(bfloat16_t); +instantiate_gated_delta(float16_t); diff --git a/mlx/backend/metal/kernels/gated_delta_update_nax.h b/mlx/backend/metal/kernels/gated_delta_update_nax.h new file mode 100644 index 0000000000..09986fe807 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_nax.h @@ -0,0 +1,251 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include "mlx/backend/metal/kernels/gated_delta_nax_ops.h" + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +/////////////////////////////////////////////////////////////////////////////// +// Function constants +/////////////////////////////////////////////////////////////////////////////// + +constant bool save_state_cache [[function_constant(200)]]; + +template +[[kernel]] void gated_delta_fused_nax( + const device InT* q [[buffer(0)]], + const device InT* k [[buffer(1)]], + const device InT* v [[buffer(2)]], + const device float* state_in [[buffer(3)]], + const device InT* g [[buffer(4)]], + const device InT* beta [[buffer(5)]], + device InT* y [[buffer(6)]], + device float* state_out [[buffer(7)]], + constant int& T [[buffer(8)]], + device float* state_cache [[buffer(9)]], // [B, Hv, n_ckpt, Dv, Dk] + device float* chunk_mats [[buffer(10)]], // [B, Hv, n_chunks, 3, 16, 16] + device float* chunk_delta [[buffer(11)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + // set up pointers + // g: [B, T, Hv] + auto g_ = g + b_idx * T * Hv; + + // q, k: [B, T, Hk, Dk] + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk; + + // v, y: [B, T, Hv, Dv] + y += b_idx * T * Hv * Dv + hv_idx * Dv; + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv; + auto beta_ = beta + b_idx * T * Hv; + + // state_in, state_out: [B, Hv, Dv, Dk] + auto i_state = state_in + (n * Dv + dv_idx) * Dk; + auto o_state = state_out + (n * Dv + dv_idx) * Dk; + + const int n_chunks = (T + C - 1) / C; + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + auto c_state = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + + auto o_chunk_mats = chunk_mats + n * n_chunks * 3 * 256; + auto o_chunk_delta = chunk_delta + n * n_chunks * C * Dv + dv_idx; + + threadgroup float gamma_all[C * 4]; + threadgroup float* gamma = gamma_all + sg_id * C; + + float beta_fm[2]; + + mlx::steel::NAXTile S_tile; + S_tile.load(i_state, Dk); + + mlx::steel::NAXTile K_tile, Q_tile; + mlx::steel::NAXTile W_tile; // panel + + mlx::steel::NAXTile V_tile; + mlx::steel::NAXTile U_tile; + mlx::steel::NAXTile WS_tile; + mlx::steel::NAXTile delta_tile; + mlx::steel::NAXTile tmp_tile; + mlx::steel::NAXTile QKt_tile; + mlx::steel::NAXTile out_tile; + mlx::steel::NAXTile Tinv_tile, P; + + mlx::steel::NAXTile KKtK_tile, KKt_tile; + + mlx::steel::NAXTile I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + const short _fn = _c.x; + const short _fm = _c.y; + AT_NAX(I_tile, _i) = (_fn == _fm) ? 1.0f : 0.0f; + } + mlx::steel::NAXTile TMP_tile; + + // Which chunk process_chunk is on, so it knows whether this is a segment + // boundary. + int chunk_idx = 0; + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // Checkpoint the state entering this chunk before anything mutates it, on + // segment boundaries only. + if (save_state_cache && (chunk_idx % Ckpt) == 0) { + S_tile.store(c_state, Dk); + c_state += Dv * Dk; + } + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max( + float(g_[thread_index_in_simdgroup * Hv + hv_idx]), 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + KKt_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + MMA16x16x32(KKt_tile, 0, K_tile, false, 0, K_tile, true, 0); + } + + // KKt_raw is identical for every Dv tile of this chunk; only the first + // tile needs to write it out for the vjp kernel to reuse. + if (save_state_cache && dv_idx == 0) { + KKt_tile.store(o_chunk_mats, 16); + } + + KKtK_tile = KKt_tile; + + SCALE_TRIEQ_NAX1(KKtK_tile, beta_fm); + SUB_NAX(Tinv_tile, I_tile, KKtK_tile); + STEEL_PRAGMA_UNROLL + for (int step = 0; step < 15; step++) { + MM16x16x16(TMP_tile, 0, KKtK_tile, false, 0, Tinv_tile, false, 0); + SUB_NAX(Tinv_tile, I_tile, TMP_tile); + } + + // Same as KKt_raw: cache the pre-decay inverse before it is overwritten + // below by the gamma-scaled (TUinv) version. + if (save_state_cache && dv_idx == 0) { + Tinv_tile.store(o_chunk_mats + 256, 16); + } + + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < Dk / 16; nn += 2) { + load_seq(K_tile, k_ + nn * 16, Dk * Hk); + SCALE_BETA_NAX(K_tile, beta_fm); + MM16x32x16(W_tile, nn, Tinv_tile, false, 0, K_tile, false, 0); + } + SCALE_ROW_NAX(W_tile, gamma) + + SCALE_TRI_NAX(Tinv_tile, gamma) + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + SCALE_BETA_NAX(V_tile, beta_fm); + MM16x16x16(U_tile, 0, Tinv_tile, false, 0, V_tile, false, 0) + + WS_tile.clear(); + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < Dk / 16; kk += 2) { + MMA16x16x32(WS_tile, 0, W_tile, false, kk, S_tile, true, kk) + } + + SUB_NAX(delta_tile, U_tile, WS_tile) + + QKt_tile.clear(); + tmp_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Hk * Dk); + MMA16x16x32(QKt_tile, 0, Q_tile, false, 0, K_tile, true, 0); + SCALE_ROW_NAX(Q_tile, gamma); + MMA16x16x32(tmp_tile, 0, Q_tile, false, 0, S_tile, true, kk / 16); + } + + if (save_state_cache) { + if (dv_idx == 0) { + QKt_tile.store(o_chunk_mats + 512, 16); + } + // Every Dv tile stores its own slice. + delta_tile.store(o_chunk_delta, Dv); + o_chunk_mats += 3 * 256; + o_chunk_delta += C * Dv; + } + + // Output path runs unconditionally: the forward serves both inference and + // the training save, so y and state_out are always needed. + SCALE_TRI_NAX(QKt_tile, gamma) + out_tile = tmp_tile; + MMA16x16x16(out_tile, 0, QKt_tile, false, 0, delta_tile, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(out_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + const short _fn = _c.x; + const short _fm = _c.y; + if (_fm < valid_rows) { + y[_fm * Hv * Dv + dv_idx + _fn] = + static_cast(AT_NAX(out_tile, _i)); + } + } + + SCALE_NAX(S_tile, metal::fast::exp(gamma[C - 1])); + + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Hk * Dk); + SCALE2_NAX(K_tile, gamma); + MMA16x32x16(S_tile, kk / 16, delta_tile, true, 0, K_tile, false, 0); + } + + chunk_idx++; + }; + + int t = 0; + for (; t + C <= T; t += C) { + process_chunk(C, metal::false_type{}); + q_ += C * Hk * Dk; + k_ += C * Hk * Dk; + v_ += C * Hv * Dv; + beta_ += C * Hv; + y += C * Hv * Dv; + g_ += C * Hv; + } + if (t < T) { + process_chunk(short(T - t), metal::true_type{}); + } + + S_tile.store(o_state, Dk); +} diff --git a/mlx/backend/metal/kernels/gated_delta_update_nax.metal b/mlx/backend/metal/kernels/gated_delta_update_nax.metal new file mode 100644 index 0000000000..de84d866ce --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_nax.metal @@ -0,0 +1,36 @@ +#include "mlx/backend/metal/kernels/gated_delta_update_nax.h" +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +#define instantiate_gated_delta_update_fused_nax( \ + in_type, dk, dv, hk, hv, c, ckpt) \ + instantiate_kernel( \ + "gated_delta_fused_nax_" #in_type "_" #dk "_" #dv \ + "_" #hk "_" #hv "_" #c "_" #ckpt, \ + gated_delta_fused_nax, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + c, \ + ckpt) + +#define instantiate_gated_delta_dims(in_type, dk, dv, hk, hv) \ + instantiate_gated_delta_update_fused_nax(in_type, dk, dv, hk, hv, 16, 1) \ + instantiate_gated_delta_update_fused_nax(in_type, dk, dv, hk, hv, 16, 4) \ + instantiate_gated_delta_update_fused_nax(in_type, dk, dv, hk, hv, 16, 8) \ + instantiate_gated_delta_update_fused_nax(in_type, dk, dv, hk, hv, 16, 16) + +#define instantiate_gated_delta(in_type) \ + instantiate_gated_delta_dims(in_type, 128, 128, 24, 24) \ + instantiate_gated_delta_dims(in_type, 128, 128, 32, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 32) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 48) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 16) \ + instantiate_gated_delta_dims(in_type, 128, 128, 16, 64) + +instantiate_gated_delta(float); +instantiate_gated_delta(bfloat16_t); +instantiate_gated_delta(float16_t); \ No newline at end of file diff --git a/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h b/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h new file mode 100644 index 0000000000..3c2190f049 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h @@ -0,0 +1,1737 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include "mlx/backend/metal/kernels/gated_delta_nax_ops.h" + +#include +#include "mlx/backend/metal/kernels/atomic.h" + +using namespace metal; +using namespace mpp; +using namespace mpp::tensor_ops; + +template +METAL_FUNC void reduce_tile_tg( + thread TileT& acc, + threadgroup float* scratch, + device mlx_atomic* out, + int row_stride, + int col_off, + short valid_rows, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(sg_id * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _s = 1; _s < kNSG; _s++) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(_s * 32 + simd_lane_id) * kE + _i]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Simdgroup 0 alone holds the total. + if (sg_id != 0) { + return; + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * row_stride + col_off + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(out, AT_NAX(acc, _i), idx); + } else { + mlx_atomic_store_explicit(out, AT_NAX(acc, _i), idx); + } + } + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_ckpt, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + device float* seg_states [[buffer(17)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + const int n_chunks = (T + C - 1) / C; + // Ceiling: the floor form gives 0 when n_chunks < Ckpt, which would leave the + // allocation empty and fault on the first read. + const int n_ckpt = (n_chunks + Ckpt - 1) / Ckpt; + const short tail = short(T - (n_chunks - 1) * C); + + // Bases, indexed by chunk rather than walked. With two nested loops the + // incremental decrements are no longer expressible. + auto q_base = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_base = k + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dq_base = dq + b_idx * T * Hk * Dk + hk_idx * Dk; + auto dk_base = dk + b_idx * T * Hk * Dk + hk_idx * Dk; + + auto v_base = v + b_idx * T * Hv * Dv + hv_idx * Dv; + auto dv_base = dv + b_idx * T * Hv * Dv + hv_idx * Dv; + auto co_base = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv; + + auto g_base = g + b_idx * T * Hv; + auto beta_base = beta + b_idx * T * Hv; + auto dg_base = dg + b_idx * T * Hv; + auto db_base = db + b_idx * T * Hv; + + auto cm_base = chunk_mats + n * n_chunks * 3 * 256; + auto cd_base = chunk_delta + n * n_chunks * C * Dv + dv_idx; + auto ck_base = state_cache + (n * n_ckpt * Dv + dv_idx) * Dk; + // Each simdgroup owns a distinct dv slice, so these regions are disjoint and + // the replay needs no cross-simdgroup synchronisation. + auto seg_base = seg_states + (n * Ckpt * Dv + dv_idx) * Dk; + + // Per-chunk pointers, assigned from the bases before each process_chunk call. + auto q_ = q_base; + auto k_ = k_base; + auto dq_ = dq_base; + auto dk_ = dk_base; + auto v_ = v_base; + auto dv_ = dv_base; + auto co_ = co_base; + auto g_ = g_base; + auto beta_ = beta_base; + auto dg_ = dg_base; + auto db_ = db_base; + auto i_chunk_mats = cm_base; + auto i_chunk_delta = cd_base; + auto i_seg = seg_base; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, taken from the replayed segment. + _M16xDk S_tile; + + _M16x32 K_tile, Q_tile; + _M16x16 V_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // From the replayed segment rather than a per-chunk checkpoint. + S_tile.load(i_seg, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + if (fm < valid_rows) { + db_st[fm] = _b0; + } + if (fm1 < valid_rows) { + db_st[fm1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (fm == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (fm < valid_rows) { + dg_st[fm] = _d0; + } + if (fm1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (fm1 < valid_rows) { + dg_st[fm1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk segments in reverse. Each is replayed forward from its checkpoint to + // recover the entry states, then walked backwards. + // Backward over one segment: replay its entry states from the checkpoint, + // then walk it in reverse. HasTail is a compile-time tag so valid_rows is the + // constant C on every chunk of an interior segment, which folds away the + // row guards in the dq/dk stores and the load_rows switch in the replay. + auto process_segment = [&](const int seg, + auto tail_tag) __attribute__((always_inline)) { + constexpr bool HasTail = decltype(tail_tag)::value; + + const int seg_start = seg * Ckpt; + const int rem = n_chunks - seg_start; + const int n_in_seg = (rem < Ckpt) ? rem : Ckpt; + const int n_full = HasTail ? n_in_seg - 1 : n_in_seg; + + // delta is cached per chunk, so the replay is the state recurrence alone: + // S <- exp(gamma_C) S + K_dec^T delta + // No T^-1, no W, no U -- roughly a tenth of a full chunk's work, which is + // what makes trading Ckpt-fold memory for it worthwhile. + // + // Scoped so S is dead before process_chunk runs: it is a _M16xDk, and + // having it live alongside S_tile and dS_tile would put three of them in + // flight. + { + _M16xDk S; + S.load(ck_base + seg * Dv * Dk, Dk); + + auto replay_one = [&](const int j, + const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + S.store(seg_base + j * Dv * Dk, Dk); + + const int c = seg_start + j; + auto k_c = k_base + c * C * Hk * Dk; + auto g_c = g_base + c * C * Hv; + auto cd_c = cd_base + c * C * Dv; + + float gv = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max( + g_c[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + auto gs = simd_prefix_inclusive_sum(gv); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gs); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float g_last = gamma[C - 1]; + const float dec[2] = { + metal::fast::exp(g_last - gamma[fm]), + metal::fast::exp(g_last - gamma[fm1])}; + + _M16x16 delta_tile; + delta_tile.load(cd_c, Dv); + + S = S * metal::fast::exp(g_last); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 Kd; + if constexpr (B) { + Kd.load_rows(k_c + kk, Dk * Hk, valid_rows); + } else { + Kd.load(k_c + kk, Dk * Hk); + } + Kd = scale_rows(Kd, dec); + MMA16x32x16(S, kk / 16, delta_tile, true, 0, Kd, false, 0); + } + }; + + for (int j = 0; j < n_full; j++) { + replay_one(j, C, metal::false_type{}); + } + if constexpr (HasTail) { + replay_one(n_in_seg - 1, tail, metal::true_type{}); + } + } + + auto set_chunk_ptrs = [&](const int j) __attribute__((always_inline)) { + const int c = seg_start + j; + q_ = q_base + c * C * Hk * Dk; + k_ = k_base + c * C * Hk * Dk; + dq_ = dq_base + c * C * Hk * Dk; + dk_ = dk_base + c * C * Hk * Dk; + v_ = v_base + c * C * Hv * Dv; + dv_ = dv_base + c * C * Hv * Dv; + co_ = co_base + c * C * Hv * Dv; + g_ = g_base + c * C * Hv; + beta_ = beta_base + c * C * Hv; + dg_ = dg_base + c * C * Hv; + db_ = db_base + c * C * Hv; + i_chunk_mats = cm_base + c * 3 * 256; + i_chunk_delta = cd_base + c * C * Dv; + i_seg = seg_base + j * Dv * Dk; + }; + + if constexpr (HasTail) { + set_chunk_ptrs(n_in_seg - 1); + process_chunk(tail, metal::true_type{}); + } + for (int j = n_full - 1; j >= 0; --j) { + set_chunk_ptrs(j); + process_chunk(C, metal::false_type{}); + } + }; + + // Only the last segment can hold a short chunk + int seg = n_ckpt - 1; + if (tail != C) { + process_segment(seg, metal::true_type{}); + --seg; + } + for (; seg >= 0; --seg) { + process_segment(seg, metal::false_type{}); + } + + dS_tile.store(o_dh, Dk); +} + +template +[[kernel]] void gated_delta_vjp_fused_nax1( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 1) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + _M16x16 tril_mask; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tril_mask)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); + AT_NAX(tril_mask, _i) = (_c.x >= _c.y) ? 0.0f : 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw * tri_decay; + TUinv_tile = TWinv_tile * tri_decay; + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + dODT = dODT * tri_decay; + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + K_tile = scale_rows(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + _M16x32 Kb_tile = scale_rows(K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dq_acc = scale_rows(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg( + dq_acc, + red_scratch, + dq_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + dVb_tile = scale_rows(dVb_tile, beta_fm); + + dVb_tile.store_rows(dv_ + dv_idx, Hv * Dv, valid_rows); + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + V_tile = scale_rows(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + dTU_tile = dTU_tile * tri_decay; + + dTinv_tile = dTW_tile + dTU_tile; + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + dA_tile = dA_tile * -1.0f; + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = scale_rows(dA_tile, beta_fm) * tril_mask; + _M16x16 GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile = QKt_raw * dODT; + _M16x16 R_tile = TWinv_tile * dTU_tile; + dgam_pair = P_tile + R_tile; + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, t1; + + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + { + _M16x32 QgdOS; + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + dgam_row32 = dgam_row32 + scale_rows(QgdOS, row_exp) * Q_tile; + } + + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + dW_raw = scale_rows(-dW_raw, row_exp); + + { + _M16x32 dKb_tile; + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + KdKb = KdKb + dKb_tile * K_tile; // KdKb_tmp folded away + dk_acc = dk_acc + scale_rows(dKb_tile, beta_fm); + } + + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + t1 = scale_rows(t1, dec_exp); + dk_acc = dk_acc + t1; + + { + const _M16x32 KdKC = K_tile * t1; + dgam_row32 = dgam_row32 - KdKC; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC, _i); + } + } + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * + (S_tile.frag_at(0, kk / 16)[_i] * dS_tile.frag_at(0, kk / 16)[_i] + + S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]); + } + + { + _M16x32 TbK; + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + dgam_row32 = fmadd(TbK, dW_raw, dgam_row32); + } + + reduce_tile_tg( + dk_acc, + red_scratch, + dk_, + Hk * Dk, + kk, + valid_rows, + sg_id, + simd_lane_id); + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + + _M16x16 AKKt = dA_tile * KKt_tile; + AKKt = AKKt * tril_mask; + _M16x16 VdVb = fmadd(V_tile, TUddelta, AKKt); + row_sum(dbeta_acc, VdVb); + row_sum(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + float _b0 = dbeta_acc[0]; + float _b1 = dbeta_acc[1]; + _b0 += simd_shuffle_xor(_b0, ushort(1)); + _b0 += simd_shuffle_xor(_b0, ushort(8)); + _b1 += simd_shuffle_xor(_b1, ushort(1)); + _b1 += simd_shuffle_xor(_b1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_r0 < valid_rows) { + db_st[_r0] = _b0; + } + if (_r1 < valid_rows) { + db_st[_r1] = _b1; + } + } + + dgam_row = reduce(dgam_row32); + + float dgam_acc[2] = {0.0f, 0.0f}; + dgam_row = dgam_row + dgam_pair; + row_sum(dgam_acc, dgam_row); + + _M16x16 cs_tile; + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + + const float dgam_last_red = simd_sum(dgam_last); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + float _d0 = dgam_acc[0]; + float _d1 = dgam_acc[1]; + _d0 += simd_shuffle_xor(_d0, ushort(1)); + _d0 += simd_shuffle_xor(_d0, ushort(8)); + _d1 += simd_shuffle_xor(_d1, ushort(1)); + _d1 += simd_shuffle_xor(_d1, ushort(8)); + + const short _r0 = fm; + const short _r1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + + _d0 -= AT_NAX(cs_tile, 0); + _d1 -= AT_NAX(cs_tile, mlx::steel::BaseNAXFrag::kElemCols); + + if (_r0 == valid_rows - 1) { + _d0 += dgam_last_red; + } + if (_r0 < valid_rows) { + dg_st[_r0] = _d0; + } + if (_r1 == valid_rows - 1) { + _d1 += dgam_last_red; + } + if (_r1 < valid_rows) { + dg_st[_r1] = _d1; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + Q_tile = scale_rows(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + K_tile = scale_rows(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + W_raw = scale_rows(-W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +template +METAL_FUNC void reduce_tile_tg0( + thread TileT& acc, + threadgroup float* scratch, + const short sg_id, + const ushort simd_lane_id) { + constexpr short kE = TileT::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short lo = kNSG / 2; lo > 0; lo >>= 1) { + if (sg_id >= lo && sg_id < 2 * lo) { + const short dst = sg_id - lo; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + scratch[(dst * 32 + simd_lane_id) * kE + _i] = AT_NAX(acc, _i); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id < lo) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < kE; _i++) { + AT_NAX(acc, _i) += scratch[(sg_id * 32 + simd_lane_id) * kE + _i]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +template +[[kernel]] void gated_delta_vjp_fused_nax0( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* beta [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B, Hv, n_chunks, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device float* dg [[buffer(12)]], + device float* db [[buffer(13)]], + device float* dh [[buffer(14)]], + // Cached, chunk-local forward intermediates produced by the forward-save + // pass (see gated_delta_fused_nax): avoids redoing the K@K^T contraction, + // the 15-step Neumann inversion, and the W/U/S contraction for delta. + const device float* chunk_mats [[buffer(15)]], + const device float* chunk_delta [[buffer(16)]], // [B, Hv, n_chunks, C, Dv] + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + using _M16xDk = mlx::steel::NAXTile; + + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + + auto dv_idx = thread_position_in_grid.y * 16; + const short sg_id = thread_position_in_threadgroup.y; // 0..3 + + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + + const int n_chunks = (T + C - 1) / C; + const int t_last = (n_chunks - 1) * C; + + // Pointers positioned at the final chunk + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dq_ = dq + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + auto dk_ = dk + b_idx * T * Hk * Dk + hk_idx * Dk + t_last * Hk * Dk; + + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto dv_ = dv + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + auto co_ = cot_o + b_idx * T * Hv * Dv + hv_idx * Dv + t_last * Hv * Dv; + + auto g_ = g + b_idx * T * Hv + t_last * Hv; + auto beta_ = beta + b_idx * T * Hv + t_last * Hv; + auto dg_ = dg + b_idx * T * Hv + t_last * Hv; + auto db_ = db + b_idx * T * Hv + t_last * Hv; + + auto c_state = state_cache + (n * n_chunks * Dv + dv_idx) * Dk + + (n_chunks - 1) * Dv * Dk; + + // Cached forward intermediates, walked in reverse alongside c_state. + auto i_chunk_mats = + chunk_mats + n * n_chunks * 3 * 256 + (n_chunks - 1) * 3 * 256; + auto i_chunk_delta = + chunk_delta + n * n_chunks * C * Dv + dv_idx + (n_chunks - 1) * C * Dv; + + auto i_cot_h = cot_h + (n * Dv + dv_idx) * Dk; + auto o_dh = dh + (n * Dv + dv_idx) * Dk; + + // One threadgroup per (b, hv) now covers every Dv slice, so the Dv reduction + // never leaves threadgroup memory. + constexpr int kNSG = Dv / 16; + // Under GQA several threadgroups still share an hk, so dq/dk keep an atomic + // for that axis -- but with kNSG writers folded away first. + constexpr bool kGQA = (Hv != Hk); + + threadgroup float gamma_all[C * kNSG]; + threadgroup float* gamma = gamma_all + sg_id * C; + + // (kNSG/2) destinations x 32 lanes x kElemsPerTile(_M16x32) floats. + threadgroup float red_scratch[(kNSG / 2) * 32 * 16]; + threadgroup float db_stage[kNSG * C]; + threadgroup float dg_stage[kNSG * C]; + + float beta_fm[2]; + + // Carried state gradient, dL/dS. Same [dv, dk] orientation as S_tile. + _M16xDk dS_tile; + dS_tile.load(i_cot_h, Dk); + + // Forward state at chunk entry, reloaded from the checkpoint each chunk + _M16xDk S_tile; + + // Recomputed forward tiles + _M16x32 K_tile, Q_tile; + _M16xDk W_tile; + _M16x16 K16_tile, Q16_tile; + _M16x16 V_tile; + _M16x16 U_tile; + _M16x16 WS_tile; + _M16x16 delta_tile; + _M16x16 QKt_tile, QKt_raw; + _M16x16 KKt_tile; + _M16x16 TWinv_tile, TUinv_tile; + _M16x16 TMP_tile; + + // Backward tiles + _M16x16 dout_tile; + _M16x16 ddelta_tile; + _M16x16 dTU_tile, dTW_tile; + _M16x16 dTinv_tile; + _M16x16 dA_tile, G_tile; + _M16x16 tri_decay; + + _M16x16 I_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(I_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(I_tile, _i) = (_c.x == _c.y) ? 1.0f : 0.0f; + } + + _M16x16 NI_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(NI_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); /* {fn, fm} */ + AT_NAX(NI_tile, _i) = (_c.x == _c.y) ? -1.0f : 0.0f; + } + + _M16x16 Ones_tile; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(Ones_tile)::kElemsPerFrag; _i++) { + AT_NAX(Ones_tile, _i) = 1.0f; + } + + auto process_chunk = [&](const short valid_rows, + auto bounded_tag) __attribute__((always_inline)) { + constexpr bool B = decltype(bounded_tag)::value; + + auto load_seq = [&](thread auto& tile, auto src, int ld) { + if constexpr (B) { + tile.load_rows(src, ld, valid_rows); + } else { + tile.load(src, ld); + } + }; + + // reload the checkpoint + S_tile.load(c_state, Dk); + + float g_val = (thread_index_in_simdgroup < (uint)valid_rows) + ? metal::fast::log( + metal::max(g_[thread_index_in_simdgroup * Hv + hv_idx], 1e-6)) + : 0.0f; + + auto gamma_val = simd_prefix_inclusive_sum(g_val); + if (thread_index_in_simdgroup < C) { + gamma[thread_index_in_simdgroup] = static_cast(gamma_val); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float gamma_last = gamma[C - 1]; + const float gamma_last_exp = metal::fast::exp(gamma_last); + + beta_fm[0] = (fm < valid_rows) ? beta_[fm * Hv + hv_idx] : 0.0f; + const short fm1 = fm + mlx::steel::BaseNAXFrag::kElemRowsJump; + beta_fm[1] = (fm1 < valid_rows) ? beta_[fm1 * Hv + hv_idx] : 0.0f; + + // Per-lane decay factors. gamma[j] == gamma[valid_rows-1] for + // j >= valid_rows (the prefix sum of zeros), so the tail chunk needs no + // special case here. + const float row_exp[2] = { + metal::fast::exp(gamma[fm]), metal::fast::exp(gamma[fm1])}; + const float dec_exp[2] = { + metal::fast::exp(gamma_last - gamma[fm]), + metal::fast::exp(gamma_last - gamma[fm1])}; + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(tri_decay)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + AT_NAX(tri_decay, _i) = + (_c.x > _c.y) ? 0.f : metal::fast::exp(gamma[_c.y] - gamma[_c.x]); + } + + KKt_tile.load(i_chunk_mats, 16); + TWinv_tile.load(i_chunk_mats + 256, 16); + QKt_raw.load(i_chunk_mats + 512, 16); + + QKt_tile = QKt_raw; + MUL_NAX(QKt_tile, QKt_tile, tri_decay); + + TUinv_tile = TWinv_tile; + MUL_NAX(TUinv_tile, TUinv_tile, tri_decay); + + delta_tile.load(i_chunk_delta, Dv); + + // dgamma accumulators: + // dgam_row : per-row + // dgam_pair : row-minus-col + // dgam_last : the gamma_{C-1} + _M16x16 dgam_row, dgam_pair; + dgam_row.clear(); + dgam_pair.clear(); + float dgam_last = 0.0f; + float dbeta_acc[2] = {0.0f, 0.0f}; + + load_seq(dout_tile, co_ + dv_idx, Hv * Dv); + + // dODT = (dO @ delta.T * D) + _M16x16 dODT; + MM16x16x16(dODT, 0, dout_tile, false, 0, delta_tile, true, 0); + MUL_NAX(dODT, dODT, tri_decay); + + // cannot fuse this because ddelta is used by the next loop + MM16x16x16(ddelta_tile, 0, QKt_tile, true, 0, dout_tile, false, 0); + for (int kk = 0; kk < Dk; kk += 32) { + load_seq(K_tile, k_ + kk, Dk * Hk); + SCALE2_P(K_tile, dec_exp); + MMA16x16x32(ddelta_tile, 0, K_tile, false, 0, dS_tile, true, kk / 16); + } + + // ddelta = M^T @ dO + K_dec @ dS^T + // dq = gamma * (dO @ S) + dODT @ K + dTW_tile.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dW_raw; + _M16x32 dq_acc; + _M16x32 Kb_tile; + load_seq(K_tile, k_ + kk, Dk * Hk); + + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + + SCALE_BETA_NAX_O(Kb_tile, K_tile, beta_fm); + MMA16x16x32(dTW_tile, 0, dW_raw, false, 0, Kb_tile, true, 0); + + MM16x32x16(dq_acc, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(dq_acc, row_exp); + MMA16x32x16(dq_acc, 0, dODT, false, 0, K_tile, false, 0); + + // dq reduces over Dv, which is now entirely inside this threadgroup. + reduce_tile_tg(dq_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dq_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + const short _fn = _c.x + _f * 16; + const short _fm = _c.y; + if (_fm < valid_rows) { + const int idx = _fm * Hk * Dk + kk + _fn; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } else { + // Dv reduction done in threadgroup memory: single writer. + mlx_atomic_store_explicit(dq_, AT_NAX(dq_acc, _i), idx); + } + } + } + } + } + + // dv = B(Tu.T @ ddelta). Indexed by dv_idx, so no reduction. + _M16x16 dVb_tile; + MM16x16x16(dVb_tile, 0, TUinv_tile, true, 0, ddelta_tile, false, 0); + _M16x16 TUddelta = dVb_tile; // pre-beta, reused by dbeta + SCALE_BETA_NAX(dVb_tile, beta_fm); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dVb_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.y < valid_rows) { + dv_[_c.y * Hv * Dv + dv_idx + _c.x] = AT_NAX(dVb_tile, _i); + } + } + + // dT_U = ddelta @ (beta * V).T + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + SCALE_BETA_NAX(V_tile, beta_fm); + MM16x16x16(dTU_tile, 0, ddelta_tile, false, 0, V_tile, true, 0); + MUL_NAX(dTU_tile, dTU_tile, tri_decay); // dTinv = dT_W + (dT_U * D). + + ADD_NAX(dTinv_tile, dTW_tile, dTU_tile); + + // dA = -T.T @ dTinv @ T.T + MM16x16x16(TMP_tile, 0, TWinv_tile, true, 0, dTinv_tile, false, 0); + MM16x16x16(dA_tile, 0, TMP_tile, false, 0, TWinv_tile, true, 0); + SCALE_NAX(dA_tile, -1.0f); + + // G = tril_(dA) * beta, and GGt = G + G.T + G_tile = dA_tile; + SCALE_TRIEQ_NAX1(G_tile, beta_fm); + _M16x16 GGt_tile; + GGt_tile = G_tile; + MMA16x16x16(GGt_tile, 0, I_tile, true, 0, G_tile, true, 0); + + // dgamma pair sites + _M16x16 P_tile; + _M16x16 R_tile; + + MUL_NAX(P_tile, QKt_raw, dODT); + MUL_NAX(R_tile, TWinv_tile, dTU_tile); + ADD_NAX(dgam_pair, P_tile, R_tile); + + _M16x32 KdKb; // rowsum(K * dK_b) source, needed for dbeta + KdKb.clear(); + _M16x32 dgam_row32; + dgam_row32.clear(); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 dk_acc, dW_raw, dKb_tile, t1, KdKb_tmp; + _M16x32 QgdOS, TbK, KdKC_blk; + + load_seq(Q_tile, q_ + kk, Hk * Dk); // [16 x 32] + load_seq(K_tile, k_ + kk, Dk * Hk); // [16 x 32] + + // gamma: + rowsum(Q * gamma*(dO @ S)) + MM16x32x16(QgdOS, 0, dout_tile, false, 0, S_tile, false, kk / 16); + SCALE_ROW_P(QgdOS, row_exp); + MULA_NAX(dgam_row32, QgdOS, Q_tile); + + // dODT.T @ Q and (G + G.T) @ K + MM16x32x16(dk_acc, 0, dODT, true, 0, Q_tile, false, 0); + MMA16x32x16(dk_acc, 0, GGt_tile, false, 0, K_tile, false, 0); + + // B (T.T @ dW_raw), dW_raw = -gamma * (ddelta @ S) + MM16x32x16(dW_raw, 0, ddelta_tile, false, 0, S_tile, false, kk / 16); + NSCALE_ROW_P(dW_raw, row_exp); + MM16x32x16(dKb_tile, 0, TWinv_tile, true, 0, dW_raw, false, 0); + + // dbeta term uses dK_b before the beta scaling, with raw K + MUL_NAX(KdKb_tmp, dKb_tile, K_tile); + ADD_NAX(KdKb, KdKb, KdKb_tmp); + + SCALE_BETA_NAX(dKb_tile, beta_fm); + ADD_NAX(dk_acc, dk_acc, dKb_tile); + + // D_C * (delta @ dS) + MM16x32x16(t1, 0, delta_tile, false, 0, dS_tile, false, kk / 16); + SCALE2_P(t1, dec_exp); + ADD_NAX(dk_acc, dk_acc, t1); + + // gamma stuff + MUL_NAX(KdKC_blk, K_tile, t1); + SUB_NAX(dgam_row32, dgam_row32, KdKC_blk); + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(KdKC_blk)::kElemsPerTile; _i++) { + dgam_last += AT_NAX(KdKC_blk, _i); + } + + // gamma stuff: gamma_C * sum(S * dS) + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16)[_i] * + dS_tile.frag_at(0, kk / 16)[_i]; + dgam_last += gamma_last_exp * S_tile.frag_at(0, kk / 16 + 1)[_i] * + dS_tile.frag_at(0, kk / 16 + 1)[_i]; + } + + // gamma stuff + SCALE_BETA_NAX(K_tile, beta_fm); + SCALE_NAX(dW_raw, -1.0f); + MM16x32x16(TbK, 0, TWinv_tile, false, 0, K_tile, false, 0); + MULS_NAX(dgam_row32, TbK, dW_raw); + + // dk reduces over Dv the same way dq does. + reduce_tile_tg(dk_acc, red_scratch, sg_id, simd_lane_id); + + if (sg_id == 0) { + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dk_acc)::kElemsPerTile; _i++) { + const short _f = _i / mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short _w = _i % mlx::steel::BaseNAXFrag::kElemsPerFrag; + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_w); // {fn, fm} + if (_c.y < valid_rows) { + const int idx = _c.y * Hk * Dk + kk + _c.x + _f * 16; + if (kGQA) { + mlx_atomic_fetch_add_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } else { + mlx_atomic_store_explicit(dk_, AT_NAX(dk_acc, _i), idx); + } + } + } + } + } + + // dbeta = rowsum(V * dV_b) + rowsum(K * dK_b) + rowsum(tril_(dA) * KKt) + _M16x16 VdVb; + load_seq(V_tile, v_ + dv_idx, Dv * Hv); + MUL_NAX(VdVb, V_tile, TUddelta); + + _M16x16 AKKt; + TRIL_NAX(AKKt, dA_tile); + MUL_NAX(AKKt, AKKt, KKt_tile); + + ADD_NAX(VdVb, VdVb, AKKt); + ROWSUM1_NAX(dbeta_acc, VdVb); + ROWSUM1_NAX(dbeta_acc, KdKb); + + { + threadgroup float* db_st = db_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _r = 0; _r < 2; _r++) { + float _b = dbeta_acc[_r]; + _b += simd_shuffle_xor(_b, ushort(1)); + _b += simd_shuffle_xor(_b, ushort(8)); + + const short _row = fm + _r * mlx::steel::BaseNAXFrag::kElemRowsJump; + if (_row < valid_rows) { + db_st[_row] = _b; + } + } + } + + // Fold the two fragments: only the row sum of dgam_row is used downstream, + // and row sums are additive across fragments. + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < mlx::steel::BaseNAXFrag::kElemsPerFrag; _i++) { + AT_NAX(dgam_row, _i) = AT_NAX(dgam_row32, _i) + + AT_NAX(dgam_row32, mlx::steel::BaseNAXFrag::kElemsPerFrag + _i); + } + + // reduce and store dgamma: rowsum(row + pair) - colsum(pair) + ADD_NAX(dgam_row, dgam_row, dgam_pair); + _M16x16 dgam_tile, cs_tile; + MM16x16x16(dgam_tile, 0, dgam_row, false, 0, Ones_tile, false, 0); + MM16x16x16(cs_tile, 0, dgam_pair, true, 0, Ones_tile, false, 0); + SUB_NAX(dgam_tile, dgam_tile, cs_tile); + + { + threadgroup float* dg_st = dg_stage + sg_id * C; + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(dgam_tile)::kElemsPerFrag; _i++) { + const short2 _c = mlx::steel::BaseNAXFrag::get_coord(_i); // {fn, fm} + if (_c.x == 0) { + dg_st[_c.y] = AT_NAX(dgam_tile, _i); + } + } + // The gamma_{C-1}-only term lands on the same slot the loop just wrote, + // so the lanes must be ordered before lane 0 accumulates into it. + simdgroup_barrier(mem_flags::mem_threadgroup); + const float dgam_last_red = simd_sum(dgam_last); + if (simd_lane_id == 0 && valid_rows > 0) { + dg_st[valid_rows - 1] += dgam_last_red; + } + } + + // One barrier serves both stages; simdgroup 0 commits. + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg_id == 0 && thread_index_in_simdgroup < (uint)valid_rows) { + float b_sum = 0.0f; + float g_sum = 0.0f; + STEEL_PRAGMA_UNROLL + for (short _s = 0; _s < kNSG; _s++) { + b_sum += db_stage[_s * C + thread_index_in_simdgroup]; + g_sum += dg_stage[_s * C + thread_index_in_simdgroup]; + } + const int idx = thread_index_in_simdgroup * Hv + hv_idx; + db_[idx] = b_sum; + dg_[idx] = g_sum; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // dS update + // dS = gamma_C * dS + dO.T @ (gamma * Q) - ddelta.T @ W + SCALE_NAX(dS_tile, gamma_last_exp); + for (int kk = 0; kk < Dk; kk += 32) { + _M16x32 term, W_raw; + load_seq(Q_tile, q_ + kk, Hk * Dk); + load_seq(K_tile, k_ + kk, Dk * Hk); + + // dO.T @ (gamma * Q) -> [dv, dk] + SCALE_ROW_P(Q_tile, row_exp); + MM16x32x16(term, 0, dout_tile, true, 0, Q_tile, false, 0); + + // - ddelta.T @ W, with W = gamma * (TWinv @ beta*K) + SCALE_BETA_NAX(K_tile, beta_fm); + MM16x32x16(W_raw, 0, TWinv_tile, false, 0, K_tile, false, 0); + NSCALE_ROW_P(W_raw, row_exp); + MMA16x32x16(term, 0, ddelta_tile, true, 0, W_raw, false, 0); + + STEEL_PRAGMA_UNROLL + for (short _i = 0; _i < decltype(term)::kElemsPerFrag; _i++) { + dS_tile.frag_at(0, kk / 16)[_i] += AT_NAX(term, _i); + dS_tile.frag_at(0, kk / 16 + 1)[_i] += + AT_NAX(term, decltype(term)::kElemsPerFrag + _i); + } + } + }; + + // Walk chunks in reverse. The tail chunk comes first. + int c = n_chunks - 1; + const short tail = short(T - c * C); + if (tail != C) { + process_chunk(tail, metal::true_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + --c; + } + for (; c >= 0; --c) { + process_chunk(C, metal::false_type{}); + q_ -= C * Hk * Dk; + k_ -= C * Hk * Dk; + v_ -= C * Hv * Dv; + co_ -= C * Hv * Dv; + g_ -= C * Hv; + beta_ -= C * Hv; + dq_ -= C * Hk * Dk; + dk_ -= C * Hk * Dk; + dv_ -= C * Hv * Dv; + dg_ -= C * Hv; + db_ -= C * Hv; + c_state -= Dv * Dk; + i_chunk_mats -= 3 * 256; + i_chunk_delta -= C * Dv; + } + + dS_tile.store(o_dh, Dk); +} + +// Postprocessing dg. Similar idea to what is done in the triton kernel. +// The kernel computes the gradient with respect to the log. +template +[[kernel]] void gated_delta_dgamma_to_dg( + const device InT* g [[buffer(0)]], + device float* dg [[buffer(1)]], // in: dL/dgamma, out: dL/dg + constant int& T [[buffer(2)]], + constant int& Hv [[buffer(3)]], + constant int& n_total [[buffer(4)]], // B * Hv + uint2 pos [[thread_position_in_grid]]) { + const int n = int(pos.x); // b * Hv + hv + const int c = int(pos.y); // chunk index + + if (n >= n_total) { + return; + } + + const int t0 = c * C; + if (t0 >= T) { + return; + } + const int len = min(C, T - t0); + + const int b_idx = n / Hv; + const int hv_idx = n % Hv; + const int base = b_idx * T * Hv + hv_idx; + + float acc = 0.0f; + for (int j = len - 1; j >= 0; --j) { + const int idx = base + (t0 + j) * Hv; + acc += static_cast(dg[idx]); + float gv = metal::max(static_cast(g[idx]), 1e-6f); + dg[idx] = acc / gv; + } +} diff --git a/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.metal b/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.metal new file mode 100644 index 0000000000..954478d425 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_nax_vjp.metal @@ -0,0 +1,44 @@ +#include "mlx/backend/metal/kernels/gated_delta_update_nax_vjp.h" +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +#define instantiate_gdu_vjp_nax(in_type, dk, dv, hk, hv, c, ckpt) \ + instantiate_kernel( \ + "gated_delta_vjp_fused_nax_" #in_type "_" #dk "_" #dv \ + "_" #hk "_" #hv "_" #c "_" #ckpt, \ + gated_delta_vjp_fused_nax, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + c, \ + ckpt) + +#define instantiate_gdu_vjp_dims(in_type, dk, dv, hk, hv) \ + instantiate_gdu_vjp_nax(in_type, dk, dv, hk, hv, 16, 1) \ + instantiate_gdu_vjp_nax(in_type, dk, dv, hk, hv, 16, 4) \ + instantiate_gdu_vjp_nax(in_type, dk, dv, hk, hv, 16, 8) \ + instantiate_gdu_vjp_nax(in_type, dk, dv, hk, hv, 16, 16) + +#define instantiate_gdu_vjp(in_type) \ + instantiate_gdu_vjp_dims(in_type, 128, 128, 24, 24) \ + instantiate_gdu_vjp_dims(in_type, 128, 128, 32, 32) \ + instantiate_gdu_vjp_dims(in_type, 128, 128, 16, 32) \ + instantiate_gdu_vjp_dims(in_type, 128, 128, 16, 16) \ + instantiate_gdu_vjp_dims(in_type, 128, 128, 16, 48) + +instantiate_gdu_vjp(float); +instantiate_gdu_vjp(bfloat16_t); + +// Postprocessing: converts dL/dgamma to dL/dg. Not templated on ckpt. +#define instantiate_gdu_dgamma(in_type, c) \ + instantiate_kernel( \ + "gated_delta_dgamma_to_dg_" #in_type "_" #c, \ + gated_delta_dgamma_to_dg, \ + in_type, \ + c) + +instantiate_gdu_dgamma(float, 16); +instantiate_gdu_dgamma(bfloat16_t, 16); diff --git a/mlx/backend/metal/kernels/gated_delta_update_vjp.h b/mlx/backend/metal/kernels/gated_delta_update_vjp.h new file mode 100644 index 0000000000..13b96416c7 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_vjp.h @@ -0,0 +1,184 @@ +// Copyright © 2024 Apple Inc. +#pragma once + +#include +#include + +#include "mlx/backend/metal/kernels/atomic.h" +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +template +[[kernel]] void gated_delta_vjp_seq( + const device InT* q [[buffer(0)]], // [B, T, Hk, Dk] + const device InT* k [[buffer(1)]], // [B, T, Hk, Dk] + const device InT* v [[buffer(2)]], // [B, T, Hv, Dv] + const device InT* g [[buffer(3)]], // [B, T, Hv] + const device InT* b [[buffer(4)]], // [B, T, Hv] + const device InT* cot_o [[buffer(5)]], // [B, T, Hv, Dv] + const device float* cot_h [[buffer(6)]], // [B, Hv, Dv, Dk] + const device float* state_cache [[buffer(7)]], // [B*Hv, n_ckpt, Dv, Dk] + constant int& T [[buffer(8)]], + device mlx_atomic* dq [[buffer(9)]], + device mlx_atomic* dk [[buffer(10)]], + device float* dv [[buffer(11)]], + device mlx_atomic* dg [[buffer(12)]], + device mlx_atomic* db [[buffer(13)]], + device float* dh [[buffer(14)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + constexpr int n_per_t = Dk / 32; + + auto dk_idx = thread_position_in_threadgroup.x; + auto dv_idx = thread_position_in_grid.y; + + const int qk_stride = Hk * Dk; + const int v_stride = Hv * Dv; + const int g_stride = Hv; + + auto q_base = q + b_idx * T * qk_stride + hk_idx * Dk; + auto k_base = k + b_idx * T * qk_stride + hk_idx * Dk; + auto dq_base = dq + b_idx * T * qk_stride + hk_idx * Dk; + auto dk_base = dk + b_idx * T * qk_stride + hk_idx * Dk; + + auto v_base = v + b_idx * T * v_stride + hv_idx * Dv; + auto dv_base = dv + b_idx * T * v_stride + hv_idx * Dv; + auto co_base = cot_o + b_idx * T * v_stride + hv_idx * Dv; + + auto g_base = g + b_idx * T * g_stride + hv_idx; + auto b_base = b + b_idx * T * g_stride + hv_idx; + auto dg_base = dg + b_idx * T * g_stride + hv_idx; + auto db_base = db + b_idx * T * g_stride + hv_idx; + + const int n_ckpt = (T + Ckpt - 1) / Ckpt; + + float s_hat[n_per_t]; + auto base_state = cot_h + (n * Dv + dv_idx) * Dk; + for (int i = 0; i < n_per_t; i++) { + s_hat[i] = base_state[n_per_t * dk_idx + i]; + } + + // Only this thread's n_per_t slice of the state is ever needed, so a whole + // segment of entry states costs Ckpt * n_per_t registers and the replay needs + // no device buffer. + float seg[Ckpt][n_per_t]; + float s_prev[n_per_t]; + float s_dec[n_per_t]; + + for (int seg_idx = n_ckpt - 1; seg_idx >= 0; --seg_idx) { + const int t0 = seg_idx * Ckpt; + const int seg_len = metal::min(Ckpt, T - t0); + + // Replay forward from the checkpoint, recording the entry state of each + // step in the segment. + auto c_state = + state_cache + n * n_ckpt * Dv * Dk + seg_idx * Dv * Dk + dv_idx * Dk; + + float s[n_per_t]; + for (int i = 0; i < n_per_t; ++i) { + s[i] = c_state[n_per_t * dk_idx + i]; + } + + for (int j = 0; j < seg_len; ++j) { + const int t = t0 + j; + + for (int i = 0; i < n_per_t; ++i) { + seg[j][i] = s[i]; + } + + float gamma = static_cast(g_base[t * g_stride]); + float beta = static_cast(b_base[t * g_stride]); + + auto k_t = k_base + t * qk_stride; + + float kv_mem = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + const int s_idx = n_per_t * dk_idx + i; + s[i] *= gamma; + kv_mem += s[i] * static_cast(k_t[s_idx]); + } + kv_mem = simd_sum(kv_mem); + + float delta = + beta * (static_cast(v_base[t * v_stride + dv_idx]) - kv_mem); + + for (int i = 0; i < n_per_t; ++i) { + s[i] += delta * static_cast(k_t[n_per_t * dk_idx + i]); + } + } + + // Backward over the same steps, newest first. + for (int j = seg_len - 1; j >= 0; --j) { + const int t = t0 + j; + + float gamma = static_cast(g_base[t * g_stride]); + float beta = static_cast(b_base[t * g_stride]); + + auto q_t = q_base + t * qk_stride; + auto k_t = k_base + t * qk_stride; + auto dq_t = dq_base + t * qk_stride; + auto dk_t = dk_base + t * qk_stride; + + float kv_mem = 0.0f; + float co = static_cast(co_base[t * v_stride + dv_idx]); + float w = 0.0f; + for (int i = 0; i < n_per_t; i++) { + const int s_idx = n_per_t * dk_idx + i; + s_prev[i] = seg[j][i]; + s_dec[i] = s_prev[i] * gamma; + kv_mem += s_dec[i] * static_cast(k_t[s_idx]); + + s_hat[i] += co * static_cast(q_t[s_idx]); + + w += s_hat[i] * static_cast(k_t[s_idx]); + } + kv_mem = simd_sum(kv_mem); + w = simd_sum(w); + + if (thread_index_in_simdgroup == 0) { + dv_base[t * v_stride + dv_idx] = beta * w; + } + + float u = static_cast(v_base[t * v_stride + dv_idx]) - kv_mem; + float delta = beta * u; + + if (thread_index_in_simdgroup == 0) { + mlx_atomic_fetch_add_explicit(db_base + t * g_stride, w * u, 0); + } + + float dgamma = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + + float s_t = s_dec[i] + delta * static_cast(k_t[s_idx]); + mlx_atomic_fetch_add_explicit(dq_t, co * s_t, s_idx); + + float contrib = beta * (u * s_hat[i] - w * s_dec[i]); + mlx_atomic_fetch_add_explicit(dk_t, contrib, s_idx); + + s_hat[i] -= beta * w * static_cast(k_t[s_idx]); + + dgamma += s_hat[i] * s_prev[i]; + } + dgamma = simd_sum(dgamma); + if (thread_index_in_simdgroup == 0) { + mlx_atomic_fetch_add_explicit(dg_base + t * g_stride, dgamma, 0); + } + + for (int i = 0; i < n_per_t; ++i) { + s_hat[i] *= gamma; + } + } + } + + for (int i = 0; i < n_per_t; ++i) { + auto s_idx = n_per_t * dk_idx + i; + dh[(n * Dv + dv_idx) * Dk + s_idx] = s_hat[i]; + } +} diff --git a/mlx/backend/metal/kernels/gated_delta_update_vjp.metal b/mlx/backend/metal/kernels/gated_delta_update_vjp.metal new file mode 100644 index 0000000000..7112750d41 --- /dev/null +++ b/mlx/backend/metal/kernels/gated_delta_update_vjp.metal @@ -0,0 +1,35 @@ +#include "mlx/backend/metal/kernels/gated_delta_update_vjp.h" +#include "mlx/backend/metal/kernels/gated_delta_update.h" +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +#define instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, ckpt) \ + instantiate_kernel( \ + "seq_gated_delta_vjp_" #in_type "_" #dk "_" #dv "_" #hk "_" #hv \ + "_" #ckpt, \ + gated_delta_vjp_seq, \ + in_type, \ + dk, \ + dv, \ + hk, \ + hv, \ + ckpt) + +#define instantiate_gated_delta_vjp_dims(in_type, dk, dv, hk, hv) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 1) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 4) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 8) \ + instantiate_gdn_vjp_seq(in_type, dk, dv, hk, hv, 16) + +#define instantiate_gated_delta_vjp(in_type) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 24, 24) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 32, 32) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 32) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 48) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 16) \ + instantiate_gated_delta_vjp_dims(in_type, 128, 128, 16, 64) + +instantiate_gated_delta_vjp(float); +instantiate_gated_delta_vjp(bfloat16_t); +instantiate_gated_delta_vjp(float16_t); \ No newline at end of file diff --git a/mlx/backend/metal/kernels/gemv_masked.h b/mlx/backend/metal/kernels/gemv_masked.h index 58ab744050..18c2699060 100644 --- a/mlx/backend/metal/kernels/gemv_masked.h +++ b/mlx/backend/metal/kernels/gemv_masked.h @@ -452,7 +452,7 @@ struct GEMVTKernel { const int n_block_idx = blockM > blockN ? out_col / blockM : int(tid.x); const int out_mask_offset = - !has_output_mask ? 0 : n_block_idx; // * out_mask_strides[0]; + !has_output_mask ? 0 : n_block_idx * out_mask_strides[0]; int mat_mask_offset = !has_operand_mask ? 0 : n_block_idx * mat_mask_strides[0]; diff --git a/mlx/backend/metal/kernels/indexing/masked_scatter.h b/mlx/backend/metal/kernels/indexing/masked_scatter.h index 2ba5474000..fe2e2b2fe5 100644 --- a/mlx/backend/metal/kernels/indexing/masked_scatter.h +++ b/mlx/backend/metal/kernels/indexing/masked_scatter.h @@ -32,7 +32,7 @@ template if (src_contiguous) { out[idx] = src[batch_idx * src_batch_size + src_index]; } else { - out[idx] = src[elem_to_loc( + out[idx] = src[elem_to_loc( batch_idx * src_batch_size + src_index, src_shapes, src_strides, diff --git a/mlx/backend/metal/kernels/indexing/scatter.h b/mlx/backend/metal/kernels/indexing/scatter.h index 3604f20f61..56fead7680 100644 --- a/mlx/backend/metal/kernels/indexing/scatter.h +++ b/mlx/backend/metal/kernels/indexing/scatter.h @@ -38,8 +38,8 @@ METAL_FUNC void scatter_impl( for (int j = 0; j < NWORK && ind_idx < idx_size; ++j, ind_idx++) { LocT out_idx = out_offset; for (int i = 0; i < NIDX; ++i) { - auto idx_loc = indices.row_contiguous[i] - ? ind_idx + LocT idx_loc = indices.row_contiguous[i] + ? LocT(ind_idx) : elem_to_loc( ind_idx, &indices.shapes[indices.ndim * i], @@ -50,7 +50,7 @@ METAL_FUNC void scatter_impl( out_idx += static_cast(idx_val) * static_cast(out_strides[ax]); } - auto upd_idx = ind_idx * static_cast(upd_size) + gid.x; + LocT upd_idx = ind_idx * static_cast(upd_size) + gid.x; if constexpr (!UPD_ROW_CONTIG) { upd_idx = elem_to_loc(upd_idx, upd_shape, upd_strides, upd_ndim); } diff --git a/mlx/backend/metal/kernels/quantized.h b/mlx/backend/metal/kernels/quantized.h index ad347e113f..19c429dd54 100644 --- a/mlx/backend/metal/kernels/quantized.h +++ b/mlx/backend/metal/kernels/quantized.h @@ -28,13 +28,28 @@ inline constexpr short get_bytes_per_pack() { template inline U load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; @@ -107,13 +122,28 @@ inline U load_vector(const device T* x, thread U* x_thread) { template inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; @@ -196,13 +226,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -298,13 +342,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -395,11 +453,25 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + result[8 * i] += x * (select(U(0), scale, bool(wb & 0x01)) + bias); + result[8 * i + 1] += x * (select(U(0), scale, bool(wb & 0x02)) + bias); + result[8 * i + 2] += x * (select(U(0), scale, bool(wb & 0x04)) + bias); + result[8 * i + 3] += x * (select(U(0), scale, bool(wb & 0x08)) + bias); + result[8 * i + 4] += x * (select(U(0), scale, bool(wb & 0x10)) + bias); + result[8 * i + 5] += x * (select(U(0), scale, bool(wb & 0x20)) + bias); + result[8 * i + 6] += x * (select(U(0), scale, bool(wb & 0x40)) + bias); + result[8 * i + 7] += x * (select(U(0), scale, bool(wb & 0x80)) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -485,14 +557,36 @@ qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { template inline void dequantize(const device uint8_t* w, U scale, U bias, W w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -585,9 +679,9 @@ struct AffineQuantizedBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -596,6 +690,12 @@ struct AffineQuantizedBlockLoader { (BCOLS_PACKED * BROWS < tgp_size) ? 1 : (BCOLS_PACKED * BROWS) / tgp_size; MLX_MTL_CONST short group_steps = group_size / BCOLS; + MLX_MTL_CONST bool partial_cols = group_size % BCOLS != 0; + + static_assert( + group_size % (n_reads * pack_factor) == 0, + "The group size must be a multiple of the columns read per thread."); + const int src_ld; const int tile_stride; short group_step_cnt; @@ -753,7 +853,7 @@ METAL_FUNC void qmv_quad_impl( } } -template +template METAL_FUNC void qmv_fast_impl( const device uint32_t* w, const device T* scales, @@ -765,7 +865,8 @@ METAL_FUNC void qmv_fast_impl( uint3 tid [[threadgroup_position_in_grid]], uint simd_gid [[simdgroup_index_in_threadgroup]], uint simd_lid [[thread_index_in_simdgroup]]) { - constexpr int packs_per_thread = bits == 2 ? 1 : 2; + constexpr int packs_per_thread = + bits <= 2 ? 1 : 2; // 1-bit: 1 pack (vpt=32) for occupancy constexpr int num_simdgroups = 2; constexpr int results_per_simdgroup = 4; constexpr int pack_factor = get_affine_pack_factor(); @@ -787,19 +888,37 @@ METAL_FUNC void qmv_fast_impl( const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup; + // With partial rows the output size need not be a multiple of 8. Rows of the + // last SIMD-group that fall past the output reuse the weights of the last + // valid output row, so the reduction loop needs no per-row bounds check, and + // are not stored. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; x += tid.x * in_vec_size + simd_lid * values_per_thread; y += tid.x * out_vec_size + out_row; - for (int k = 0; k < in_vec_size; k += block_size) { + const int aligned_end = (in_vec_size / block_size) * block_size; + + for (int k = 0; k < aligned_end; k += block_size) { U sum = load_vector(x, x_thread); for (int row = 0; row < results_per_simdgroup; row++) { - auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); - const device T* sl = scales + row * in_vec_size_g; - const device T* bl = biases + row * in_vec_size_g; + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; U s = sl[0]; U b = bl[0]; @@ -812,9 +931,37 @@ METAL_FUNC void qmv_fast_impl( x += block_size; } + // Tail block: handles K that is a multiple of 512 (dispatch gate) but not + // of block_size. Only 1-bit has block_size > 512 (it uses 2048), so for + // >=2-bit this is a no-op. Out-of-bounds lanes skip the qdot call entirely; + // their result[row] stays at 0 and contributes 0 to the simd_sum below. + if (aligned_end < in_vec_size) { + bool in_bounds = + (aligned_end + static_cast(simd_lid) * values_per_thread) < + in_vec_size; + if (in_bounds) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + } + } + for (int row = 0; row < results_per_simdgroup; row++) { result[row] = simd_sum(result[row]); - if (simd_lid == 0) { + if (simd_lid == 0 && row <= last_row) { y[row] = static_cast(result[row]); } } @@ -1321,6 +1468,7 @@ template < const int group_size, const int bits, const bool aligned_N, + typename U = T, const int BM = 32, const int BK = 32, const int BN = 32> @@ -1329,7 +1477,7 @@ METAL_FUNC void qmm_t_impl( const device T* scales, const device T* biases, const device T* x, - device T* y, + device U* y, threadgroup T* Xs, threadgroup T* Ws, const constant int& K, @@ -1354,7 +1502,7 @@ METAL_FUNC void qmm_t_impl( // Instantiate the appropriate BlockMMA and Loader using mma_t = mlx::steel:: - BlockMMA; + BlockMMA; using loader_x_t = mlx::steel::BlockLoader; using loader_w_t = AffineQuantizedBlockLoader< @@ -1730,6 +1878,7 @@ template < int group_size, int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv_fast( @@ -1770,7 +1919,7 @@ template < b_strides, tid); } - qmv_fast_impl( + qmv_fast_impl( w, scales, biases, @@ -1788,6 +1937,7 @@ template < int group_size, const int bits, bool batched, + bool partial_rows = false, bool has_global_scale = false, int results_per_simdgroup = 4> [[kernel]] void affine_qmv( @@ -2024,6 +2174,7 @@ template < const int bits, const bool aligned_N, const bool batched, + const bool has_global_scale = false, const int BM = 32, const int BK = 32, const int BN = 32> @@ -2073,7 +2224,7 @@ template < b_strides, tid); } - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -2104,7 +2255,7 @@ template < const device T* scales [[buffer(1)]], const device T* biases [[buffer(2)]], const device T* x [[buffer(3)]], - device T* y [[buffer(4)]], + device float* y [[buffer(4)]], const constant int& K [[buffer(5)]], const constant int& N [[buffer(6)]], const constant int& M [[buffer(7)]], @@ -2132,7 +2283,7 @@ template < biases += k_start / group_size; y += tid.z * static_cast(split_k_partition_stride); - qmm_t_impl( + qmm_t_impl( (const device uint32_t*)wl, scales, biases, @@ -2403,6 +2554,7 @@ template < const int group_size, const int bits, const bool aligned_N, + const bool has_global_scale = false, const int BM = 32, const int BK = 32, const int BN = 32> @@ -2462,7 +2614,7 @@ template < s_strides, b_strides, tid); - qmm_t_impl( + qmm_t_impl( w, scales, biases, @@ -2967,14 +3119,23 @@ template w_min = simd_min(w_min); w_max = simd_max(w_max); - float scale = max((w_max - w_min) / n_bins, eps); - bool side = abs(w_min) > abs(w_max); - scale = side ? scale : -scale; - float edge = side ? w_min : w_max; - float q0 = round(edge / scale); - bool at_zero = q0 == 0.0f; - scale = at_zero ? scale : edge / q0; - float bias = at_zero ? 0 : edge; + float scale; + float bias; + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scale = max(w_max - w_min, eps); + bias = w_min; + } else { + scale = max((w_max - w_min) / n_bins, eps); + bool side = abs(w_min) > abs(w_max); + scale = side ? scale : -scale; + float edge = side ? w_min : w_max; + float q0 = round(edge / scale); + bool at_zero = q0 == 0.0f; + scale = at_zero ? scale : edge / q0; + bias = at_zero ? 0 : edge; + } // Write out the scales and biases size_t gindex = in_index / group_size; @@ -3078,7 +3239,9 @@ template #pragma clang loop unroll(full) for (int i = 0; i < pack_factor; i++) { uint8_t d; - if (bits == 2) { + if (bits == 1) { + d = (val >> i) & 0x01; + } else if (bits == 2) { d = (val >> (bits * i)) & 0x03; } else if (bits == 4) { d = (val >> (bits * i)) & 0x0f; diff --git a/mlx/backend/metal/kernels/quantized.metal b/mlx/backend/metal/kernels/quantized.metal index 75e788ea2f..42d5e35ab6 100644 --- a/mlx/backend/metal/kernels/quantized.metal +++ b/mlx/backend/metal/kernels/quantized.metal @@ -23,6 +23,16 @@ bits, \ batched) +#define instantiate_quantized_qmv(name, type, group_size, bits, batched, partial_rows) \ + instantiate_kernel( \ + #name "_" #type "_gs_" #group_size "_b_" #bits "_batch_" #batched "_pr_" #partial_rows "_hgs_0_r_4", \ + name, \ + type, \ + group_size, \ + bits, \ + batched, \ + partial_rows) + #define instantiate_quantized_aligned(name, type, group_size, bits, aligned) \ instantiate_kernel( \ #name "_" #type "_gs_" #group_size "_b_" #bits "_alN_" #aligned, \ @@ -90,9 +100,14 @@ instantiate_quantized_batched(name, type, group_size, bits, 1) \ instantiate_quantized_batched(name, type, group_size, bits, 0) -#define instantiate_quantized_all_batched(type, group_size, bits) \ - instantiate_quantized_batched_wrap(affine_qmv_fast, type, group_size, bits) \ - instantiate_quantized_batched_wrap(affine_qmv, type, group_size, bits) \ +#define instantiate_quantized_qmv_wrap(name, type, group_size, bits, partial_rows) \ + instantiate_quantized_qmv(name, type, group_size, bits, 1, partial_rows) \ + instantiate_quantized_qmv(name, type, group_size, bits, 0, partial_rows) + +#define instantiate_quantized_all_batched(type, group_size, bits) \ + instantiate_quantized_qmv_wrap(affine_qmv_fast, type, group_size, bits, 1) \ + instantiate_quantized_qmv_wrap(affine_qmv_fast, type, group_size, bits, 0) \ + instantiate_quantized_qmv_wrap(affine_qmv, type, group_size, bits, 0) \ instantiate_quantized_batched_wrap(affine_qvm, type, group_size, bits) \ instantiate_quantized_batched_wrap(affine_qmm_n, type, group_size, bits) @@ -118,8 +133,9 @@ instantiate_quantized_quad(affine_qmv_quad, type, group_size, bits, 128, 1) \ instantiate_quantized_quad(affine_qmv_quad, type, group_size, bits, 128, 0) -// vecs_per_tg (input-vector tile) 2..5; affine uses k_lanes=8 (more rows per -// simdgroup) where the fp path uses 16. +// vecs_per_tg (input-vector tile) 2..8; affine uses k_lanes=8 (more rows per +// simdgroup) where the fp path uses 16. The affine kernel holds every streamed +// vector in registers and spills above 8. #define instantiate_quantized_wide_wrap(name, type, group_size, bits, vecs_per_tg, k_lanes) \ instantiate_quantized_wide(name, type, group_size, bits, vecs_per_tg, k_lanes, 0) \ instantiate_quantized_wide(name, type, group_size, bits, vecs_per_tg, k_lanes, 1) @@ -128,7 +144,10 @@ instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 2, 8) \ instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 3, 8) \ instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 4, 8) \ - instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 5, 8) + instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 5, 8) \ + instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 6, 8) \ + instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 7, 8) \ + instantiate_quantized_wide_wrap(affine_qmv_wide, type, group_size, bits, 8, 8) #define instantiate_quantized_all_splitk(type, group_size, bits) \ instantiate_quantized_split_k(affine_qvm_split_k, type, group_size, bits, 8) \ @@ -172,6 +191,7 @@ instantiate_quantized_types(32, bits) #define instantiate_quantized_all() \ + instantiate_quantized_groups(1) \ instantiate_quantized_groups(2) \ instantiate_quantized_groups(3) \ instantiate_quantized_groups(4) \ diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 60893f0f0e..fb414f1a6e 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -31,15 +31,30 @@ inline constexpr short get_bytes_per_pack() { template inline U nax_load_vector(const device T* x, thread U* x_thread) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -49,8 +64,8 @@ inline U nax_load_vector(const device T* x, thread U* x_thread) { else if (bits == 3) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; x_thread[i + 2] = x[i + 2] / 64.0f; @@ -64,7 +79,7 @@ inline U nax_load_vector(const device T* x, thread U* x_thread) { else if (bits == 4) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -74,8 +89,8 @@ inline U nax_load_vector(const device T* x, thread U* x_thread) { else if (bits == 5) { for (int i = 0; i < values_per_thread; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -89,7 +104,7 @@ inline U nax_load_vector(const device T* x, thread U* x_thread) { else if (bits == 6) { for (int i = 0; i < values_per_thread; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -110,15 +125,30 @@ inline U nax_load_vector(const device T* x, thread U* x_thread) { template inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U sum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 2.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 8.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 32.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 128.0f; + } + } + + else if (bits == 2) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 4.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -128,8 +158,8 @@ inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 3) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 8.0f; @@ -144,7 +174,7 @@ inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 4) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 16.0f; x_thread[i + 2] = x[i + 2] / 256.0f; @@ -154,8 +184,8 @@ inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 5) { for (int i = 0; i < N; i += 8) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + - x[i + 6] + x[i + 7]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 32.0f; x_thread[i + 2] = x[i + 2] / 4.0f; @@ -169,7 +199,7 @@ inline U nax_load_vector_safe(const device T* x, thread U* x_thread, int N) { else if (bits == 6) { for (int i = 0; i < N; i += 4) { - sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); x_thread[i] = x[i]; x_thread[i + 1] = x[i + 1] / 64.0f; x_thread[i + 2] = x[i + 2] / 16.0f; @@ -199,13 +229,27 @@ inline U qdot( U bias, U sum) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (values_per_thread / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -301,13 +345,27 @@ inline U qdot_safe( U sum, int N) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); U accum = 0; - if (bits == 2) { + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + accum += + (x_thread[8 * i] * (w[i] & 0x01) + + x_thread[8 * i + 1] * (w[i] & 0x02) + + x_thread[8 * i + 2] * (w[i] & 0x04) + + x_thread[8 * i + 3] * (w[i] & 0x08) + + x_thread[8 * i + 4] * (w[i] & 0x10) + + x_thread[8 * i + 5] * (w[i] & 0x20) + + x_thread[8 * i + 6] * (w[i] & 0x40) + + x_thread[8 * i + 7] * (w[i] & 0x80)); + } + } + + else if (bits == 2) { for (int i = 0; i < (N / 4); i++) { accum += (x_thread[4 * i] * (w[i] & 0x03) + @@ -398,11 +456,33 @@ template inline void qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + U s[8] = { + scale, + scale / 2.0f, + scale / 4.0f, + scale / 8.0f, + scale / 16.0f, + scale / 32.0f, + scale / 64.0f, + scale / 128.0f}; + for (int i = 0; i < (values_per_thread / 8); i++) { + result[8 * i] += x * (s[0] * (w[i] & 0x01) + bias); + result[8 * i + 1] += x * (s[1] * (w[i] & 0x02) + bias); + result[8 * i + 2] += x * (s[2] * (w[i] & 0x04) + bias); + result[8 * i + 3] += x * (s[3] * (w[i] & 0x08) + bias); + result[8 * i + 4] += x * (s[4] * (w[i] & 0x10) + bias); + result[8 * i + 5] += x * (s[5] * (w[i] & 0x20) + bias); + result[8 * i + 6] += x * (s[6] * (w[i] & 0x40) + bias); + result[8 * i + 7] += x * (s[7] * (w[i] & 0x80) + bias); + } + } - if (bits == 2) { + else if (bits == 2) { U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; for (int i = 0; i < (values_per_thread / 4); i++) { result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); @@ -483,18 +563,44 @@ qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { } } -template -inline void -dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) { +template < + typename U, + int N, + int bits, + typename BytePtr = const device uint8_t*, + typename OutPtr = threadgroup U*> +inline void dequantize(BytePtr w, U scale, U bias, OutPtr w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); const float s = float(scale); const float b = float(bias); - if (bits == 2) { + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; for (int i = 0; i < (N / 4); i++) { w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); @@ -587,9 +693,9 @@ struct AffineQuantizedNAXBlockLoader { group_size % BCOLS == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -721,9 +827,9 @@ struct AffineQuantizedNAXBlockLoader< BCOLS % group_size == 0, "The group size should be divisible by the columns"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || - bits == 8, - "Template undefined for bits not in {2, 3, 4, 5, 6, 8}"); + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); @@ -930,26 +1036,292 @@ METAL_FUNC void adjust_matrix_offsets( y += tid.z * output_stride; } +// AffineQuantizedNAXBlockLoader's thread mapping split into two steps: fetch() +// reads the packed words and the group's scale and bias for one BK step into +// registers, store() dequantizes them into threadgroup memory. Fetching step +// k + 1 before the MMAs of step k hides the device reads behind the matrix +// work. template < typename T, - const int group_size, - const int bits, - const bool aligned_N, - const int BM = 64, - const int BK = 64, - const int BN = 64, - const int WM = 2, - const int WN = 2> + short BROWS, + short BCOLS, + short dst_ld, + short tgp_size, + short group_size, + short bits> +struct QuantizedBlockLoaderStaged { + MLX_MTL_CONST short pack_factor = get_affine_pack_factor(); + MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); + MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; + MLX_MTL_CONST short n_reads = (BCOLS_PACKED * BROWS) / tgp_size; + MLX_MTL_CONST short n_words = n_reads * bytes_per_pack / 4; + + static_assert( + BCOLS_PACKED * BROWS >= tgp_size && + n_words * 4 == n_reads * bytes_per_pack, + "Every thread loads whole words"); + static_assert( + n_reads * pack_factor <= group_size && n_reads * pack_factor <= BCOLS, + "A thread's values must lie in one row and quantization group"); + + const short thread_idx; + const short bi; + const short bj; + const device uint8_t* src; + const device T* scales; + const device T* biases; + uint32_t raw[n_words]; + T scale; + T bias; + + QuantizedBlockLoaderStaged( + const device uint8_t* src_, + const device T* scales_, + const device T* biases_, + const int src_ld, + ushort simd_group_id, + ushort simd_lane_id) thread + : thread_idx(simd_group_id * 32 + simd_lane_id), + bi(n_reads* thread_idx / BCOLS_PACKED), + bj((n_reads * thread_idx) % BCOLS_PACKED), + src(src_ + bi * src_ld * bytes_per_pack / pack_factor + + bj * bytes_per_pack), + scales(scales_ + bi * src_ld / group_size), + biases(biases_ + bi * src_ld / group_size) {} + + // k: first column of the step + void fetch(const int k) thread { + auto p = (const device uint32_t*)(src + k * bytes_per_pack / pack_factor); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_words; i++) { + raw[i] = p[i]; + } + const int g = (k + bj * pack_factor) / group_size; + scale = scales[g]; + bias = biases[g]; + } + + // Dequantize into registers, then write 8 values per store + void store(threadgroup T* dst) const thread { + constexpr short n_vals = n_reads * pack_factor; + static_assert(n_vals % 8 == 0, "8-value stores"); + T v[n_vals]; + // Unpack with shifts (constant indices keep it in registers) + uint8_t b[n_words * 4]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_words * 4; i++) { + b[i] = uint8_t(raw[i / 4] >> (8 * (i % 4))); + } + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_reads; i++) { + dequantize( + b + i * bytes_per_pack, scale, bias, v + i * pack_factor); + } + dst += bi * dst_ld + bj * pack_factor; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_vals; i += 8) { + *(threadgroup vec*)(dst + i) = *(thread vec*)(v + i); + } + } +}; + +// Each simdgroup computes SM rows and prefetches the next activation tile. +// Weights use two threadgroup buffers with one barrier between K steps. +template < + typename T, + int group_size, + int bits, + typename U = T, + int BM = 64, + int BK = 64, + int BN = 64, + int SM = 16> +METAL_FUNC void qmm_t_nax_staged_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device U* y, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const constant int& M, + const int k_end, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BK == 64 && BN == 64, "64-column tiles"); + static_assert(SM > 0 && SM % 16 == 0 && BM % SM == 0, "Whole row fragments"); + static_assert( + sizeof(T) == 2, "Two tiles fit threadgroup memory for 16-bit T"); + + constexpr int pack_factor = get_affine_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int tile_size = BN * BK_padded; + + using loader_w_t = QuantizedBlockLoaderStaged< + T, + BN, + BK, + BK_padded, + (BM / SM) * SIMD_SIZE, + group_size, + bits>; + using frag_t = typename BaseNAXFrag::template dtype_frag_t; + + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + + loader_w_t loader_w( + (const device uint8_t*)w + y_col * K_w, + scales + y_col * K_g, + biases + y_col * K_g, + K, + simd_gid, + simd_lid); + + // This simdgroup's rows and the two rows each thread holds in a fragment + const int tile_rows = min(BM, M - y_row); + constexpr int TM = SM / 16; + const int sm = SM * int(simd_gid); + const int rows = min(SM, tile_rows - sm); + const short2 sc = BaseNAXFrag::get_coord(); + const device T* x0[TM]; + const device T* x1[TM]; + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + const int r0 = min(sm + m * 16 + int(sc.y), tile_rows - 1); + const int r1 = min(sm + m * 16 + int(sc.y) + 8, tile_rows - 1); + x0[m] = x + (y_row + r0) * static_cast(K) + sc.x; + x1[m] = x + (y_row + r1) * static_cast(K) + sc.x; + } + + NAXTile Dtile; + Dtile.clear(); + vec a_cur[BK / 16][TM][2]; + vec a_next[BK / 16][TM][2]; + + loader_w.fetch(0); + loader_w.store(Ws); + if (rows > 0) { + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_cur[s][m][0] = *(const device vec*)(x0[m] + s * 16); + a_cur[s][m][1] = *(const device vec*)(x1[m] + s * 16); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int k = 0, it = 0; k < k_end; k += BK, it++) { + const bool more = k + BK < k_end; + if (more) { + loader_w.fetch(k + BK); + } + if (rows > 0) { + const int kn = more ? k + BK : k; + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_next[s][m][0] = *(const device vec*)(x0[m] + kn + s * 16); + a_next[s][m][1] = *(const device vec*)(x1[m] + kn + s * 16); + } + } + const threadgroup T* ws = + Ws + (it & 1) * tile_size + sc.y * BK_padded + sc.x; + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < BN / 16; j += 2) { + const threadgroup T* p0 = ws + (j * 16) * BK_padded + s * 16; + const threadgroup T* p1 = p0 + 16 * BK_padded; + frag_t b0; + frag_t b1; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const vec u0 = + *(const threadgroup vec*)(p0 + h * 8 * BK_padded); + const vec u1 = + *(const threadgroup vec*)(p1 + h * 8 * BK_padded); + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + b0[h * 4 + c] = u0[c]; + b1[h * 4 + c] = u1[c]; + } + } + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + frag_t a; + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + a[c] = a_cur[s][m][0][c]; + a[4 + c] = a_cur[s][m][1][c]; + } + BaseNAXFrag::mma( + Dtile.frag_at(m, j), + Dtile.frag_at(m, j + 1), + a, + metal::bool_constant{}, + b0, + b1, + metal::bool_constant{}); + } + } + } + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_cur[s][m][0] = a_next[s][m][0]; + a_cur[s][m][1] = a_next[s][m][1]; + } + } + } + if (more) { + loader_w.store(Ws + ((it + 1) & 1) * tile_size); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + if (rows <= 0) { + return; + } + y += (y_row + sm) * static_cast(N) + y_col; + if (rows == SM) { + Dtile.store(y, N); + } else { + Dtile.store_safe(y, N, short2(BN, rows)); + } +} + +template < + typename T, + int group_size, + int bits, + bool aligned_N, + typename U = T, + int BM = 64, + int BK = 64, + int BN = 64, + int WM = 2, + int WN = 2> METAL_FUNC void qmm_t_nax_tgp_impl( const device uint32_t* w, const device T* scales, const device T* biases, const device T* x, - device T* y, + device U* y, threadgroup T* Ws, const constant int& K, const constant int& N, const constant int& M, + const int k_end, uint3 tid [[threadgroup_position_in_grid]], uint lid [[thread_index_in_threadgroup]], uint simd_gid [[simdgroup_index_in_threadgroup]], @@ -1022,7 +1394,7 @@ METAL_FUNC void qmm_t_nax_tgp_impl( dispatch_bool(!is_unaligned_sm, [&](auto kAlignedM) { dispatch_bool(aligned_N || !is_unaligned_bn, [&](auto kAlignedN) { - for (int k = 0; k < K; k += BK) { + for (int k = 0; k < k_end; k += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); if constexpr (kAlignedN.value) { loader_w.load_unsafe(); @@ -1213,7 +1585,8 @@ template < const int BK = 32, const int BN = 64, const int WM = 2, - const int WN = 2> + const int WN = 2, + const bool has_global_scale = false> [[kernel]] void affine_qmm_t_nax( const device uint32_t* w [[buffer(0)]], const device T* scales [[buffer(1)]], @@ -1239,7 +1612,8 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(T)); - threadgroup T Ws[BN * BK_padded]; + // WN == 1 selects the staged impl + threadgroup T Ws[(WN == 1 ? 2 : 1) * BN * BK_padded]; if (batched) { adjust_matrix_offsets( @@ -1259,8 +1633,98 @@ template < b_strides, tid); } - qmm_t_nax_tgp_impl( - w, scales, biases, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + if constexpr (WN == 1) { + static_assert(aligned_N, "Aligned output columns"); + qmm_t_nax_staged_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, simd_gid, simd_lid); + } else { + qmm_t_nax_tgp_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); + } +} + +template < + typename T, + int group_size, + int bits, + bool aligned_N, + int BM = 64, + int BK = 64, + int BN = 64, + int WM = 2, + int WN = 2> +[[kernel]] void affine_qmm_t_nax_splitk( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device float* y [[buffer(4)]], + const constant int& K [[buffer(5)]], + const constant int& N [[buffer(6)]], + const constant int& M [[buffer(7)]], + const constant int& k_partition_size [[buffer(8)]], + const constant int& split_k_partition_stride [[buffer(9)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int pack_factor = get_affine_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + threadgroup T Ws[(WN == 1 ? 2 : 1) * BN * BK_padded]; + + const int k_start = tid.z * k_partition_size; + x += k_start; + auto wl = (const device uint8_t*)w; + wl += k_start * bytes_per_pack / pack_factor; + scales += k_start / group_size; + biases += k_start / group_size; + y += tid.z * static_cast(split_k_partition_stride); + + if constexpr (WN == 1) { + static_assert(aligned_N, "Aligned output columns"); + qmm_t_nax_staged_impl( + (const device uint32_t*)wl, + scales, + biases, + x, + y, + Ws, + K, + N, + M, + k_partition_size, + tid, + simd_gid, + simd_lid); + } else { + qmm_t_nax_tgp_impl< + T, + group_size, + bits, + aligned_N, + float, + BM, + BK, + BN, + WM, + WN>( + (const device uint32_t*)wl, + scales, + biases, + x, + y, + Ws, + K, + N, + M, + k_partition_size, + tid, + lid, + simd_gid, + simd_lid); + } } template < @@ -1332,7 +1796,8 @@ template < const int BK = 64, const int BN = 64, const int WM = 2, - const int WN = 2> + const int WN = 2, + const bool has_global_scale = false> [[kernel]] void affine_gather_qmm_t_nax( const device uint32_t* w [[buffer(0)]], const device T* scales [[buffer(1)]], @@ -1388,8 +1853,8 @@ template < s_strides, b_strides, tid); - qmm_t_nax_tgp_impl( - w, scales, biases, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + qmm_t_nax_tgp_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); } template < diff --git a/mlx/backend/metal/kernels/quantized_nax.metal b/mlx/backend/metal/kernels/quantized_nax.metal index 9557fd838d..f627298740 100644 --- a/mlx/backend/metal/kernels/quantized_nax.metal +++ b/mlx/backend/metal/kernels/quantized_nax.metal @@ -91,10 +91,23 @@ instantiate_quantized_all_aligned(type, group_size, bits) \ instantiate_quantized_all_rhs(type, group_size, bits) +#define instantiate_quantized_splitk(group_size, bits) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float, group_size, bits, 32, 64, 64, 2, 2, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float, group_size, bits, 64, 64, 64, 2, 2, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float16_t, group_size, bits, 64, 64, 64, 4, 1, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, bfloat16_t, group_size, bits, 64, 64, 64, 4, 1, true) + +#define instantiate_quantized_staged(type, group_size, bits) \ + instantiate_quantized_aligned_batched(affine_qmm_t_nax, type, group_size, bits, 64, 64, 64, 4, 1, true, 1) \ + instantiate_quantized_aligned_batched(affine_qmm_t_nax, type, group_size, bits, 64, 64, 64, 4, 1, true, 0) + #define instantiate_quantized_types(group_size, bits) \ instantiate_quantized_funcs(float, group_size, bits) \ instantiate_quantized_funcs(float16_t, group_size, bits) \ - instantiate_quantized_funcs(bfloat16_t, group_size, bits) + instantiate_quantized_funcs(bfloat16_t, group_size, bits) \ + instantiate_quantized_splitk(group_size, bits) \ + instantiate_quantized_staged(float16_t, group_size, bits) \ + instantiate_quantized_staged(bfloat16_t, group_size, bits) #define instantiate_quantized_groups(bits) \ instantiate_quantized_types(128, bits) \ @@ -102,6 +115,7 @@ instantiate_quantized_types(32, bits) #define instantiate_quantized_all() \ + instantiate_quantized_groups(1) \ instantiate_quantized_groups(2) \ instantiate_quantized_groups(3) \ instantiate_quantized_groups(4) \ diff --git a/mlx/backend/metal/kernels/reduce.metal b/mlx/backend/metal/kernels/reduce.metal index 3f5f91be49..0cd290ab8a 100644 --- a/mlx/backend/metal/kernels/reduce.metal +++ b/mlx/backend/metal/kernels/reduce.metal @@ -19,6 +19,8 @@ instantiate_init_reduce(or, bool_, bool, Or) #define instantiate_init_sum_prod(name, op) \ instantiate_init_reduce(name, int32, int32_t, op) \ instantiate_init_reduce(name, int64, int64_t, op) \ + instantiate_init_reduce(name, uint32, uint32_t, op) \ + instantiate_init_reduce(name, uint64, uint64_t, op) \ instantiate_init_reduce(name, float16, float16_t, op) \ instantiate_init_reduce(name, bfloat16, bfloat16_t, op) \ instantiate_init_reduce(name, float32, float, op) \ @@ -131,7 +133,8 @@ instantiate_init_min_max(max, Max) instantiate_reduce_functions(name, int64, int64_t, bool, op) \ instantiate_reduce_functions(name, float16, float16_t, bool, op) \ instantiate_reduce_functions(name, bfloat16, bfloat16_t, bool, op) \ - instantiate_reduce_functions(name, float32, float, bool, op) + instantiate_reduce_functions(name, float32, float, bool, op) \ + instantiate_reduce_functions(name, complex64, complex64_t, bool, op) instantiate_and_or(and, And) instantiate_and_or(or, Or) diff --git a/mlx/backend/metal/kernels/reduction/reduce_col.h b/mlx/backend/metal/kernels/reduction/reduce_col.h index b1546adb55..fce36a4cd2 100644 --- a/mlx/backend/metal/kernels/reduction/reduce_col.h +++ b/mlx/backend/metal/kernels/reduction/reduce_col.h @@ -117,7 +117,7 @@ template IdxT out_idx = gid.x + gsize.x * IdxT(gid.y); IdxT in_idx = elem_to_loc(out_idx, shape, strides, ndim); - in += in_idx + lid.x; + in += in_idx + IdxT(lid.x); U total = Op::init; IdxT total_rows = IdxT(non_col_reductions) * IdxT(reduction_size); @@ -172,6 +172,7 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], + const constant int64_t& column_offset [[buffer(11)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -193,7 +194,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT out_idx = gid.y + gsize.y * IdxT(gid.z); @@ -243,7 +244,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += out_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { @@ -311,7 +312,8 @@ template < const constant int64_t* reduce_strides [[buffer(8)]], const constant int& reduce_ndim [[buffer(9)]], const constant size_t& non_col_reductions [[buffer(10)]], - const constant size_t& out_size [[buffer(11)]], + const constant int64_t& column_offset [[buffer(11)]], + const constant size_t& out_size [[buffer(12)]], uint3 gid [[threadgroup_position_in_grid]], uint3 gsize [[threadgroups_per_grid]], uint simd_lane_id [[thread_index_in_simdgroup]], @@ -336,7 +338,7 @@ template < short lid = simd_group_id * simd_size + simd_lane_id; short2 offset((lid % n_read_blocks) * n_reads, lid / n_read_blocks); - IdxT column = BN * gid.x + offset.x; + IdxT column = IdxT(BN) * gid.x + IdxT(column_offset) + offset.x; bool safe = column + n_reads <= reduction_stride; IdxT full_idx = gid.y + gsize.y * IdxT(gid.z); @@ -383,7 +385,7 @@ template < // Write the output. if (simd_lane_id == 0) { - IdxT out_column = BN * gid.x + out_offset.x; + IdxT out_column = IdxT(BN) * gid.x + IdxT(column_offset) + out_offset.x; out += full_idx * IdxT(reduction_stride) + out_column; if (out_column + n_outputs <= reduction_stride) { for (int i = 0; i < n_outputs; i++) { diff --git a/mlx/backend/metal/kernels/reduction/reduce_init.h b/mlx/backend/metal/kernels/reduction/reduce_init.h index 604efa785f..9a1e363e12 100644 --- a/mlx/backend/metal/kernels/reduction/reduce_init.h +++ b/mlx/backend/metal/kernels/reduction/reduce_init.h @@ -3,6 +3,7 @@ template [[kernel]] void init_reduce( device T* out [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = Op::init; + uint2 index [[thread_position_in_grid]], + uint2 grid_dim [[threads_per_grid]]) { + out[index.x + grid_dim.x * int64_t(index.y)] = Op::init; } diff --git a/mlx/backend/metal/kernels/scaled_dot_product_attention.metal b/mlx/backend/metal/kernels/scaled_dot_product_attention.metal index cfe5aec6c3..482b9f178a 100644 --- a/mlx/backend/metal/kernels/scaled_dot_product_attention.metal +++ b/mlx/backend/metal/kernels/scaled_dot_product_attention.metal @@ -2,10 +2,28 @@ // clang-format off #include "mlx/backend/metal/kernels/utils.h" +#include "mlx/backend/metal/kernels/sdpa_blocked.h" #include "mlx/backend/metal/kernels/sdpa_vector.h" using namespace metal; +instantiate_kernel( + "sdpa_blocked_scale_copy_bfloat16", + sdpa_blocked_scale_copy, + bfloat16_t) +instantiate_kernel( + "sdpa_blocked_scale_copy_float16", + sdpa_blocked_scale_copy, + float16_t) +instantiate_kernel( + "sdpa_blocked_causal_mask_bfloat16", + sdpa_blocked_causal_mask, + bfloat16_t) +instantiate_kernel( + "sdpa_blocked_causal_mask_float16", + sdpa_blocked_causal_mask, + float16_t) + // SDPA vector instantiations #define instantiate_sdpa_vector_aggregation(type, value_dim) \ instantiate_kernel( \ @@ -28,32 +46,51 @@ using namespace metal; qk_dim, \ value_dim) -#define instantiate_sdpa_vector_gqa(type, qk_dim, value_dim, hpt) \ - instantiate_kernel( \ - "sdpa_vector_2pass_fp32partials_1_gqa_" #type "_" #qk_dim "_" #value_dim, \ - sdpa_vector_2pass_1_gqa, \ - type, \ - qk_dim, \ - value_dim, \ - 8, \ +#define instantiate_sdpa_vector_gqa(type, qk_dim, value_dim, g, hpt) \ + instantiate_kernel( \ + "sdpa_vector_2pass_fp32partials_1_gqa_" #g "_" #type "_" #qk_dim "_" #value_dim, \ + sdpa_vector_2pass_1_gqa, \ + type, \ + qk_dim, \ + value_dim, \ + g, \ hpt) #define instantiate_sdpa_vector_heads(type) \ instantiate_sdpa_vector(type, 64, 64) \ + instantiate_sdpa_vector(type, 96, 64) \ instantiate_sdpa_vector(type, 96, 96) \ instantiate_sdpa_vector(type, 128, 128) \ instantiate_sdpa_vector(type, 192, 128) \ instantiate_sdpa_vector(type, 192, 192) \ instantiate_sdpa_vector(type, 256, 256) \ - instantiate_sdpa_vector_gqa(type, 64, 64, 8) \ - instantiate_sdpa_vector_gqa(type, 128, 128, 4) \ + instantiate_sdpa_vector(type, 512, 512) \ + instantiate_sdpa_vector_gqa(type, 64, 64, 8, 8) \ + instantiate_sdpa_vector_gqa(type, 128, 128, 8, 4) \ + instantiate_sdpa_vector_gqa(type, 128, 128, 12, 4) \ + instantiate_sdpa_vector_gqa(type, 128, 128, 16, 2) \ instantiate_sdpa_vector_aggregation(type, 64) \ instantiate_sdpa_vector_aggregation(type, 96) \ instantiate_sdpa_vector_aggregation(type, 128) \ instantiate_sdpa_vector_aggregation(type, 192) \ - instantiate_sdpa_vector_aggregation(type, 256) + instantiate_sdpa_vector_aggregation(type, 256) \ + instantiate_sdpa_vector_aggregation(type, 512) instantiate_sdpa_vector_heads(float) instantiate_sdpa_vector_heads(bfloat16_t) instantiate_sdpa_vector_heads(float16_t) - // clang-format on + +#define instantiate_sdpa_vector_tk1(type, dim) \ + instantiate_kernel( \ + "sdpa_vector_2pass_fp32partials_1_" #type "_" #dim "_" #dim "_tk1", \ + sdpa_vector_2pass_1, \ + type, \ + dim, \ + dim, \ + 1) + +instantiate_sdpa_vector_tk1(float16_t, 256) +instantiate_sdpa_vector_tk1(bfloat16_t, 256) +instantiate_sdpa_vector_tk1(float, 192) +instantiate_sdpa_vector_tk1(float, 256) +// clang-format on diff --git a/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal b/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal new file mode 100644 index 0000000000..ddd9f4bcda --- /dev/null +++ b/mlx/backend/metal/kernels/scaled_dot_product_attention_vjp.metal @@ -0,0 +1,154 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/metal/kernels/utils.h" + +using namespace metal; + +template +[[kernel]] void sdpa_vjp_odo( + const device InT* o [[buffer(0)]], // [B, H, qL, Dv] + const device InT* cot_o [[buffer(1)]], // [B, H, qL, Dv] + device float* odo [[buffer(2)]], // [B, H, qL] + constant int& qL [[buffer(3)]], + uint3 tpg [[thread_position_in_grid]], + uint simd_lane_id [[thread_index_in_simdgroup]]) { + const uint bh = tpg.z; + const int i = int(tpg.y); + + if (i >= qL) { + return; + } + + const size_t row = (size_t)bh * qL + i; + auto o_i = o + row * Dv; + auto co_i = cot_o + row * Dv; + + float acc = 0.0f; + for (int d = int(simd_lane_id); d < Dv; d += 32) { + acc += float(o_i[d]) * float(co_i[d]); + } + acc = simd_sum(acc); + + if (simd_lane_id == 0) { + odo[row] = acc; + } +} + +struct SDPAVJPTileParams { + int bq; + int bk; + int qL; + int i0; + int j0; + float scale; + int diag_off; + int causal; +}; + +template +[[kernel]] void sdpa_vjp_ds( + const device T* S [[buffer(0)]], // [BH, bq, bk] + const device T* dP [[buffer(1)]], // [BH, bq, bk] + const device float* lse [[buffer(2)]], // [B, H, qL] + const device float* odo [[buffer(3)]], // [B, H, qL] + device T* dS [[buffer(4)]], // [BH, bq, bk] + device T* P [[buffer(5)]], // [BH, bk, bq] + const constant SDPAVJPTileParams& p [[buffer(6)]], + uint3 gid [[thread_position_in_grid]]) { + int col = int(gid.x); + int row = int(gid.y); + int bh = int(gid.z); + if (row >= p.bq || col >= p.bk) { + return; + } + + size_t sbase = (size_t(bh) * size_t(p.bq) + size_t(row)) * size_t(p.bk); + size_t qi = size_t(bh) * size_t(p.qL) + size_t(p.i0 + row); + + float l = lse[qi]; + float dlt = odo[qi]; + // Fully masked rows carry lse == -inf; exp(-inf - -inf) would be NaN. + bool dead = (l < 0.0f) && metal::isinf(l); + int lim = p.i0 + row + p.diag_off; + + float pv; + if (dead || (p.causal != 0 && (p.j0 + col) > lim)) { + pv = 0.0f; + } else { + pv = metal::fast::exp(static_cast(S[sbase + col]) * p.scale - l); + } + float dsv = pv * (static_cast(dP[sbase + col]) - dlt) * p.scale; + + dS[sbase + col] = static_cast(dsv); + P[sbase + col] = static_cast(pv); +} + +template +[[kernel]] void sdpa_vjp_reduce( + const device T* src [[buffer(0)]], + device float* acc [[buffer(1)]], + device T* out [[buffer(2)]], + const constant int& rows [[buffer(3)]], + const constant int& dim [[buffer(4)]], + const constant int& group [[buffer(5)]], + const constant int& acc_rows [[buffer(6)]], + const constant int& row_off [[buffer(7)]], + uint3 gid [[thread_position_in_grid]]) { + int c = int(gid.x); + int row = int(gid.y); + int bh = int(gid.z); + if (c >= dim || row >= rows) { + return; + } + + size_t sbase = size_t(bh) * size_t(group) * size_t(rows) * size_t(dim); + float sum = 0.0f; + for (int g = 0; g < group; ++g) { + size_t si = sbase + + (size_t(g) * size_t(rows) + size_t(row)) * size_t(dim) + size_t(c); + sum += static_cast(src[si]); + } + + size_t ai = + (size_t(bh) * size_t(acc_rows) + size_t(row_off + row)) * size_t(dim) + + size_t(c); + float total = Accum ? acc[ai] + sum : sum; + acc[ai] = total; + out[ai] = static_cast(total); +} + +// Instantiations +#define instantiate_odo(in_type, dv) \ + instantiate_kernel( \ + "sdpa_vjp_odo_" #in_type "_" #dv, sdpa_vjp_odo, in_type, dv) + +#define instantiate_odo_shapes(in_type) \ + instantiate_odo(in_type, 64); \ + instantiate_odo(in_type, 72); \ + instantiate_odo(in_type, 80); \ + instantiate_odo(in_type, 96); \ + instantiate_odo(in_type, 128); \ + instantiate_odo(in_type, 192); \ + instantiate_odo(in_type, 256); \ + instantiate_odo(in_type, 512); \ + +instantiate_odo_shapes(bfloat16_t); +instantiate_odo_shapes(float16_t); +instantiate_odo_shapes(float); + +#define instantiate_sdpa_vjp_ds(tname, type) \ + instantiate_kernel("sdpa_vjp_ds_" #tname, sdpa_vjp_ds, type) + +instantiate_sdpa_vjp_ds(float, float); +instantiate_sdpa_vjp_ds(float16_t, float16_t); +instantiate_sdpa_vjp_ds(bfloat16_t, bfloat16_t); + +#define instantiate_sdpa_vjp_reduce(tname, type) \ + instantiate_kernel( \ + "sdpa_vjp_reduce_add_" #tname, sdpa_vjp_reduce, type, true) \ + instantiate_kernel( \ + "sdpa_vjp_reduce_set_" #tname, sdpa_vjp_reduce, type, false) + +instantiate_sdpa_vjp_reduce(float, float); +instantiate_sdpa_vjp_reduce(float16_t, float16_t); +instantiate_sdpa_vjp_reduce(bfloat16_t, bfloat16_t); diff --git a/mlx/backend/metal/kernels/sdpa_blocked.h b/mlx/backend/metal/kernels/sdpa_blocked.h new file mode 100644 index 0000000000..be4e900c67 --- /dev/null +++ b/mlx/backend/metal/kernels/sdpa_blocked.h @@ -0,0 +1,45 @@ +// Copyright © 2026 Apple Inc. + +#pragma once + +#include + +#include "mlx/backend/metal/kernels/defines.h" + +using namespace metal; + +template +[[kernel]] void sdpa_blocked_scale_copy( + const device T* q [[buffer(0)]], + device T* q_block [[buffer(1)]], + constant float& scale [[buffer(2)]], + constant int64_t* q_strides [[buffer(3)]], + constant int& heads [[buffer(4)]], + constant int& rows [[buffer(5)]], + constant int& head_dim [[buffer(6)]], + constant int& q_offset [[buffer(7)]], + uint3 elem [[thread_position_in_grid]]) { + int d = elem.x; + int row = elem.y; + int head = elem.z % heads; + int batch = elem.z / heads; + int64_t q_index = int64_t(batch) * q_strides[0] + + int64_t(head) * q_strides[1] + int64_t(q_offset + row) * q_strides[2] + d; + size_t q_block_index = (size_t(elem.z) * rows + row) * head_dim + d; + q_block[q_block_index] = q[q_index] * static_cast(scale); +} + +template +[[kernel]] void sdpa_blocked_causal_mask( + device T* scores [[buffer(0)]], + constant int& tile_rows [[buffer(1)]], + constant int& columns [[buffer(2)]], + uint2 elem [[thread_position_in_grid]]) { + int column = elem.x; + int score_row = elem.y; + int row = score_row % tile_rows; + if (column > row) { + size_t index = size_t(score_row) * columns + columns - tile_rows + column; + scores[index] = Limits::finite_min; + } +} diff --git a/mlx/backend/metal/kernels/sdpa_vector.h b/mlx/backend/metal/kernels/sdpa_vector.h index 3631e49daa..e1dea06f2b 100644 --- a/mlx/backend/metal/kernels/sdpa_vector.h +++ b/mlx/backend/metal/kernels/sdpa_vector.h @@ -61,6 +61,7 @@ template const int q_batch_head_idx = tid.x; const int q_seq_idx = tid.y; const int kv_head_idx = q_batch_head_idx / gqa_factor; + const int kv_seq_idx = simd_gid; const int o_offset = q_batch_head_idx * tpg.y + q_seq_idx; const int q_offset = query_transposed ? tpg.x * q_seq_idx + q_batch_head_idx : o_offset; @@ -71,11 +72,11 @@ template simd_lid * v_per_thread; if (bool_mask) { bmask += q_batch_head_idx * mask_head_stride + - simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + kv_seq_idx * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; } if (float_mask) { fmask += q_batch_head_idx * mask_head_stride + - simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + kv_seq_idx * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; } out += o_offset * V + simd_gid * v_per_thread; @@ -176,7 +177,7 @@ template } } -template +template [[kernel]] void sdpa_vector_2pass_1( const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], @@ -259,8 +260,73 @@ template sum_exp_score = 1; } + const int stride_k_tok = blocks * int(k_seq_stride); + const int stride_v_tok = blocks * int(v_seq_stride); + const int stride_mask_tok = + (bool_mask || float_mask) ? blocks * mask_kv_seq_stride : 0; + // For each key - for (int i = block_idx; i < N; i += blocks) { + int i = block_idx; + for (; i + (TK - 1) * blocks < N; i += blocks * TK) { + // Prefetch: issue all TK K/V loads first so the HW can overlap them. + T k_reg[TK][qk_per_thread]; + T v_reg[TK][v_per_thread]; + for (int t = 0; t < TK; t++) { + const device T* kp = keys + t * stride_k_tok; + for (int j = 0; j < qk_per_thread; j++) { + k_reg[t][j] = kp[j]; + } + } + for (int t = 0; t < TK; t++) { + const device T* vp = values + t * stride_v_tok; + for (int j = 0; j < v_per_thread; j++) { + v_reg[t][j] = vp[j]; + } + } + + for (int t = 0; t < TK; t++) { + int ii = i + t * blocks; + bool use_key = true; + if (do_causal) { + use_key = ii <= (N - q_seq_len + int(q_seq_idx)); + } else if (bool_mask) { + use_key = bmask[t * stride_mask_tok]; + } else if (float_mask) { + use_key = (fmask[t * stride_mask_tok] >= Limits::finite_min); + } + if (use_key) { + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(k_reg[t][j]); + } + score = simd_sum(score); + if (float_mask) { + score += static_cast(fmask[t * stride_mask_tok]); + } + + U new_max = max(max_score, score); + U factor = fast::exp(max_score - new_max); + U exp_score = fast::exp(score - new_max); + max_score = new_max; + sum_exp_score = sum_exp_score * factor + exp_score; + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * static_cast(v_reg[t][j]); + } + } + } + + keys += TK * stride_k_tok; + values += TK * stride_v_tok; + if (bool_mask) { + bmask += TK * stride_mask_tok; + } + if (float_mask) { + fmask += TK * stride_mask_tok; + } + } + + // Tail (fewer than TK remaining keys) + for (; i < N; i += blocks) { bool use_key = true; if (do_causal) { use_key = i <= (N - q_seq_len + int(q_seq_idx)); @@ -272,8 +338,8 @@ template if (use_key) { // Compute the i-th score U score = 0; - for (int i = 0; i < qk_per_thread; i++) { - score += q[i] * keys[i]; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * keys[j]; } score = simd_sum(score); @@ -290,19 +356,19 @@ template sum_exp_score = sum_exp_score * factor + exp_score; // Update the output accumulator - for (int i = 0; i < v_per_thread; i++) { - o[i] = o[i] * factor + exp_score * values[i]; + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * values[j]; } } // Move the pointers to the next kv - keys += blocks * int(k_seq_stride); - values += blocks * int(v_seq_stride); + keys += stride_k_tok; + values += stride_v_tok; if (bool_mask) { - bmask += blocks * mask_kv_seq_stride; + bmask += stride_mask_tok; } if (float_mask) { - fmask += blocks * mask_kv_seq_stride; + fmask += stride_mask_tok; } } @@ -357,6 +423,7 @@ template const int num_kv_heads = tpg.x; const int num_q_heads = num_kv_heads * G; const int base_head = batch_idx * num_q_heads + kv_head_idx * G; + const int kv_batch_head_idx = batch_idx * num_kv_heads + kv_head_idx; const int chunk = (N + blocks - 1) / blocks; const int kstart = block_idx * chunk; @@ -365,9 +432,9 @@ template const int s0 = kstart + cchunk * sub; const int s1 = min(kend, s0 + sub); - const device T* kp = keys + kv_head_idx * k_head_stride + s0 * k_seq_stride + - simd_lid * qk_per_thread; - const device T* vp = values + kv_head_idx * v_head_stride + + const device T* kp = keys + kv_batch_head_idx * k_head_stride + + s0 * k_seq_stride + simd_lid * qk_per_thread; + const device T* vp = values + kv_batch_head_idx * v_head_stride + s0 * v_seq_stride + simd_lid * v_per_thread; U q[HPT][qk_per_thread]; diff --git a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h index 29fa7ba396..d8f5efdc11 100644 --- a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h +++ b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h @@ -1,4 +1,4 @@ -// Copyright © 2024-25 Apple Inc. +// Copyright © 2024-26 Apple Inc. #include "mlx/backend/metal/kernels/steel/attn/attn.h" @@ -14,6 +14,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; struct MaxOp { template @@ -63,6 +64,7 @@ template < int BQ, int BK, int BD, + int BV, int WM, int WN, typename MaskType = float, @@ -76,6 +78,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -102,6 +105,12 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -114,13 +123,15 @@ template < constexpr short LDQ_tgp = BD + padQ; constexpr short LDK_tgp = BK + padK; - constexpr short LDV_tgp = BD + padV; + constexpr short LDV_tgp = BV + padV; constexpr short tgp_mem_0 = (BK + padK) * (BD); - constexpr short tgp_mem_1 = BK * (BD + padV); + constexpr short tgp_mem_1 = BK * (BV + padV); constexpr short tgp_mem_s = tgp_mem_0 > tgp_mem_1 ? tgp_mem_0 : tgp_mem_1; + constexpr bool q_in_registers = (WN == 2) && (BK == 32 || sizeof(T) == 4); + constexpr short q_tgp_mem_s = q_in_registers ? 1 : BQ * (BD + padQ); - threadgroup T Q_smem[BQ * (BD + padQ)]; + threadgroup T Q_smem[q_tgp_mem_s]; threadgroup T KV_smem[tgp_mem_s]; threadgroup T* Qs = Q_smem; @@ -150,7 +161,7 @@ template < using VBlockLoader = BlockLoaderT< /* typename T = */ T, /* short BROWS = */ BK, - /* short BCOLS = */ BD, + /* short BCOLS = */ BV, /* short kDstStrRow = */ LDV_tgp, /* short kDstStrCol = */ 1, /* short reduction_dim = */ 0, @@ -168,8 +179,15 @@ template < // Prepare MMA tiles constexpr short kFragSize = 8; // MMAFrag size using MMAFrag_acc_t = BaseMMAFrag; + using MMAInType = metal::conditional_t; + using MMAFrag_in_t = BaseMMAFrag; + + static_assert(WN == 1 || WN == 2, "WN must be 1 or 2"); + static_assert( + BD % WN == 0 && BV % WN == 0, + "The head dims must split evenly across WN"); - constexpr int kNWarps = WM * WN; + constexpr int kNWarps = WM; static_assert( BQ >= (kNWarps * kFragSize) && BQ % (kNWarps * kFragSize) == 0, "Each simdgroup must host atleast 1 simdgroup matrix along Q sequence."); @@ -180,14 +198,19 @@ template < constexpr int TK = BK / kFragSize; // HeadDim frags (all warps load the same frags) constexpr int TD = BD / kFragSize; + constexpr int TDh = TD / WN; + constexpr int BDh = BD / WN; + constexpr int TVh = BV / (kFragSize * WN); + constexpr int BVh = BV / WN; static_assert(TQ == 1, "Check TQ"); - MMATile Qtile; - MMATile Ktile; + MMATile Qtile; + MMATile Ktile; MMATile Stile; - MMATile Vtile; - MMATile Otile; + MMATile Vtile; + MMATile Otile; + MMATile Qtiles[q_in_registers ? TDh : 1]; Otile.clear(); @@ -195,22 +218,45 @@ template < const short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id); const short sm = simd_coord.y; const short sn = simd_coord.x; - const short tm = kFragSize * TQ * simd_group_id; + const short row_group = simd_group_id / WN; + const short d_half = simd_group_id % WN; + const short tm = kFragSize * TQ * row_group; - const short Qs_offset = (tm + sm) * LDQ_tgp + sn; - const short Ks_offset = sm * LDK_tgp + sn; - const short Vs_offset = sm * LDV_tgp + sn; + const short Qs_offset = (tm + sm) * LDQ_tgp + d_half * BDh + sn; + const short Ks_offset = d_half * BDh * LDK_tgp + sm * LDK_tgp + sn; + const short Vs_offset = sm * LDV_tgp + d_half * BVh + sn; constexpr short Qs_tile_stride = kFragSize; constexpr short Ks_tile_stride = kFragSize * LDK_tgp; threadgroup_barrier(mem_flags::mem_threadgroup); - // Load Q blocks - if (!align_Q && int(tid.x) == (params->NQ_aligned)) { - loader_q.load_safe(short2(BD, params->qL_rem)); + if constexpr (!q_in_registers) { + if (!align_Q && int(tid.x) == (params->NQ_aligned)) { + loader_q.load_safe(short2(BD, params->qL_rem)); + } else { + loader_q.load_unsafe(); + } } else { - loader_q.load_unsafe(); + STEEL_PRAGMA_UNROLL + for (short dd = 0; dd < TDh; dd++) { + const device T* q_src = Q + (tm + sm) * params->Q_strides[2] + + d_half * BDh + dd * kFragSize + sn; + if (!align_Q && int(tid.x) == (params->NQ_aligned)) { + MMAFrag_in_t::load_safe( + Qtiles[dd].frag_at(0, 0), + q_src, + params->Q_strides[2], + Int<1>{}, + params->qL_rem - (tm + sm), + BDh - (dd * kFragSize + sn), + Int<0>{}, + Int<0>{}); + } else { + MMAFrag_in_t::load( + Qtiles[dd].frag_at(0, 0), q_src, params->Q_strides[2], Int<1>{}); + } + } } // Init row reduction variables @@ -262,17 +308,51 @@ template < threadgroup_barrier(mem_flags::mem_threadgroup); STEEL_PRAGMA_UNROLL - for (short dd = 0; dd < TD; dd++) { + for (short dd = 0; dd < TDh; dd++) { simdgroup_barrier(mem_flags::mem_none); - Qtile.template load( - &Qs[Qs_offset + dd * Qs_tile_stride]); + if constexpr (!q_in_registers) { + Qtile.template load( + &Qs[Qs_offset + dd * Qs_tile_stride]); + } Ktile.template load( &Ks[Ks_offset + dd * Ks_tile_stride]); simdgroup_barrier(mem_flags::mem_none); - tile_matmad(Stile, Qtile, Ktile, Stile); + if constexpr (!q_in_registers) { + tile_matmad(Stile, Qtile, Ktile, Stile); + } else { + tile_matmad(Stile, Qtiles[dd], Ktile, Stile); + } + } + + if constexpr (WN == 2) { + constexpr int s_xchg_stride = decltype(Stile)::kElemsPerTile * 32; + constexpr int s_xchg_size = WM * WN * s_xchg_stride; + static_assert( + s_xchg_size * sizeof(AccumType) <= tgp_mem_s * sizeof(T), + "The score exchange must fit in KV_smem"); + + threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup AccumType* s_xchg = + reinterpret_cast(KV_smem); + threadgroup AccumType* slot = + s_xchg + (row_group * WN + d_half) * s_xchg_stride; + const short base = short(simd_lane_id) * decltype(Stile)::kElemsPerTile; + + STEEL_PRAGMA_UNROLL + for (short ii = 0; ii < decltype(Stile)::kElemsPerTile; ii++) { + slot[base + ii] = Stile.elems()[ii]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const threadgroup AccumType* peer = + s_xchg + (row_group * WN + 1 - d_half) * s_xchg_stride; + STEEL_PRAGMA_UNROLL + for (short ii = 0; ii < decltype(Stile)::kElemsPerTile; ii++) { + Stile.elems()[ii] += peer[base + ii]; + } } // Apply scale in float32 @@ -373,7 +453,7 @@ template < // Load V blocks if (!align_K && kb == (params->NK_aligned)) { - loader_v.load_safe(short2(BD, params->kL_rem)); + loader_v.load_safe(short2(BV, params->kL_rem)); } else { loader_v.load_unsafe(); } @@ -425,7 +505,7 @@ template < STEEL_PRAGMA_UNROLL for (short iq = 0; iq < TQ; iq++) { STEEL_PRAGMA_UNROLL - for (short id = 0; id < TD; id++) { + for (short id = 0; id < TVh; id++) { STEEL_PRAGMA_UNROLL for (short ik = 0; ik < TK; ik++) { if constexpr (BD >= 128) { @@ -460,11 +540,25 @@ template < Otile.template row_bin_op(sum_score); threadgroup_barrier(mem_flags::mem_none); + // Store the logsumexp for the backward pass + if (save_lse && sn == 0) { + using stile_t = decltype(Stile); + const bool is_last_q = int(tid.x) == (params->NQ_aligned); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + sm + i * stile_t::kFragRows; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = M_LN2_F * (max_score[i] + metal::log2(sum_score[i])); + } + } + } + // Store results - O += (tm + sm) * params->O_strides[2] + sn; + O += (tm + sm) * params->O_strides[2] + d_half * BVh + sn; if (!align_Q && int(tid.x) == (params->NQ_aligned)) { - auto dst_tile_dims = short2(BD - sn, params->qL_rem - (tm + sm)); + auto dst_tile_dims = short2(BVh - sn, params->qL_rem - (tm + sm)); if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) return; @@ -473,4 +567,4 @@ template < } else { Otile.template store(O, params->O_strides[2]); } -} +} \ No newline at end of file diff --git a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.metal b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.metal index fbd84004f0..44ed0b61e3 100644 --- a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.metal +++ b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.metal @@ -1,31 +1,36 @@ -// Copyright © 2024-25 Apple Inc. +// Copyright © 2024-26 Apple Inc. // clang-format off #include "mlx/backend/metal/kernels/utils.h" #include "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h" -#define instantiate_attn(tname, dtype, bq, bk, bd, wm, wn, mname, mtype) \ - instantiate_kernel( \ - "steel_attention_" #tname "_bq" #bq "_bk" #bk "_bd" #bd \ - "_wm" #wm "_wn" #wn "_mask" #mname, \ - attention, dtype, bq, bk, bd, wm, wn, mtype, float) +#define instantiate_attn(tname, dtype, bq, bk, bd, bv, wm, wn, mname, mtype) \ + instantiate_kernel( \ + "steel_attention_" #tname "_bq" #bq "_bk" #bk "_bd" #bd "_bv" #bv \ + "_wm" #wm "_wn" #wn "_mask" #mname, \ + attention, dtype, bq, bk, bd, bv, wm, wn, mtype, float) -#define instantiate_attn_shapes_helper(iname, itype, mname, mtype) \ - instantiate_attn(iname, itype, 32, 16, 256, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 16, 192, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 16, 128, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 32, 96, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 32, 80, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 32, 72, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 32, 32, 64, 4, 1, mname, mtype) +#define instantiate_attn_helper(iname, itype, bq, bk, bd, bv, wm, wn) \ + instantiate_attn(iname, itype, bq, bk, bd, bv, wm, wn, iname, itype) \ + instantiate_attn(iname, itype, bq, bk, bd, bv, wm, wn, bool_, bool) -#define instantiate_attn_mask_helper(iname, itype) \ - instantiate_attn_shapes_helper(iname, itype, iname, itype) \ - instantiate_attn_shapes_helper(iname, itype, bool_, bool) +#define instantiate_attn_shapes_helper(iname, itype) \ + instantiate_attn_helper(iname, itype, 32, 16, 192, 192, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 16, 128, 128, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 32, 96, 96, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 32, 96, 64, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 32, 80, 80, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 32, 72, 72, 4, 1) \ + instantiate_attn_helper(iname, itype, 32, 32, 64, 64, 4, 1) -instantiate_attn_mask_helper(float16, half); -instantiate_attn_mask_helper(bfloat16, bfloat16_t); +instantiate_attn_shapes_helper(float16, half); +instantiate_attn_shapes_helper(bfloat16, bfloat16_t); +instantiate_attn_shapes_helper(float32, float); -instantiate_attn_mask_helper(float32, float); +instantiate_attn_helper(float16, half, 32, 16, 256, 256, 4, 2); +instantiate_attn_helper(float16, half, 32, 32, 256, 256, 4, 2); +instantiate_attn_helper(bfloat16, bfloat16_t, 32, 16, 256, 256, 4, 2); +instantiate_attn_helper(bfloat16, bfloat16_t, 32, 32, 256, 256, 4, 2); +instantiate_attn_helper(float32, float, 32, 16, 256, 256, 4, 2); // clang-format on diff --git a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.h b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.h index 4a5a9716fd..13cf24f78a 100644 --- a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.h +++ b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.h @@ -1,4 +1,4 @@ -// Copyright © 2024-25 Apple Inc. +// Copyright © 2024-26 Apple Inc. #include "mlx/backend/metal/kernels/steel/attn/nax.h" #include "mlx/backend/metal/kernels/steel/attn/params.h" @@ -17,6 +17,7 @@ constant bool align_K [[function_constant(201)]]; constant bool has_mask [[function_constant(300)]]; constant bool do_causal [[function_constant(301)]]; constant bool has_sinks [[function_constant(302)]]; +constant bool save_lse [[function_constant(303)]]; template struct TransformScale { @@ -76,6 +77,7 @@ template < int BQ, int BK, int BD, + int BV, int WM, int WN, typename MaskType = float, @@ -89,6 +91,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* lse [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -116,6 +119,13 @@ template < tidl.y * params->O_strides[1] + // Head tidl.x * BQ * params->O_strides[2]; // Sequence + if (save_lse) { + // [B, H, qL], contiguous. + lse += tidl.z * params->H * params->qL + // Batch + tidl.y * params->qL + // Head + tidl.x * BQ; // Sequence + } + if (has_mask) { mask += tidl.z * mask_params->M_strides[0] + // Batch tidl.y * mask_params->M_strides[1]; // Head @@ -136,11 +146,13 @@ template < constexpr int TQ = BQ / (kNWarps * kU); // HeadDim frags (all warps load the same frags) constexpr int TD = BD / kU; + constexpr int TV = BV / kU; + static_assert(BD % kU == 0 && BV % (2 * kU) == 0, "Invalid head dimensions"); // KV seq frags per warp constexpr short TK = BK / kU; static_assert(TQ == 1, "Check TQ"); - using otile_t = NAXTile; + using otile_t = NAXTile; otile_t Otile; Otile.clear(); @@ -421,8 +433,8 @@ template < STEEL_PRAGMA_UNROLL for (short iq = 0; iq < TQ; iq++) { STEEL_PRAGMA_UNROLL - for (short id = 0; id < TD; id += 2) { - if constexpr (BD == 128) { + for (short id = 0; id < TV; id += 2) { + if constexpr (BV == 128) { if (id == 4) { threadgroup_barrier(mem_flags::mem_none); } @@ -472,6 +484,16 @@ template < Otile.template row_bin_op(rcp); + if (save_lse && sn == 0) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const short r = tm + i * otile_t::kFragRowsJump + sm; + if (align_Q || !is_last_q || r < params->qL_rem) { + lse[r] = max_score[i] * M_LN2_F + metal::log(sum_score[i]); + } + } + } + // Store results O += tm * int(params->O_strides[2]); @@ -489,15 +511,10 @@ template < // Head-dim split attention kernel /////////////////////////////////////////////////////////////////////////////// -// Variant of attention_nax for wide heads (bd = 256). There, the per-simdgroup -// accumulator working set of attention_nax (TD output fragments plus the S -// fragments) is what gates tensor-unit throughput, so this kernel splits the -// head dim across the WN = 2 simdgroups of the second warp dimension: each -// simdgroup of a pair owns one half of D for Q@K.T and one half of Dv for P@V, -// halving its accumulator set. The pair exchanges its partial Q@K.T sums -// through threadgroup memory, then both simdgroups run softmax redundantly on -// the full S tile (the row statistics are cheap) and each accumulates P@V for -// its own half of Dv. +// Split wide heads across WN simdgroups to reduce the accumulator working set. +// Each group owns one D slice. The groups exchange their partial Q@K.T scores +// through threadgroup memory and reduce them in the same order. Each group then +// runs softmax and accumulates its P@V slice. // clang-format off template < @@ -518,6 +535,7 @@ template < const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]], const device MaskType* mask [[buffer(6), function_constant(has_mask)]], const device T* sinks [[buffer(7), function_constant(has_sinks)]], + device float* LSE [[buffer(8), function_constant(save_lse)]], uint simd_lane_id [[thread_index_in_simdgroup]], uint simd_group_id [[simdgroup_index_in_threadgroup]], uint3 tid [[threadgroup_position_in_grid]], @@ -556,9 +574,9 @@ template < constexpr short kU = 16; // The WM simdgroups along the first warp dimension split the Q sequence; - // the WN simdgroups along the second split the head dim. The exchange - // below reduces exactly one peer, so WN is fixed at 2. - static_assert(WN == 2, "The head-dim split kernel needs WN == 2"); + // the WN simdgroups along the second split the head dim. + static_assert( + WN == 2 || WN == 4, "The head-dim split kernel needs WN == 2 or WN == 4"); constexpr int kNWarps = WM; static_assert( BQ >= (kNWarps * kU) && BQ % (kNWarps * kU) == 0, @@ -579,20 +597,20 @@ template < constexpr int BDh = BD / WN; static_assert(TDh % 2 == 0, "P@V accumulates output fragments in pairs"); - static_assert(TK % 2 == 0, "S fragments are exchanged pair by pair"); + static_assert(TK % 2 == 0, "S fragments are computed pair by pair"); const short row_group = simd_group_id / WN; - const short d_half = simd_group_id % WN; + const short d_group = simd_group_id % WN; using otile_t = NAXTile; otile_t Otile; Otile.clear(); const short tm = kU * TQ * row_group; - Q += tm * int(params->Q_strides[2]) + d_half * BDh; - K += d_half * BDh; - V += d_half * BDh; - O += tm * int(params->O_strides[2]) + d_half * BDh; + Q += tm * int(params->Q_strides[2]) + d_group * BDh; + K += d_group * BDh; + V += d_group * BDh; + O += tm * int(params->O_strides[2]) + d_group * BDh; constexpr short kRowsPT = otile_t::kRowsPerThread; @@ -632,12 +650,11 @@ template < using stile_t = NAXTile; constexpr short kEPF = stile_t::NAXFrag_t::kElemsPerFrag; - // One slot per (row group, half): a fragment pair in per-lane-linear - // layout. Both halves share the fragment-to-lane mapping, so the - // exchange needs no coordinate math. - threadgroup AccumType s_xchg[WM][WN][2 * kEPF * 32]; + // One slot per (row group, D group) in per-lane-linear layout. All groups + // share the fragment-to-lane mapping. + threadgroup AccumType s_xchg[WM][WN][TK * kEPF * 32]; - // Keep the simdgroup's Q half resident in registers for the whole KV + // Keep the simdgroup's Q slice resident in registers for the whole KV // loop: TDh fragments of T are cheap next to the accumulators. NAXTile Qtiles[TDh]; STEEL_PRAGMA_UNROLL @@ -662,7 +679,7 @@ template < stile_t Stile; Stile.clear(); - // S = Q @ K.T, this half of D only, exchanged pair by pair. + // S = Q @ K.T for this D slice. STEEL_PRAGMA_UNROLL for (short ik = 0; ik < TK; ik += 2) { STEEL_PRAGMA_UNROLL @@ -686,26 +703,37 @@ template < Ktile.frag_at(1, 0), metal::true_type{}); } + } - // Exchange the partial pair and reduce. - threadgroup AccumType* slot = s_xchg[row_group][d_half]; - thread auto& s0 = Stile.frag_at(0, ik); - thread auto& s1 = Stile.frag_at(0, ik + 1); - const short base = short(simd_lane_id) * (2 * kEPF); + // Exchange all partial scores and reduce them in a fixed order. + threadgroup AccumType* slot = s_xchg[row_group][d_group]; + const short base = short(simd_lane_id) * (TK * kEPF); + STEEL_PRAGMA_UNROLL + for (short ik = 0; ik < TK; ik++) { + thread auto& s = Stile.frag_at(0, ik); STEEL_PRAGMA_UNROLL for (short i = 0; i < kEPF; i++) { - slot[base + i] = s0[i]; - slot[base + kEPF + i] = s1[i]; + slot[base + ik * kEPF + i] = s[i]; } - threadgroup_barrier(mem_flags::mem_threadgroup); - const threadgroup AccumType* peer = s_xchg[row_group][1 - d_half]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + STEEL_PRAGMA_UNROLL + for (short ik = 0; ik < TK; ik++) { + thread auto& s = Stile.frag_at(0, ik); STEEL_PRAGMA_UNROLL for (short i = 0; i < kEPF; i++) { - s0[i] += peer[base + i]; - s1[i] += peer[base + kEPF + i]; + s[i] = s_xchg[row_group][0][base + ik * kEPF + i]; + } + STEEL_PRAGMA_UNROLL + for (short peer_group = 1; peer_group < WN; peer_group++) { + const threadgroup AccumType* peer = s_xchg[row_group][peer_group]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kEPF; i++) { + s[i] += peer[base + ik * kEPF + i]; + } } - threadgroup_barrier(mem_flags::mem_threadgroup); } + threadgroup_barrier(mem_flags::mem_threadgroup); // Scale S STEEL_PRAGMA_UNROLL @@ -826,7 +854,7 @@ template < } } - // Do softmax (redundantly per half; the row statistics are cheap) + // Do softmax in each D group; the row statistics are cheap. metal::vec new_max; metal::vec factor; STEEL_PRAGMA_UNROLL @@ -854,7 +882,7 @@ template < simdgroup_barrier(mem_flags::mem_none); - // O = P @ V, this half of Dv only. + // O = P @ V for this D slice. STEEL_PRAGMA_UNROLL for (short id = 0; id < TDh; id += 2) { STEEL_PRAGMA_UNROLL @@ -895,6 +923,21 @@ template < rcp[i] = 1.f / sum_score[i]; } + if (save_lse && d_group == 0 && sn == 0) { + const int lse_row_base = int(tid.x) * BQ + tm; + const int lse_head_off = (int(tid.z) * params->H + int(tid.y)) * params->qL; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const int row = lse_row_base + i * stile_t::kFragRowsJump + sm; + if (row < params->qL) { + LSE[lse_head_off + row] = (sum_score[i] == 0) + ? -INFINITY + : float(M_LN2_F * (max_score[i] + metal::log2(sum_score[i]))); + } + } + } + Otile.template row_bin_op(rcp); if (!align_Q && is_last_q) { diff --git a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.metal b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.metal index 66d55539ab..eba254155d 100644 --- a/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.metal +++ b/mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.metal @@ -1,29 +1,33 @@ -// Copyright © 2024-25 Apple Inc. +// Copyright © 2024-26 Apple Inc. // clang-format off #include "mlx/backend/metal/kernels/utils.h" #include "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention_nax.h" -#define instantiate_attn(tname, dtype, bq, bk, bd, wm, wn, mname, mtype) \ - instantiate_kernel( \ - "steel_attention_" #tname "_bq" #bq "_bk" #bk "_bd" #bd \ - "_wm" #wm "_wn" #wn "_mask" #mname, \ - attention_nax, dtype, bq, bk, bd, wm, wn, mtype, float) +#define instantiate_attn(tname, dtype, bq, bk, bd, bv, wm, wn, mname, mtype) \ + instantiate_kernel( \ + "steel_attention_" #tname "_bq" #bq "_bk" #bk "_bd" #bd "_bv" #bv \ + "_wm" #wm "_wn" #wn "_mask" #mname, \ + attention_nax, dtype, bq, bk, bd, bv, wm, wn, mtype, float) #define instantiate_attn_dsplit(tname, dtype, bq, bk, bd, wm, wn, mname, mtype) \ instantiate_kernel( \ - "steel_attention_dsplit_" #tname "_bq" #bq "_bk" #bk "_bd" #bd \ + "steel_attention_dsplit_" #tname "_bq" #bq "_bk" #bk "_bd" #bd "_bv" #bd \ "_wm" #wm "_wn" #wn "_mask" #mname, \ attention_nax_dsplit, dtype, bq, bk, bd, wm, wn, mtype, float) #define instantiate_attn_shapes_helper(iname, itype, mname, mtype) \ + instantiate_attn_dsplit(iname, itype, 32, 32, 512, 2, 4, mname, mtype) \ instantiate_attn_dsplit(iname, itype, 64, 32, 256, 4, 2, mname, mtype) \ - instantiate_attn(iname, itype, 64, 32, 128, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 64, 32, 96, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 64, 32, 64, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 64, 64, 128, 4, 1, mname, mtype) \ - instantiate_attn(iname, itype, 64, 64, 64, 4, 1, mname, mtype) + instantiate_attn(iname, itype, 64, 64, 128, 128, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 64, 64, 64, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 32, 256, 256, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 32, 128, 128, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 32, 96, 96, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 32, 96, 64, 4, 1, mname, mtype) \ + instantiate_attn(iname, itype, 64, 32, 64, 64, 4, 1, mname, mtype) + #define instantiate_attn_mask_helper(iname, itype) \ instantiate_attn_shapes_helper(iname, itype, iname, itype) \ @@ -31,6 +35,5 @@ instantiate_attn_mask_helper(float16, half); instantiate_attn_mask_helper(bfloat16, bfloat); - instantiate_attn_mask_helper(float32, float); // clang-format on diff --git a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.h b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.h index f559596b73..f948ec069a 100644 --- a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.h +++ b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.h @@ -46,7 +46,7 @@ implicit_gemm_conv_2d( using loader_a_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DInputBlockLoaderSmallChannels< @@ -84,7 +84,7 @@ implicit_gemm_conv_2d( // Weight loader using loader_b_t = typename metal::conditional_t< // Check for small channel specialization - N_CHANNELS != 0 && N_CHANNELS <= 4, + N_CHANNELS != 0 && N_CHANNELS <= 8, // Go to small channel specialization Conv2DWeightBlockLoaderSmallChannels< diff --git a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.metal b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.metal index 7851e5ef14..475d28e53f 100644 --- a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.metal +++ b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv.metal @@ -43,13 +43,17 @@ instantiate_implicit_conv_2d(name, itype, bm, bn, bk, wm, wn, 3, 3, l, false) \ instantiate_implicit_conv_2d(name, itype, bm, bn, bk, wm, wn, 4, 4, l, false) -#define instantiate_implicit_2d_blocks(name, itype) \ - instantiate_implicit_2d_filter(name, itype, 32, 8, 16, 4, 1) \ - instantiate_implicit_2d_filter(name, itype, 64, 8, 16, 4, 1) \ - instantiate_implicit_2d_filter(name, itype, 32, 32, 16, 2, 2) \ - instantiate_implicit_2d_filter(name, itype, 32, 64, 16, 2, 2) \ - instantiate_implicit_2d_filter(name, itype, 64, 32, 16, 2, 2) \ - instantiate_implicit_2d_filter(name, itype, 64, 64, 16, 2, 2) +// The 8 channel loader reads one row per thread and needs bm = 64 +#define instantiate_implicit_2d_blocks(name, itype) \ + instantiate_implicit_2d_filter(name, itype, 32, 8, 16, 4, 1) \ + instantiate_implicit_2d_filter(name, itype, 64, 8, 16, 4, 1) \ + instantiate_implicit_2d_filter(name, itype, 32, 32, 16, 2, 2) \ + instantiate_implicit_2d_filter(name, itype, 32, 64, 16, 2, 2) \ + instantiate_implicit_2d_filter(name, itype, 64, 32, 16, 2, 2) \ + instantiate_implicit_2d_filter(name, itype, 64, 64, 16, 2, 2) \ + instantiate_implicit_conv_2d(name, itype, 64, 8, 16, 4, 1, 8, 8, l, false) \ + instantiate_implicit_conv_2d(name, itype, 64, 32, 16, 2, 2, 8, 8, l, false) \ + instantiate_implicit_conv_2d(name, itype, 64, 64, 16, 2, 2, 8, 8, l, false) instantiate_implicit_2d_blocks(float32, float); instantiate_implicit_2d_blocks(float16, half); diff --git a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv_general.h b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv_general.h index 38250f9b81..bb896711c4 100644 --- a/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv_general.h +++ b/mlx/backend/metal/kernels/steel/conv/kernels/steel_conv_general.h @@ -186,7 +186,7 @@ implicit_gemm_conv_2d_general( if (offset_n >= gemm_params->N) return; - short diff = gemm_params->N - offset_n; + int diff = gemm_params->N - offset_n; STEEL_PRAGMA_UNROLL for (int i = 0; i < mma_t::TM; i++) { diff --git a/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_l.h b/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_l.h index 15dc13cccf..ad1f68dacf 100644 --- a/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_l.h +++ b/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_l.h @@ -47,8 +47,8 @@ struct Conv2DInputBlockLoaderLargeFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -197,8 +197,8 @@ struct Conv2DInputBlockLoaderSmallFilter { const constant MLXConvParams<2>* params; const constant ImplicitGemmConv2DParams* gemm_params; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -384,6 +384,7 @@ struct Conv2DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -405,11 +406,12 @@ struct Conv2DWeightBlockLoader { weight_hw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ METAL_FUNC void load_unsafe() const thread { - if (BN != 8 || do_read) { + if (do_read) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BN; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -419,7 +421,7 @@ struct Conv2DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; @@ -481,9 +483,9 @@ struct Conv3DInputBlockLoaderLargeFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; short kdil_d; short kdil_h; @@ -665,9 +667,9 @@ struct Conv3DInputBlockLoaderSmallFilter { const constant MLXConvParams<3>* params; const constant ImplicitGemmConv3DParams* gemm_params; - short weight_d; - short weight_h; - short weight_w; + int weight_d; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -887,6 +889,7 @@ struct Conv3DWeightBlockLoader { int weight_step; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -908,11 +911,12 @@ struct Conv3DWeightBlockLoader { weight_dhw(0), weight_step(params->C / params->groups), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + n_rows * TROWS <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ METAL_FUNC void load_unsafe() const thread { - if (BN != 8 || do_read) { + if (do_read) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BN; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -922,7 +926,7 @@ struct Conv3DWeightBlockLoader { } } else { for (short i = 0; i < BN; i += TROWS) { - if ((read_n + i) < params->O) { + if ((read_n + i) < N) { STEEL_PRAGMA_UNROLL for (short j = 0; j < vec_size; j++) { dst[i * dst_ld + j] = src[i * src_ld + j]; diff --git a/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_n.h b/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_n.h index 6a6c16daf0..ae07495a55 100644 --- a/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_n.h +++ b/mlx/backend/metal/kernels/steel/conv/loaders/loader_channel_n.h @@ -71,6 +71,7 @@ struct Conv2DInputBlockLoaderSmallChannels { // Rows / strided reads within the block STEEL_CONST short n_rows = BROWS / TROWS; + static_assert(n_rows > 0, "BM must be at least tgp_size * vec_size / BK"); // Thread location indices const short thread_idx; @@ -233,6 +234,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { int weight_hw; const int read_n; + const int N; const bool do_read; /* Constructor */ @@ -253,6 +255,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { params(params_), weight_hw(thread_idx % TCOLS), read_n(offsets.y + bi), + N(gemm_params_->N), do_read(read_n + BN <= gemm_params_->N) {} /* Load from device memory into threadgroup memory - without bound checking */ @@ -260,7 +263,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { if (bi >= BROWS || bj >= BCOLS) return; - if (read_n >= params->O || weight_hw >= params->wS[1] * params->wS[0]) { + if (read_n >= N || weight_hw >= params->wS[1] * params->wS[0]) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BROWS; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -274,7 +277,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { const device T* curr_src = src + weight_hw * (params->C / params->groups); - if (BN != 8 || do_read) { + if (do_read) { STEEL_PRAGMA_UNROLL for (short i = 0; i < BROWS; i += TROWS) { STEEL_PRAGMA_UNROLL @@ -289,7 +292,7 @@ struct Conv2DWeightBlockLoaderSmallChannels { } } else { for (short i = 0; i < BROWS; i += TROWS) { - if (((read_n + i) < params->O)) { + if (((read_n + i) < N)) { STEEL_PRAGMA_UNROLL for (short j = 0; j < n_channels; j++) { dst[i * dst_ld + j] = curr_src[i * src_ld + j]; diff --git a/mlx/backend/metal/kernels/steel/conv/loaders/loader_general.h b/mlx/backend/metal/kernels/steel/conv/loaders/loader_general.h index cf7794235d..6bc90e8694 100644 --- a/mlx/backend/metal/kernels/steel/conv/loaders/loader_general.h +++ b/mlx/backend/metal/kernels/steel/conv/loaders/loader_general.h @@ -48,8 +48,8 @@ struct Conv2DInputBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const device T* src[n_rows]; @@ -248,8 +248,8 @@ struct Conv2DWeightBlockLoaderGeneral { const short base_wh; const short base_ww; - short weight_h; - short weight_w; + int weight_h; + int weight_w; const int start_row; diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_fused_nax.metal b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_fused_nax.metal index 97cbe4ea1a..f2a36fe104 100644 --- a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_fused_nax.metal +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_fused_nax.metal @@ -23,6 +23,8 @@ #define instantiate_gemm_shapes_helper(iname, itype, oname, otype) \ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 64, 256, 2, 2) \ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 128, 64, 2, 4) \ + instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 128, 512, 2, 4) \ + instantiate_gemm_transpose_helper(iname, itype, oname, otype, 128, 64, 512, 4, 2) \ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 128, 256, 2, 4) \ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 128, 128, 64, 4, 4) \ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 128, 128, 256, 4, 4) \ diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented.h b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented.h index 5a43e2233f..6814ef50d4 100644 --- a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented.h +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented.h @@ -79,8 +79,8 @@ template < k_start = segments[tid.z]; k_end = segments[tid.z + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid.z * params->batch_stride_d; // Prepare threadgroup mma operation diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented_nax.h b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented_nax.h index 9cfece5c54..5731cb8c12 100644 --- a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented_nax.h +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_segmented_nax.h @@ -51,8 +51,8 @@ void segmented_mm_nax( k_start = segments[tid_s]; k_end = segments[tid_s + 1]; } - A += transpose_a ? k_start * params->lda : k_start; - B += transpose_b ? k_start : k_start * params->ldb; + A += transpose_a ? int64_t(k_start) * params->lda : k_start; + B += transpose_b ? k_start : int64_t(k_start) * params->ldb; C += tid_s * params->batch_stride_d; constexpr short SM = BM / WM; diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk_nax.metal b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk_nax.metal index b1b6b89626..f848997f48 100644 --- a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk_nax.metal +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_splitk_nax.metal @@ -22,6 +22,8 @@ #define instantiate_gemm_splitk_shapes_helper(iname, itype, oname, otype) \ instantiate_gemm_splitk_transpose_helper(iname, itype, oname, otype, 64, 64, 256, 2, 2) \ + instantiate_gemm_splitk_transpose_helper(iname, itype, oname, otype, 64, 128, 512, 2, 4) \ + instantiate_gemm_splitk_transpose_helper(iname, itype, oname, otype, 128, 64, 512, 4, 2) \ instantiate_gemm_splitk_transpose_helper(iname, itype, oname, otype, 128, 128, 512, 4, 4) instantiate_gemm_splitk_shapes_helper(float16, half, float32, float); diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h new file mode 100644 index 0000000000..28229a03cf --- /dev/null +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h @@ -0,0 +1,223 @@ +// Copyright © 2026 Apple Inc. + +using namespace mlx::steel; + +constant bool use_out_source [[function_constant(100)]]; +constant bool do_axpby [[function_constant(110)]]; + +constant bool align_M [[function_constant(200)]]; +constant bool align_N [[function_constant(201)]]; +constant bool align_K [[function_constant(202)]]; + +// Each simdgroup computes one (16 * UM) x (16 * UN) block of D. It keeps a K +// chunk of A in registers and MPP reads the B chunk from device memory. +// KS groups of SM x SN simdgroups split K. +// clang-format off +template < + typename T, + int UM, + int UN, + int SM, + int SN, + int KS, + bool transpose_b> +[[kernel, max_total_threads_per_threadgroup(SM * SN * KS * 32)]] void gemm_thin_nax( + const device T* A [[buffer(0)]], + const device T* B [[buffer(1)]], + const device T* C [[buffer(2), function_constant(use_out_source)]], + device T* D [[buffer(3)]], + const constant GEMMParams* params [[buffer(4)]], + const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on + using extents_t = metal::dextents; + using strides_t = metal::array; + using tensor_t = metal::tensor; + + constexpr int TSM = 16 * UM; + constexpr int TSN = 16 * UN; + constexpr int BK = 64; + + const int M = params->M; + const int N = params->N; + const int K = params->K; + const int lda = params->lda; + const int ldb = params->ldb; + + // Threadgroups go along M first, so groups that run together share B. + const int tgp = tid.x; + const int tile_m = tgp % params->tiles_m; + const int tile_n = tgp / params->tiles_m; + + const int k_group = simd_group_id / (SM * SN); + const int sg = simd_group_id % (SM * SN); + int m_off = (tile_m * SM + sg % SM) * TSM; + int n_off = (tile_n * SN + sg / SM) * TSN; + + // A block at the edge moves back inside if the matrix is large enough. It + // then writes again some outputs of a neighbor block, with equal values. + const bool active = (align_M || m_off < M) && (align_N || n_off < N); + if (!align_M && m_off + TSM > M && M >= TSM) { + m_off = M - TSM; + } + if (!align_N && n_off + TSN > N && N >= TSN) { + n_off = N - TSN; + } + const bool inside = + (align_M || m_off + TSM <= M) && (align_N || n_off + TSN <= N); + const int rows = active ? M - m_off : 0; + const int cols = active ? N - n_off : 0; + + A += int64_t(m_off) * lda; + B += transpose_b ? int64_t(n_off) * ldb : int64_t(n_off); + D += int64_t(m_off) * params->ldd + n_off; + if (use_out_source) { + C += + int64_t(m_off) * addmm_params->ldc + int64_t(n_off) * addmm_params->fdc; + } + + tensor_t tA((device T*)A, extents_t(K, rows), strides_t{1, lda}); + tensor_t tB( + (device T*)B, + transpose_b ? extents_t(K, cols) : extents_t(cols, K), + strides_t{1, ldb}); + + auto a_chunk = [&](int k) { return tA.template slice(k, 0); }; + auto b_chunk = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + auto b_tail = [&](int k) { + if constexpr (transpose_b) { + return tB.template slice(k, 0); + } else { + return tB.template slice(0, k); + } + }; + using a_chunk_t = decltype(a_chunk(0)); + using b_chunk_t = decltype(b_chunk(0)); + + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + TSM, + TSN, + BK, + false, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + mpp::tensor_ops::matmul2d op; + + // The accumulator layout depends only on the element types, so the masked + // runs below can also use it. + auto Dacc = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] = 0.0f; + } + auto Areg = op.template get_left_input_cooperative_tensor(); + + const int k_iters = params->gemm_k_iterations_aligned; + for (int it = 0; it < k_iters; it++) { + // Keep the simdgroups near each other in K, so that their shared loads + // hit in cache. + if ((it & 3) == 0) { + threadgroup_barrier(mem_flags::mem_none); + } + const int k = (it * KS + k_group) * BK; + if (!active || k >= K) { + continue; + } + if (inside && (align_K || k + BK <= K)) { + auto a = a_chunk(k); + Areg.load(a); + auto b = b_chunk(k); + op.run(Areg, b, Dacc); + } else if (inside) { + auto a = tA.template slice(k, 0); + auto b = b_tail(k); + op.run(a, b, Dacc); + } else { + // The views stop at the matrix edge and MPP masks the rest. + const int kk = min(BK, K - k); + tensor_t vA((device T*)A + k, extents_t(kk, rows), strides_t{1, lda}); + tensor_t vB( + (device T*)B + (transpose_b ? int64_t(k) : int64_t(k) * ldb), + transpose_b ? extents_t(kk, cols) : extents_t(cols, kk), + strides_t{1, ldb}); + op.run(vA, vB, Dacc); + } + } + + if constexpr (KS > 1) { + // K groups 1 to KS - 1 store their partial sums and group 0 adds them. + using tg_tensor_t = + metal::tensor; + constexpr int kBlockSize = TSM * TSN; + static_assert( + (KS - 1) * SM * SN * kBlockSize <= 4096, + "Partial sums need more than 16 KB of threadgroup memory"); + threadgroup float partials[(KS - 1) * SM * SN * kBlockSize]; + + if (active && k_group > 0) { + tg_tensor_t tP( + partials + ((k_group - 1) * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + Dacc.store(tP); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (active && k_group == 0) { + for (int g = 0; g < KS - 1; g++) { + tg_tensor_t tP( + partials + (g * SM * SN + sg) * kBlockSize, + extents_t(TSN, TSM), + strides_t{1, TSN}); + auto part = op.template get_destination_cooperative_tensor< + a_chunk_t, + b_chunk_t, + float>(); + part.load(tP); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + Dacc[i] += part[i]; + } + } + } + } + if (k_group != 0 || !active) { + return; + } + + auto Dout = + op.template get_destination_cooperative_tensor(); + STEEL_PRAGMA_UNROLL + for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + float d = Dacc[i]; + if (use_out_source) { + auto idx = Dacc.get_multidimensional_index(i); + const int r = idx[1]; + const int c = idx[0]; + if (inside || (r < rows && c < cols)) { + float c_val = static_cast( + C[int64_t(r) * addmm_params->ldc + int64_t(c) * addmm_params->fdc]); + d = do_axpby ? addmm_params->alpha * d + addmm_params->beta * c_val + : d + c_val; + } + } + Dout[i] = static_cast(d); + } + + tensor_t tD(D, extents_t(cols, rows), strides_t{1, params->ldd}); + if (inside) { + auto d = tD.template slice(0, 0); + Dout.store(d); + } else { + Dout.store(tD); + } +} diff --git a/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.metal b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.metal new file mode 100644 index 0000000000..e3f87e8dc4 --- /dev/null +++ b/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.metal @@ -0,0 +1,27 @@ +// Copyright © 2026 Apple Inc. + +#include + +#include "mlx/backend/metal/kernels/utils.h" + +#include "mlx/backend/metal/kernels/steel/gemm/gemm_nax.h" +#include "mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_thin_nax.h" + +// clang-format off +#define instantiate_gemm_thin(tname, trans_b, iname, itype, um, un, sm, sn, ks) \ + instantiate_kernel( \ + "steel_gemm_thin_nax_" #tname "_" #iname \ + "_um" #um "_un" #un "_sm" #sm "_sn" #sn "_ks" #ks, \ + gemm_thin_nax, itype, um, un, sm, sn, ks, trans_b) + +#define instantiate_gemm_thin_transpose_helper(iname, itype, um, un, sm, sn, ks) \ + instantiate_gemm_thin(nn, false, iname, itype, um, un, sm, sn, ks) \ + instantiate_gemm_thin(nt, true , iname, itype, um, un, sm, sn, ks) + +#define instantiate_gemm_thin_shapes_helper(iname, itype) \ + instantiate_gemm_thin_transpose_helper(iname, itype, 2, 2, 1, 1, 4) \ + instantiate_gemm_thin_transpose_helper(iname, itype, 2, 2, 1, 2, 2) + +instantiate_gemm_thin_shapes_helper(float16, half); +instantiate_gemm_thin_shapes_helper(bfloat16, bfloat); +// clang-format on diff --git a/mlx/backend/metal/kernels/steel/gemm/mma.h b/mlx/backend/metal/kernels/steel/gemm/mma.h index 1d9e0a7820..a5c0503ece 100644 --- a/mlx/backend/metal/kernels/steel/gemm/mma.h +++ b/mlx/backend/metal/kernels/steel/gemm/mma.h @@ -510,7 +510,9 @@ struct BlockMMA { } /* (BM, BK) X (BK, BN) multiply accumulate function */ - METAL_FUNC void mma(const threadgroup T* As, const threadgroup T* Bs) thread { + template + METAL_FUNC void mma(const threadgroup T* As, const threadgroup TB* Bs) + thread { // Adjust for simdgroup and thread location As += As_offset; Bs += Bs_offset; @@ -524,7 +526,7 @@ struct BlockMMA { simdgroup_barrier(mem_flags::mem_none); - Btile.template load(Bs); + Btile.template load(Bs); simdgroup_barrier(mem_flags::mem_none); diff --git a/mlx/backend/metal/kernels/unary_ops.h b/mlx/backend/metal/kernels/unary_ops.h index 1337f6b52e..4c6088fc4b 100644 --- a/mlx/backend/metal/kernels/unary_ops.h +++ b/mlx/backend/metal/kernels/unary_ops.h @@ -35,7 +35,7 @@ struct Abs { return x; }; complex64_t operator()(complex64_t x) thread { - return {metal::precise::sqrt(x.real * x.real + x.imag * x.imag), 0}; + return {hypot(x.real, x.imag), 0}; }; }; @@ -308,7 +308,7 @@ struct Round { struct Sigmoid { template T operator()(T x) thread { - auto y = 1 / (1 + metal::exp(metal::abs(x))); + auto y = 1 / (1 + metal::precise::exp(metal::abs(x))); return (x < 0) ? y : 1 - y; } }; @@ -325,8 +325,8 @@ struct Sign { if (x == complex64_t(0)) { return x; } - return x / - (complex64_t)metal::precise::sqrt(x.real * x.real + x.imag * x.imag); + auto r = hypot(x.real, x.imag); + return {x.real / r, x.imag / r}; }; }; @@ -378,7 +378,7 @@ struct Sqrt { auto b_abs = metal::precise::sqrt((r - x.real) / 2.0); auto b = metal::copysign(b_abs, x.imag); return {a, b}; - } + }; }; struct Rsqrt { diff --git a/mlx/backend/metal/kernels/utils.h b/mlx/backend/metal/kernels/utils.h index 84d0b74bf0..405a082819 100644 --- a/mlx/backend/metal/kernels/utils.h +++ b/mlx/backend/metal/kernels/utils.h @@ -353,6 +353,29 @@ inline complex64_t log1p(complex64_t in) { } } +// https://github.com/pytorch/pytorch/blob/a82aae9d4a7827849ce50f31c4c7ee8f278d05f5/c10/metal/utils.h#L554 +inline float hypot(float x, float y) { + if (metal::isinf(x) || metal::isinf(y)) { + return metal::numeric_limits::infinity(); + } + if (metal::isnan(x) || metal::isnan(y)) { + return metal::numeric_limits::quiet_NaN(); + } + float a = metal::fmax(metal::fabs(x), metal::fabs(y)); + float b = metal::fmin(metal::fabs(x), metal::fabs(y)); + if (a == 0.0f) { + return 0.0f; + } + float r = (b / a) * (b / a); + float sqrt_1_plus_r = metal::precise::sqrt(1.0f + r); + float h1 = metal::sqrt(2.0f) * a; + float h2 = a + a * r / 2.0f; + float h3 = a * sqrt_1_plus_r; + bool is_h1 = (a == b); + bool is_h2 = ((sqrt_1_plus_r == 1.0f) && (r > 0.0f)); + return metal::select(metal::select(h3, h2, is_h2), h1, is_h1); +} + /////////////////////////////////////////////////////////////////////////////// // SIMD shuffle ops /////////////////////////////////////////////////////////////////////////////// diff --git a/mlx/backend/metal/matmul.cpp b/mlx/backend/metal/matmul.cpp index b7f1e868eb..3de3ffd7e9 100644 --- a/mlx/backend/metal/matmul.cpp +++ b/mlx/backend/metal/matmul.cpp @@ -7,6 +7,7 @@ #include #include "mlx/backend/common/broadcasting.h" +#include "mlx/backend/common/compiled.h" #include "mlx/backend/common/matmul.h" #include "mlx/backend/gpu/copy.h" #include "mlx/backend/metal/binary.h" @@ -208,11 +209,25 @@ void steel_matmul_regular_axpby_nax( // Temp routing for larger devices char devc = d.get_architecture().back(); - if (devc == 's' || devc == 'c' || devc == 'd') { + if (devc == 's' || devc == 'c') { bk = (K >= 8192 && K > (M + N)) ? 64 : 256; bm = 64; wm = 2; + } else if (devc == 'd') { + if (N > M) { + bm = 128; + bn = 64; + + wm = 4; + wn = 2; + } else { + bm = 64; + bn = 128; + + wm = 2; + wn = 4; + } } // Prepare kernel name @@ -279,8 +294,10 @@ void steel_matmul_regular_axpby_nax( // TODO: Explore device-based tuning for swizzle int swizzle_log = tm <= 3 ? 0 : 1; - if (devc == 's' || devc == 'c' || devc == 'd') { + if (devc == 's' || devc == 'c') { swizzle_log = 2; + } else if (devc == 'd') { + swizzle_log = (M > N) ? 0 : 2; } // Prepare steel matmul params @@ -681,6 +698,33 @@ void steel_gemm_splitk_axpby_nax( int wm = 4, wn = 4; int split_k_partition_size = 4096; + // Temp routing for larger devices + char devc = d.get_architecture().back(); + if (devc == 'd') { + if (M <= 2048 && N <= 2048) { + bm = 64; + bn = 64; + + wm = 2; + wn = 2; + + split_k_partition_size = 2048; + bk = 256; + } else if (N > M) { + bm = 128; + bn = 64; + + wm = 4; + wn = 2; + } else { + bm = 64; + bn = 128; + + wm = 2; + wn = 4; + } + } + if ((M + N) / 2 < 512 || K <= 4096) { bm = bn = 64; bk = 256; @@ -754,6 +798,9 @@ void steel_gemm_splitk_axpby_nax( int tm = (M + bm - 1) / bm; int swizzle_log = tm <= 3 ? 0 : 1; + if (devc == 'd') { + swizzle_log = (M > N) ? 0 : 1; + } // Compute swizzled tile counts int tile = 1 << swizzle_log; @@ -944,7 +991,62 @@ void steel_matmul_axpby( /* float beta = */ beta); } - // Case 2: Large K with sufficient M, N, and NAX is available, use NAX split-K + // Case 2: Few output rows or columns, small tiles with A in registers + if (use_nax && batch_size_out == 1 && !transpose_a && + (N <= 64 || (M <= 64 && transpose_b)) && out.dtype() != float32 && + (transpose_b || int64_t(K) * ldb <= INT_MAX)) { + int sn = M < 2048 ? 1 : 2, ks = 4 / sn; + std::ostringstream kname; + kname << "steel_gemm_thin_nax_n" << (transpose_b ? 't' : 'n') << "_" + << type_to_name(out) << "_um2_un2_sm1_sn" << sn << "_ks" << ks; + auto base_name = kname.str(); + bool use_out_source = CHECK_AB && (alpha != 0.0f || beta != 1.0f); + bool do_axpby = use_out_source && (alpha != 1.0f || beta != 1.0f); + bool align_M = M % 32 == 0, align_N = N % (32 * sn) == 0; + bool align_K = K % 64 == 0; + kname << "_" << use_out_source << do_axpby << align_M << align_N << align_K; + auto kernel = get_steel_gemm_thin_nax_kernel( + d, + base_name, + kname.str(), + {{&use_out_source, MTL::DataType::DataTypeBool, 100}, + {&do_axpby, MTL::DataType::DataTypeBool, 110}, + {&align_M, MTL::DataType::DataTypeBool, 200}, + {&align_N, MTL::DataType::DataTypeBool, 201}, + {&align_K, MTL::DataType::DataTypeBool, 202}}, + get_template_definition( + base_name, + "gemm_thin_nax", + get_type_string(out.dtype()), + 2, + 2, + 1, + sn, + ks, + transpose_b)); + auto& compute_encoder = metal::get_command_encoder(s); + compute_encoder.set_compute_pipeline_state(kernel); + int tm = (M + 31) / 32, tn = (N + 32 * sn - 1) / (32 * sn); + int k_iters = ((K + 63) / 64 + ks - 1) / ks; + steel::GEMMParams params{ + M, N, K, lda, ldb, N, tn, tm, 0, 0, 0, 0, k_iters, 0}; + compute_encoder.set_input_array(a, 0); + compute_encoder.set_input_array(b, 1); + compute_encoder.set_output_array(out, 3); + compute_encoder.set_bytes(params, 4); + if (use_out_source) { + int ldc = c.strides()[c.ndim() - 2], fdc = c.strides()[c.ndim() - 1]; + steel::GEMMAddMMParams addmm_params{ldc, fdc, 0, alpha, beta}; + compute_encoder.set_input_array(c, 2); + compute_encoder.set_bytes(addmm_params, 5); + } + compute_encoder.dispatch_threadgroups( + MTL::Size(tm * tn, 1, 1), MTL::Size(32 * sn * ks, 1, 1)); + compute_encoder.add_temporaries(std::move(copies)); + return; + } + + // Case 3: Large K with sufficient M, N, and NAX is available, use NAX split-K if (use_nax && batch_size_out == 1 && (K >= 3 * std::max(M, N) || (std::max(M, N) <= 1024 && K > 2 * std::max(M, N)))) { diff --git a/mlx/backend/metal/nojit_kernels.cpp b/mlx/backend/metal/nojit_kernels.cpp index 3795a6fb22..93f8cf311f 100644 --- a/mlx/backend/metal/nojit_kernels.cpp +++ b/mlx/backend/metal/nojit_kernels.cpp @@ -79,6 +79,13 @@ MTL::ComputePipelineState* get_logsumexp_kernel( return d.get_kernel(kernel_name); } +MTL::ComputePipelineState* get_cross_entropy_kernel( + metal::Device& d, + const std::string& kernel_name, + const array&) { + return d.get_kernel(kernel_name); +} + MTL::ComputePipelineState* get_scan_kernel( metal::Device& d, const std::string& kernel_name, @@ -382,6 +389,7 @@ MTL::ComputePipelineState* get_gather_qmm_kernel( int, int, int, + bool, bool) { return d.get_kernel(kernel_name, hash_name, func_consts); } @@ -451,6 +459,15 @@ MTL::ComputePipelineState* get_steel_gemm_segmented_nax_kernel( return d.get_kernel(kernel_name, hash_name, func_consts); } +MTL::ComputePipelineState* get_steel_gemm_thin_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const std::string&) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, @@ -473,6 +490,7 @@ MTL::ComputePipelineState* get_gather_qmm_nax_kernel( int, int, int, + bool, bool) { return d.get_kernel(kernel_name, hash_name, func_consts); } @@ -488,6 +506,7 @@ MTL::ComputePipelineState* get_steel_attention_kernel( int, int, int, + int, const array&) { return d.get_kernel(kernel_name, hash_name, func_consts); } @@ -503,7 +522,54 @@ MTL::ComputePipelineState* get_steel_attention_nax_kernel( int, int, int, + int, + const array&, + bool) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_vjp_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} +MTL::ComputePipelineState* get_gated_delta_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const array&, + int, + int, + int, + int, + int, + int) { + return d.get_kernel(kernel_name, hash_name, func_consts); +} + +MTL::ComputePipelineState* get_gated_delta_vjp_nax_kernel( + metal::Device& d, + const std::string& kernel_name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, const array&, + int, + int, + int, + int, + int, + int, bool) { return d.get_kernel(kernel_name, hash_name, func_consts); } diff --git a/mlx/backend/metal/primitives.cpp b/mlx/backend/metal/primitives.cpp index d1d0e781cc..45929e27dd 100644 --- a/mlx/backend/metal/primitives.cpp +++ b/mlx/backend/metal/primitives.cpp @@ -13,7 +13,6 @@ #include "mlx/backend/metal/kernels.h" #include "mlx/backend/metal/utils.h" #include "mlx/dtype_utils.h" -#include "mlx/fast_primitives.h" #include "mlx/primitives.h" #include "mlx/scheduler.h" #include "mlx/utils.h" @@ -215,26 +214,4 @@ void LUF::eval_gpu( throw std::runtime_error("[LUF::eval_gpu] Metal LU factorization NYI."); } -namespace fast { - -// There is no fused Metal cross entropy kernel yet -bool CrossEntropy::use_fallback(Stream s) { - return true; -} - -void CrossEntropy::eval_gpu( - const std::vector& inputs, - std::vector& outputs) { - throw std::runtime_error("[CrossEntropy::eval_gpu] Metal cross entropy NYI."); -} - -void CrossEntropyVJP::eval_gpu( - const std::vector& inputs, - std::vector& outputs) { - throw std::runtime_error( - "[CrossEntropyVJP::eval_gpu] Metal cross entropy NYI."); -} - -} // namespace fast - } // namespace mlx::core diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index fc5d121225..f43a4ad5b5 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -126,7 +126,7 @@ inline int get_qmv_batch_limit(int D, int O, metal::Device& d) { } else if (D <= 4096 && O <= 4096) { return 10; } else { - return 6; + return (arch_gen == 13 && arch_size == 's') ? 7 : 6; } } } else { @@ -490,7 +490,8 @@ void qmv( std::string kname; kname.reserve(64); std::string type_string = get_type_string(x.dtype()); - bool fast = N % bn == 0 && K % qmv_fast_k_alignment(bits) == 0; + bool fast = (K % qmv_fast_k_alignment(bits) == 0); + bool partial_rows = fast && (N % bn != 0); // A narrower output tile reduces register pressure for large // floating-point quantized matrix-vector products on M5 Max GPUs. bool use_narrow_qmv = fast && N >= 4096 && d.get_architecture_gen() == 17 && @@ -508,9 +509,11 @@ void qmv( group_size, "_b_", bits, - use_narrow_qmv ? "_r_2" : "", B > 1 ? "_batch_1" : "_batch_0", - global_scale ? "_hgs" : ""); + partial_rows ? "_pr_1" : "_pr_0", + global_scale ? "_hgs_1" : "_hgs_0", + "_r_", + results_per_simdgroup); auto kernel = get_quantized_kernel_wrapped( d, kname, @@ -520,6 +523,7 @@ void qmv( group_size, bits, B > 1, + partial_rows, global_scale.has_value(), results_per_simdgroup); @@ -565,9 +569,10 @@ void qmv_wide( const Stream& s, const std::string& mode) { // vecs_per_tg is the per-threadgroup input-vector tile. Each tile re-reads - // the weights, so use the fewest tiles, then the smallest tile that fills - // them. - int n_tiles = (M + 4) / 5; // ceil(M / 5); tile size caps at 5 + // the weights, and the affine kernel keeps every streamed vector in + // registers, so use one tile up to the widest tile that still fits. + int tile_cap = mode == "affine" ? 8 : 5; + int n_tiles = (M + tile_cap - 1) / tile_cap; int vecs_per_tg = (M + n_tiles - 1) / n_tiles; // k_lanes: lanes reducing K per output row (32/k_lanes rows per simdgroup). @@ -633,11 +638,42 @@ void qmv_wide( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } -void qvm_split_k( +inline bool use_qmv_mma( + const array& x, + const array& w, + const array& scales, + QuantizationMode mode, + int M, + int N, + int K, + metal::Device& d) { + if (K % 128 != 0) { + return false; + } + if (mode == QuantizationMode::Affine) { + return false; + } + // Require aligned vector load. + if ((x.offset() % (8 * x.itemsize())) || (w.offset() % 16) || + (scales.offset() % 2)) { + return false; + } + // Route for large K/N. + if (metal::is_nax_available()) { + return (env::enable_tf32() || x.dtype() != float32) && (N >= 2048) && + (K >= 2048) && (N % 32 == 0); + } + if (d.get_architecture().back() == 'd') { + return (N >= 4096) && (K >= 4096) && (N % 16 == 0); + } + return (N >= 512) && (K >= 512) && (int64_t(N) * K >= (int64_t(1) << 22)) && + (N % 16 == 0); +} + +void qmv_mma( const array& x, const array& w, const array& scales, - const std::optional& biases, array& out, int group_size, int bits, @@ -647,11 +683,78 @@ void qvm_split_k( metal::Device& d, const Stream& s, const std::string& mode) { + bool nax = metal::is_nax_available(); + int wk = nax || d.get_architecture_gen() >= 15 ? 8 : 4; + int bn = nax ? 32 : 16; + std::string type_string = get_type_string(x.dtype()); + std::string kname; + kname.reserve(64); + concatenate( + kname, + mode, + nax ? "_qmv_nax_" : "_qmv_mma_", + type_string, + "_gs_", + group_size, + "_b_", + bits, + "_wk", + wk, + "_bn", + bn); + MTL::ComputePipelineState* kernel; + if (nax) { + kernel = get_qmm_nax_kernel_wrapped( + d, kname, "qmv_nax", mode, type_string, group_size, bits, wk, bn); + } else { + int tm = M > 8 ? 2 : 1; + concatenate(kname, "_tm", tm); + kernel = get_quantized_kernel_wrapped( + d, kname, "qmv_mma", mode, type_string, group_size, bits, wk, bn, tm); + } + + auto& compute_encoder = metal::get_command_encoder(s); + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(w, 0); + compute_encoder.set_input_array(scales, 1); + compute_encoder.set_input_array(x, 2); + compute_encoder.set_output_array(out, 3); + compute_encoder.set_bytes(K, 4); + compute_encoder.set_bytes(N, 5); + compute_encoder.set_bytes(M, 6); + compute_encoder.dispatch_threadgroups( + MTL::Size(N / bn, 1, 1), MTL::Size(32, wk, 1)); +} + +void qvm_split_k( + array x, + const array& w, + const array& scales, + const std::optional& biases, + array out, + int group_size, + int bits, + int M, + int N, + int K, + metal::Device& d, + const Stream& s, + const std::string& mode) { auto& compute_encoder = metal::get_command_encoder(s); int split_k = K > 8192 ? 32 : 8; int split_D = (K + split_k - 1) / split_k; int B = out.size() / M / N; + + // When weights are 2D, collapse leading batch dimensions of x and out into M + // so the kernel and reduction operate on standard 2D matrices. + if (B == 1 && x.ndim() != 2) { + x = reshape_in_eval(x, {M, K}, s); + } + if (B == 1 && out.ndim() != 2) { + out = reshape_in_eval(out, {M, N}, s); + } + B *= split_k; constexpr int num_simdgroups = 2; @@ -820,11 +923,21 @@ void qvm( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } +bool use_qmm_t_nax_staged( + const array& x, + bool transpose, + bool aligned_n, + const std::string& mode) { + return transpose && aligned_n && (mode == "affine") && + (x.dtype() == float16 || x.dtype() == bfloat16) && (x.offset() % 8 == 0); +} + void qmm_nax( const array& x, const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, array& out, bool transpose, int group_size, @@ -839,16 +952,24 @@ void qmm_nax( int wm = 2; int wn = 2; - // Use smaller bm when one block covers all of M. - int bm = (M <= 32) ? 32 : 64; + MTL::Size group_dims(32, wn, wm); + // Use smaller bm when one block covers all of M. Only qmm_t_nax has a 32-row + // instantiation. + int bm = (transpose && M <= 32) ? 32 : 64; int bn = 64; int bk = 64; - MTL::Size group_dims(32, wn, wm); - MTL::Size grid_dims((N + bn - 1) / bn, (M + bm - 1) / bm, B); + + bool aligned_n = (N % 64 == 0); + if (use_qmm_t_nax_staged(x, transpose, aligned_n, mode)) { + wm = 4; + wn = 1; + bm = 64; + // A flat threadgroup runs the 16-row schedule faster than (32, 1, wm). + group_dims = MTL::Size(32 * wm, 1, 1); + } std::string kname; kname.reserve(64); - bool aligned = N % 64 == 0; bool batched = B > 1; std::string type_string = get_type_string(x.dtype()); concatenate( @@ -869,8 +990,9 @@ void qmm_nax( wm, "_wn", wn, - transpose ? (aligned ? "_alN_true" : "_alN_false") : "", - batched ? "_batch_1" : "_batch_0"); + transpose ? (aligned_n ? "_alN_true" : "_alN_false") : "", + batched ? "_batch_1" : "_batch_0", + global_scale ? "_hgs" : ""); std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { @@ -882,13 +1004,14 @@ void qmm_nax( type_string, group_size, bits, - aligned, + aligned_n, batched, bm, bk, bn, wm, - wn); + wn, + global_scale.has_value()); } else { kernel = get_qmm_nax_kernel_wrapped( d, @@ -913,6 +1036,11 @@ void qmm_nax( compute_encoder.set_input_array(scales, c++); if (biases) { compute_encoder.set_input_array(*biases, c++); + } else if (transpose) { + if (global_scale) { + compute_encoder.set_input_array(*global_scale, c); + } + c++; } compute_encoder.set_input_array(x, c++); compute_encoder.set_output_array(out, c++); @@ -921,7 +1049,8 @@ void qmm_nax( compute_encoder.set_bytes(M, c++); add_strides_and_shapes(compute_encoder, B <= 1, x, w, scales, biases, c); - compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + compute_encoder.dispatch_threadgroups( + MTL::Size(ceildiv(N, bn), ceildiv(M, bm), B), group_dims); } void gather_qmm_nax( @@ -929,6 +1058,7 @@ void gather_qmm_nax( const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, const array& lhs_indices, const array& rhs_indices, array& out, @@ -975,7 +1105,8 @@ void gather_qmm_nax( wm, "_wn", wn, - transpose ? (aligned ? "_alN_true" : "_alN_false") : ""); + transpose ? (aligned ? "_alN_true" : "_alN_false") : "", + global_scale ? "_hgs" : ""); MTL::ComputePipelineState* kernel; if (transpose) { kernel = get_qmm_nax_kernel_wrapped( @@ -991,7 +1122,8 @@ void gather_qmm_nax( bk, bn, wm, - wn); + wn, + global_scale.has_value()); } else { kernel = get_qmm_nax_kernel_wrapped( d, @@ -1011,12 +1143,14 @@ void gather_qmm_nax( auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); - int c = 0; - compute_encoder.set_input_array(w, c++); - compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(w, 0); + compute_encoder.set_input_array(scales, 1); if (biases) { - compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(*biases, 2); + } else if (global_scale) { + compute_encoder.set_input_array(*global_scale, 2); } + int c = 3; compute_encoder.set_input_array(x, c++); compute_encoder.set_input_array(lhs_indices, c++); compute_encoder.set_input_array(rhs_indices, c++); @@ -1030,11 +1164,22 @@ void gather_qmm_nax( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } +// Must match use_fp4_half_loader in fp_quantized.h. +inline bool use_fp4_half_loader( + const array& x, + const std::string& mode, + const std::optional& global_scale, + int bits) { + return (mode != "affine") && !global_scale && (bits == 4) && + (x.dtype() == float16 || (x.dtype() == bfloat16 && mode == "nvfp4")); +} + void qmm( const array& x, const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, array& out, bool transpose, int group_size, @@ -1045,15 +1190,21 @@ void qmm( metal::Device& d, const Stream& s, const std::string& mode) { + assert( + (!global_scale || (transpose && !biases)) && + "qmm global scale requires transposed weights without biases"); + bool has_nax_kernel = metal::is_nax_available() && (transpose || mode == "affine"); - if (has_nax_kernel && transpose && (K % 64 == 0) && + bool nax_aligned = (K % 64 == 0) && (transpose || N % 64 == 0); + if (has_nax_kernel && nax_aligned && (env::enable_tf32() || x.dtype() != float32)) { return qmm_nax( /* const array& x = */ x, /* const array& w = */ w, /* const array& scales = */ scales, /* const std::optional& biases = */ biases, + /* const std::optional& global_scale = */ global_scale, /* array& out = */ out, /* bool transpose = */ transpose, /* int group_size = */ group_size, @@ -1071,13 +1222,28 @@ void qmm( int wm = 2; int wn = 2; int bm = 32; + int bk = 32; int bn = 32; + + // Tune for larger tile with Fp4HalfLoader. + if (use_fp4_half_loader(x, mode, global_scale, bits) && transpose) { + bool ultra = d.get_architecture().back() == 'd'; + bool pad_free = (ceildiv(M, 32) % 2) == 0; + bool pad_ok = M > ((d.get_architecture_gen() < 15 && !ultra) ? 256 : 2048); + int tgs_64 = ceildiv(N, 64) * ceildiv(M, 64) * B; + int min_tgs_64 = ultra ? 1024 : 160; + if ((pad_free || pad_ok) && (tgs_64 >= min_tgs_64)) { + bm = 64; + bn = 64; + } + } + MTL::Size group_dims(32, wn, wm); - MTL::Size grid_dims((N + bn - 1) / bn, (M + bm - 1) / bm, B); + MTL::Size grid_dims(ceildiv(N, bn), ceildiv(M, bm), B); std::string kname; kname.reserve(64); - bool aligned = N % 32 == 0; + bool aligned = N % bn == 0; bool batched = B > 1; std::string type_string = get_type_string(x.dtype()); concatenate( @@ -1089,7 +1255,9 @@ void qmm( "_b_", bits, transpose ? (aligned ? "_alN_true" : "_alN_false") : "", - batched ? "_batch_1" : "_batch_0"); + batched ? "_batch_1" : "_batch_0", + (bm == 64 && bn == 64) ? "_bm_64_bn_64" : "", + global_scale ? "_hgs" : ""); std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { @@ -1102,7 +1270,11 @@ void qmm( group_size, bits, aligned, - batched); + batched, + global_scale.has_value(), + bm, + bk, + bn); } else { kernel = get_quantized_kernel_wrapped( d, kname, "qmm_n", mode, type_string, group_size, bits, batched); @@ -1115,6 +1287,11 @@ void qmm( compute_encoder.set_input_array(scales, c++); if (biases) { compute_encoder.set_input_array(*biases, c++); + } else if (transpose) { + if (global_scale) { + compute_encoder.set_input_array(*global_scale, c); + } + c++; } compute_encoder.set_input_array(x, c++); compute_encoder.set_output_array(out, c++); @@ -1126,6 +1303,174 @@ void qmm( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } +bool use_qmm_nax_splitk( + const array& x, + const std::optional& biases, + const std::string& mode, + int M, + int N, + int K, + int group_size) { + if (!biases) { + return false; + } + // Use split-k for transposed affine weights with aligned N and K. + if (!metal::is_nax_available() || + (x.dtype() == float32 && !env::enable_tf32() || (mode != "affine") || + (N % 64 != 0) || (K % 64 != 0) || (K % group_size != 0))) { + return false; + } + // A two-way K split must fit within 256 threadgroups. + int bm = (M <= 32) ? 32 : 64; + int tiles = (N / 64) * ceildiv(M, bm); + return (tiles * 2 <= 256) && (K % (2 * std::max(64, group_size)) == 0); +} + +// K partitions for the NAX split-K launch over 64 x 64 output tiles. +int qmm_nax_k_partitions(int M, int N, int K, int group_size) { + int tiles = (N / 64) * ceildiv(M, 64); + int k_align = std::max(64, group_size); + int split_k = 1; + // Double up to 4 while the grid stays within 256 threadgroups and every + // partition keeps at least 256 columns. + while ((split_k < 4) && (tiles * split_k * 2 <= 256) && + (K % (split_k * 2 * k_align) == 0) && (K / (split_k * 2) >= 256)) { + split_k *= 2; + } + return split_k; +} + +void qmm_splitk_nax( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + array& out, + int group_size, + int bits, + int M, + int N, + int K, + metal::Device& d, + const Stream& s, + const std::string& mode) { + // The staged kernel needs an 8-byte aligned activation offset. + auto& compute_encoder = metal::get_command_encoder(s); + if ((x.dtype() != float32) && (x.offset() % 8 != 0)) { + array x_copy = contiguous_copy_gpu(x, s); + compute_encoder.add_temporary(x_copy); + return qmm_splitk_nax( + x_copy, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); + } + + int bm = (M <= 32) ? 32 : 64; + int bn = 64; + int bk = 64; + int wm = 2; + int wn = 2; + MTL::Size group_dims(32, wn, wm); + + if (use_qmm_t_nax_staged(x, true, true, mode)) { + bm = 64; + wm = 4; + wn = 1; + // A flat threadgroup runs the 16-row schedule faster than (32, 1, wm). + group_dims = MTL::Size(32 * wm, 1, 1); + } + + int split_k = qmm_nax_k_partitions(M, N, K, group_size); + if (split_k == 1) { + return qmm_nax( + x, + w, + scales, + biases, + std::nullopt, + out, + true, + group_size, + bits, + M, + N, + K, + d, + s, + mode); + } + + int k_partition_size = K / split_k; + int split_k_partition_stride = M * N; + + array intermediate({split_k, M, N}, float32, nullptr, {}); + intermediate.set_data(allocator::malloc(intermediate.nbytes())); + compute_encoder.add_temporary(intermediate); + + std::string type_string = get_type_string(x.dtype()); + std::string kname; + kname.reserve(64); + concatenate( + kname, + mode + "_qmm_t_nax_splitk_", + type_string, + "_gs_", + group_size, + "_b_", + bits, + "_bm", + bm, + "_bn", + bn, + "_bk", + bk, + "_wm", + wm, + "_wn", + wn, + "_alN_true"); + auto kernel = get_qmm_nax_kernel_wrapped( + d, + kname, + "qmm_t_nax_splitk", + mode, + type_string, + group_size, + bits, + true, + bm, + bk, + bn, + wm, + wn); + compute_encoder.set_compute_pipeline_state(kernel); + + int c = 0; + compute_encoder.set_input_array(w, c++); + compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(x, c++); + compute_encoder.set_output_array(intermediate, c++); + compute_encoder.set_bytes(K, c++); + compute_encoder.set_bytes(N, c++); + compute_encoder.set_bytes(M, c++); + compute_encoder.set_bytes(k_partition_size, c++); + compute_encoder.set_bytes(split_k_partition_stride, c++); + compute_encoder.dispatch_threadgroups( + MTL::Size(N / bn, ceildiv(M, bm), split_k), group_dims); + + // Sum the partitions and cast to the output type. + auto accum_kname = "steel_gemm_splitk_accum_" + type_to_name(out) + "_" + + type_to_name(intermediate); + auto accum_kernel = get_steel_gemm_splitk_accum_kernel( + d, accum_kname, intermediate, out, false); + compute_encoder.set_compute_pipeline_state(accum_kernel); + compute_encoder.set_input_array(intermediate, 0); + compute_encoder.set_output_array(out, 1); + compute_encoder.set_bytes(split_k, 2); + compute_encoder.set_bytes(split_k_partition_stride, 3); + compute_encoder.set_bytes(N, 4); + compute_encoder.dispatch_threads(MTL::Size(N, M, 1), get_block_dims(N, M, 1)); +} + void qmm_splitk( const array& x, const array& w, @@ -1140,6 +1485,12 @@ void qmm_splitk( metal::Device& d, const Stream& s, const std::string& mode) { + // The split-K NAX route. + if (use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size)) { + return qmm_splitk_nax( + x, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); + } + // Choose split_k to target ~512 threadgroups int bm = 32, bn = 32; int n_tiles = (N + bn - 1) / bn; @@ -1160,21 +1511,31 @@ void qmm_splitk( } if (split_k <= 1) { return qmm( - x, w, scales, biases, out, true, group_size, bits, M, N, K, d, s, mode); + x, + w, + scales, + biases, + std::nullopt, + out, + true, + group_size, + bits, + M, + N, + K, + d, + s, + mode); } int k_partition_size = K / split_k; int split_k_partition_stride = M * N; - // Allocate intermediate buffer: insert split_k at the front so that - // partition_stride = M * N matches the leading stride of the buffer. + // Allocate a float32 buffer for the partial sums, so that each partition is + // rounded to the output type only once, after they're summed, as in + // steel_matmul_splitk. auto& compute_encoder = metal::get_command_encoder(s); - auto temp_shape = out.shape(); - if (temp_shape.size() == 1) { - temp_shape.insert(temp_shape.begin(), 1); - } - temp_shape.insert(temp_shape.begin(), split_k); - array intermediate(temp_shape, x.dtype(), nullptr, {}); + array intermediate({split_k, M, N}, float32, nullptr, {}); intermediate.set_data(allocator::malloc(intermediate.nbytes())); compute_encoder.add_temporary(intermediate); @@ -1216,13 +1577,18 @@ void qmm_splitk( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); - // Sum across split_k dimension (axis 0) - ReductionPlan plan( - ReductionOpType::ContiguousStridedReduce, - {intermediate.shape(0)}, - {intermediate.strides(0)}); - strided_reduce_general_dispatch( - intermediate, out, "sum", plan, {0}, compute_encoder, d, s); + // Sum the partitions and cast to the output type + auto accum_kname = "steel_gemm_splitk_accum_" + type_to_name(out) + "_" + + type_to_name(intermediate); + auto accum_kernel = get_steel_gemm_splitk_accum_kernel( + d, accum_kname, intermediate, out, false); + compute_encoder.set_compute_pipeline_state(accum_kernel); + compute_encoder.set_input_array(intermediate, 0); + compute_encoder.set_output_array(out, 1); + compute_encoder.set_bytes(split_k, 2); + compute_encoder.set_bytes(split_k_partition_stride, 3); + compute_encoder.set_bytes(N, 4); + compute_encoder.dispatch_threads(MTL::Size(N, M, 1), get_block_dims(N, M, 1)); } void gather_qmm( @@ -1230,6 +1596,7 @@ void gather_qmm( const array& w, const array& scales, const std::optional& biases, + const std::optional& global_scale, const array& lhs_indices, const array& rhs_indices, array& out, @@ -1249,6 +1616,7 @@ void gather_qmm( /* const array& w = */ w, /* const array& scales = */ scales, /* const std::optional& biases = */ biases, + /* const std::optional& global_scale = */ global_scale, /* const array& lhs_indices = */ lhs_indices, /* const array& rhs_indices = */ rhs_indices, /* array& out = */ out, @@ -1284,25 +1652,43 @@ void gather_qmm( group_size, "_b_", bits, - transpose ? (aligned ? "_alN_true" : "_alN_false") : ""); + transpose ? (aligned ? "_alN_true" : "_alN_false") : "", + global_scale ? "_hgs" : ""); MTL::ComputePipelineState* kernel; if (transpose) { kernel = get_quantized_kernel_wrapped( - d, kname, "gather_qmm_t", mode, type_string, group_size, bits, aligned); + d, + kname, + "gather_qmm_t", + mode, + type_string, + group_size, + bits, + aligned, + global_scale.has_value()); } else { kernel = get_quantized_kernel_wrapped( - d, kname, "gather_qmm_n", mode, type_string, group_size, bits); + d, + kname, + "gather_qmm_n", + mode, + type_string, + group_size, + bits, + global_scale.has_value()); } auto& compute_encoder = metal::get_command_encoder(s); compute_encoder.set_compute_pipeline_state(kernel); - int c = 0; - compute_encoder.set_input_array(w, c++); - compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(w, 0); + compute_encoder.set_input_array(scales, 1); if (biases) { - compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(*biases, 2); + } else if (global_scale) { + compute_encoder.set_input_array(*global_scale, 2); } + int c = 3; compute_encoder.set_input_array(x, c++); compute_encoder.set_input_array(lhs_indices, c++); compute_encoder.set_input_array(rhs_indices, c++); @@ -1475,6 +1861,7 @@ void gather_qmm_rhs_nax( const array& w_, const array& scales_, const std::optional& biases_, + const std::optional& global_scale, const array& indices_, array& out, bool transpose, @@ -1514,6 +1901,10 @@ void gather_qmm_rhs_nax( if (biases_) { biases = ensure_row_contiguous(*biases_, d, s); } + std::optional gs; + if (global_scale) { + gs = ensure_row_contiguous(*global_scale, d, s); + } // Use smaller bm for many experts and few tokens. int E = w.size() / w.shape(-1) / w.shape(-2); @@ -1546,7 +1937,8 @@ void gather_qmm_rhs_nax( "_wm_", wm, "_wn_", - wn); + wn, + global_scale ? "_hgs" : ""); metal::MTLFCList func_consts = { {&align_N, MTL::DataType::DataTypeBool, 201}, @@ -1582,20 +1974,23 @@ void gather_qmm_rhs_nax( bk, wm, wn, - transpose); + transpose, + global_scale.has_value()); compute_encoder.set_compute_pipeline_state(kernel); MTL::Size group_dims(32, wn, wm); MTL::Size grid_dims( (N + bn - 1) / bn, std::min(M, (M + bm - 1) / bm + E - 1), 1); - int c = 0; - compute_encoder.set_input_array(x, c++); - compute_encoder.set_input_array(w, c++); - compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(x, 0); + compute_encoder.set_input_array(w, 1); + compute_encoder.set_input_array(scales, 2); if (biases) { - compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(*biases, 3); + } else if (gs) { + compute_encoder.set_input_array(*gs, 3); } + int c = 4; compute_encoder.set_input_array(offsets, c++); compute_encoder.set_output_array(out, c++); compute_encoder.set_bytes(M, c++); @@ -1722,6 +2117,7 @@ bool gather_qmm_rhs( const array& w_, const array& scales_, const std::optional& biases_, + const std::optional& global_scale, const array& indices_, array& out, bool transpose, @@ -1733,7 +2129,7 @@ bool gather_qmm_rhs( metal::Device& d, const Stream& s, const std::string mode) { - const bool nax_takes_call = metal::is_nax_available() && transpose && + const bool nax_takes_call = metal::is_nax_available() && (env::enable_tf32() || x_.dtype() != float32); if (nax_takes_call) { if (d.gemma4_expert_qmm_diagnostics_armed() && @@ -1749,6 +2145,7 @@ bool gather_qmm_rhs( /* const array& w_ = */ w_, /* const array& scales_ = */ scales_, /* const std::optional& biases_ = */ biases_, + /* const std::optional& global_scale = */ global_scale, /* const array& indices_ = */ indices_, /* array& out = */ out, /* bool transpose = */ transpose, @@ -1791,6 +2188,10 @@ bool gather_qmm_rhs( if (biases_) { biases = ensure_row_contiguous(*biases_, d, s); } + std::optional gs; + if (global_scale) { + gs = ensure_row_contiguous(*global_scale, d, s); + } if (d.gemma4_expert_qmm_requested()) { auto shape_dim = [](const array& value, int axis) { @@ -1912,7 +2313,8 @@ bool gather_qmm_rhs( "_wm_", wm, "_wn_", - wn); + wn, + global_scale ? "_hgs" : ""); metal::MTLFCList func_consts = { {&align_N, MTL::DataType::DataTypeBool, 201}, @@ -1948,20 +2350,23 @@ bool gather_qmm_rhs( bk, wm, wn, - transpose); + transpose, + global_scale.has_value()); compute_encoder.set_compute_pipeline_state(kernel); MTL::Size group_dims(32, wn, wm); MTL::Size grid_dims( (N + bn - 1) / bn, std::min(M, (M + bm - 1) / bm + E - 1), 1); - int c = 0; - compute_encoder.set_input_array(x, c++); - compute_encoder.set_input_array(w, c++); - compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(x, 0); + compute_encoder.set_input_array(w, 1); + compute_encoder.set_input_array(scales, 2); if (biases) { - compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(*biases, 3); + } else if (gs) { + compute_encoder.set_input_array(*gs, 3); } + int c = 4; compute_encoder.set_input_array(offsets, c++); compute_encoder.set_output_array(out, c++); compute_encoder.set_bytes(M, c++); @@ -1989,7 +2394,8 @@ void dispatch_qmv( const Stream& s, const std::string& mode) { // It is a qmv with a small inner dimension so route to qmv_quad kernel - if ((K == 128 || K == 64) && is_power_of_2(bits) && !global_scale) { + if ((K == 128 || (K == 64 && bits >= 2)) && is_power_of_2(bits) && + !global_scale) { qmv_quad(x, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); return; } @@ -2040,6 +2446,23 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { int vector_limit = transpose_ ? get_qmv_batch_limit(K, N, d) : 4; auto mode = quantization_mode_to_string(mode_); + + // For few rows use qmv_mma when N/K is large enough. + if (transpose_ && non_batched && (M >= 6) && (M <= 16) && + use_qmv_mma(x, w, scales, mode_, M, N, K, d)) { + qmv_mma(x, w, scales, out, group_size_, bits_, M, N, K, d, s, mode); + return; + } + + // For mid rows use NAX qmm when output is large enough. + if (transpose_ && non_batched && (M >= 8) && (M < vector_limit) && + (M * N >= 16384) && + use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size_)) { + qmm_splitk_nax( + x, w, scales, biases, out, group_size_, bits_, M, N, K, d, s, mode); + return; + } + // It is a matrix matrix product. if (M >= vector_limit) { // Use split-K qmm for small M with transposed weights (non-batched only) @@ -2053,6 +2476,7 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, + std::nullopt, out, transpose_, group_size_, @@ -2129,9 +2553,13 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { array x = ensure_row_contiguous_matrix(inputs[0], d, s); array w = ensure_row_contiguous_matrix(inputs[1], d, s); array scales = ensure_row_contiguous_matrix(inputs[2], d, s); + // Affine gets biases at index 3, nvfp4 an optional global scale. std::optional biases = std::nullopt; - if (inputs.size() == 6) { + std::optional global_scale = std::nullopt; + if (mode_ == QuantizationMode::Affine) { biases = ensure_row_contiguous_matrix(inputs[3], d, s); + } else if (inputs.size() == 6) { + global_scale = ensure_row_contiguous(inputs[3], d, s); } const array& lhs_indices = inputs[inputs.size() - 2]; const array& rhs_indices = inputs[inputs.size() - 1]; @@ -2162,6 +2590,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, + global_scale, rhs_indices, out, transpose_, @@ -2183,6 +2612,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, + global_scale, lhs_indices, rhs_indices, out, @@ -2204,7 +2634,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, - std::nullopt, + global_scale, lhs_indices, rhs_indices, out, @@ -2224,7 +2654,7 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { w, scales, biases, - std::nullopt, + global_scale, lhs_indices, rhs_indices, out, @@ -2280,6 +2710,26 @@ void QQMatmul::eval_gpu(const std::vector& inputs, array& out) { int K = x.shape(-1); int M = non_batched ? x.size() / K : x.shape(-2); int N = out.shape(-1); + if (has_global_scales && w_quantized && non_batched && + x.dtype() == bfloat16 && K % 32 == 0 && + M >= get_qmv_batch_limit(K, N, d)) { + qmm(x, + w_q, + scales_w, + std::nullopt, + global_scale_w, + out, + true, + group_size_, + bits_, + M, + N, + K, + d, + s, + mode); + return; + } dispatch_qmv( x, w_q, @@ -2341,6 +2791,66 @@ void GatherQQMM::eval_gpu(const std::vector& inputs, array& out) { int K = x.shape(-1); int M = non_batched ? x.size() / K : x.shape(-2); int N = out.shape(-1); + + // temporary, until we add proper scaling for gather qqmm + if (global_scale_w) { + int E = w_q.size() / w_q.shape(-1) / w_q.shape(-2); + array gs_e(Shape{E}, float32, nullptr, {}); + broadcast(*global_scale_w, gs_e); + global_scale_w = ensure_row_contiguous(gs_e, d, s); + } + + int B = out.size() / M / N; + bool use_matrix_kernels = has_global_scales && w_quantized && + x.dtype() == bfloat16 && w_q.ndim() == 3 && + K % (metal::is_nax_available() ? 64 : 32) == 0; + + if (use_matrix_kernels && M == 1 && B >= 16 && right_sorted_) { + int E = w_q.size() / w_q.shape(-1) / w_q.shape(-2); + if (B / E >= 4) { + gather_qmm_rhs( + x, + w_q, + scales_w, + std::nullopt, + global_scale_w, + rhs_indices, + out, + true, + group_size_, + bits_, + x.size() / K, + N, + K, + d, + s, + mode); + return; + } + } + + if (use_matrix_kernels && M >= get_qmv_batch_limit(K, N, d)) { + gather_qmm( + x, + w_q, + scales_w, + std::nullopt, + global_scale_w, + lhs_indices, + rhs_indices, + out, + true, + group_size_, + bits_, + M, + N, + K, + d, + s, + mode); + return; + } + gather_qmv( x, w_q, diff --git a/mlx/backend/metal/reduce.cpp b/mlx/backend/metal/reduce.cpp index ac11ac6359..5d9f6d43c4 100644 --- a/mlx/backend/metal/reduce.cpp +++ b/mlx/backend/metal/reduce.cpp @@ -242,6 +242,27 @@ inline auto output_grid_for_col_reduce( return get_2d_grid_dims(out_shape, out_strides); } +// Metal silently truncates a grid dimension past UINT32_MAX threads, so a +// column reduction too wide for one dispatch is split into several, each +// covering the BN-wide column blocks starting at column_offset. +inline void dispatch_col_reduce( + CommandEncoder& compute_encoder, + int64_t n_columns, + int BN, + int threadgroup_size, + size_t grid_y, + size_t grid_z) { + const int64_t n_blocks = (n_columns + BN - 1) / BN; + const int64_t max_blocks = UINT32_MAX / threadgroup_size; + const MTL::Size group_dims(threadgroup_size, 1, 1); + for (int64_t start = 0; start < n_blocks; start += max_blocks) { + const int64_t blocks = std::min(max_blocks, n_blocks - start); + compute_encoder.set_bytes(start * BN, 11); + compute_encoder.dispatch_threads( + MTL::Size(threadgroup_size * blocks, grid_y, grid_z), group_dims); + } +} + std::pair remap_reduce_types( const array& in, const std::string& op_name) { @@ -275,9 +296,7 @@ std::pair remap_reduce_types( } else if (op_name == "and" || op_name == "or") { // Integers can be tested as whatever type has the same width, since only // their bits matter. Floats cannot: -0.0 compares equal to zero but has a - // bit set, so it has to be tested as a float. complex64 stays on the - // integer path, since testing it as a complex would only look at the real - // part and miss 1j. + // bit set, so it has to be tested as a float. switch (in.dtype()) { case float16: return {float16, bool_}; @@ -285,6 +304,8 @@ std::pair remap_reduce_types( return {bfloat16, bool_}; case float32: return {float32, bool_}; + case complex64: + return {complex64, bool_}; default: break; } @@ -315,11 +336,10 @@ void init_reduce( std::string kname = func_name; concatenate(kname, "_", op_name, type_to_name(out_type)); auto kernel = get_reduce_init_kernel(d, kname, func_name, op_name, out_type); - size_t nthreads = out.size(); - MTL::Size grid_dims = MTL::Size(nthreads, 1, 1); + MTL::Size grid_dims = get_2d_grid_dims(out.shape(), out.strides()); NS::UInteger thread_group_size = kernel->maxTotalThreadsPerThreadgroup(); - if (thread_group_size > nthreads) { - thread_group_size = nthreads; + if (thread_group_size > grid_dims.width) { + thread_group_size = grid_dims.width; } MTL::Size group_dims = MTL::Size(thread_group_size, 1, 1); compute_encoder.set_compute_pipeline_state(kernel); @@ -421,7 +441,7 @@ void row_reduce_small( auto [in_type, out_type] = remap_reduce_types(in, op_name); const std::string func_name = "row_reduce_small"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -518,7 +538,7 @@ void row_reduce_looped( int n = get_kernel_reduce_ndim(args.reduce_ndim); const std::string func_name = "row_reduce_looped"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -602,7 +622,7 @@ void strided_reduce_small( int n = get_kernel_reduce_ndim(args.reduce_ndim); const std::string func_name = "col_reduce_small"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -693,7 +713,7 @@ void strided_reduce_longcolumn( int n = get_kernel_reduce_ndim(args.reduce_ndim); std::string func_name = "col_reduce_longcolumn"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -728,8 +748,7 @@ void strided_reduce_longcolumn( second_args.reduce_strides.push_back(out.size()); second_args.reduce_ndim++; int BN = 32; - grid_dims = MTL::Size(256 * ((out.size() + BN - 1) / BN), 1, 1); - group_dims = MTL::Size(256, 1, 1); + int threadgroup_size = 256; // Set the 2nd kernel func_name = "col_reduce_looped"; @@ -755,7 +774,7 @@ void strided_reduce_longcolumn( compute_encoder.set_input_array(intermediate, 0); compute_encoder.set_output_array(out, 1); second_args.encode(compute_encoder); - compute_encoder.dispatch_threads(grid_dims, group_dims); + dispatch_col_reduce(compute_encoder, out.size(), BN, threadgroup_size, 1, 1); } void strided_reduce_looped( @@ -778,17 +797,12 @@ void strided_reduce_looped( int BN = 32; int BM = 1024 / BN; int threadgroup_size = 8 * 32; - MTL::Size grid_dims( - threadgroup_size * ((args.reduction_stride + BN - 1) / BN), - out_grid_size.width, - out_grid_size.height); - MTL::Size group_dims(threadgroup_size, 1, 1); // Set the kernel int n = get_kernel_reduce_ndim(args.reduce_ndim); std::string func_name = "col_reduce_looped"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -820,7 +834,13 @@ void strided_reduce_looped( compute_encoder.set_input_array(in, 0); compute_encoder.set_output_array(out, 1); args.encode(compute_encoder); - compute_encoder.dispatch_threads(grid_dims, group_dims); + dispatch_col_reduce( + compute_encoder, + args.reduction_stride, + BN, + threadgroup_size, + out_grid_size.width, + out_grid_size.height); } void strided_reduce_2pass( @@ -855,17 +875,12 @@ void strided_reduce_2pass( int BN = 32; int BM = 1024 / BN; int threadgroup_size = 8 * 32; - MTL::Size grid_dims( - threadgroup_size * ((args.reduction_stride + BN - 1) / BN), - out_grid_size.width * outer_blocks, - out_grid_size.height); - MTL::Size group_dims(threadgroup_size, 1, 1); // Set the kernel int n = get_kernel_reduce_ndim(args.reduce_ndim); std::string func_name = "col_reduce_2pass"; std::string kname = func_name; - bool large = in.size() > INT32_MAX; + bool large = in.size() > INT32_MAX || in.data_size() > INT32_MAX; if (large) { kname += "_large"; } @@ -897,15 +912,20 @@ void strided_reduce_2pass( compute_encoder.set_input_array(in, 0); compute_encoder.set_output_array(intermediate, 1); args.encode(compute_encoder); - compute_encoder.set_bytes(out_size, 11); - compute_encoder.dispatch_threads(grid_dims, group_dims); + compute_encoder.set_bytes(out_size, 12); + dispatch_col_reduce( + compute_encoder, + args.reduction_stride, + BN, + threadgroup_size, + out_grid_size.width * outer_blocks, + out_grid_size.height); // Make the 2nd pass arguments and grid_dims ColReduceArgs second_args(intermediate); second_args.reduce_shape.push_back(outer_blocks); second_args.reduce_strides.push_back(out.size()); second_args.reduce_ndim++; - grid_dims = MTL::Size(threadgroup_size * ((out.size() + BN - 1) / BN), 1, 1); // Set the 2nd kernel func_name = "col_reduce_looped"; @@ -931,7 +951,7 @@ void strided_reduce_2pass( compute_encoder.set_input_array(intermediate, 0); compute_encoder.set_output_array(out, 1); second_args.encode(compute_encoder); - compute_encoder.dispatch_threads(grid_dims, group_dims); + dispatch_col_reduce(compute_encoder, out.size(), BN, threadgroup_size, 1, 1); } void strided_reduce_general_dispatch( diff --git a/mlx/backend/metal/resident.cpp b/mlx/backend/metal/resident.cpp index fede178a5a..bb4d7c2500 100644 --- a/mlx/backend/metal/resident.cpp +++ b/mlx/backend/metal/resident.cpp @@ -1,10 +1,12 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #include #include +#include #include #include #include +#include #include "mlx/backend/metal/device.h" #include "mlx/backend/metal/resident.h" @@ -33,21 +35,49 @@ ResidencySets::ResidencySets(MTL::Device* d) { std::lock_guard lk(mtx_); // Set 0 always exists and is the fallback when a later set cannot be // made, so failing to create it is fatal. - NS::Error* error = nullptr; + std::string error; if (!add_set_locked(&error)) { std::ostringstream msg; msg << "[metal::Device] Unable to construct residency set.\n"; - if (error) { - msg << error->localizedDescription()->utf8String() << "\n"; + if (!error.empty()) { + msg << error << "\n"; } throw std::runtime_error(msg.str()); } + if (int interval = + env::get_var("MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS", 0); + interval > 0) { + refresh_thread_ = std::thread([this, interval] { + std::unique_lock lock(mtx_); + while (!refresh_cv_.wait_for( + lock, std::chrono::milliseconds(interval), [this] { + return stop_refresh_; + })) { + auto pool = new_scoped_memory_pool(); + // macOS can drop residency after GPU idle despite a standing request. + for (auto& s : sets_) { + if (s.size != 0) { + s.set->requestResidency(); + } + } + } + }); + } } } -ResidencySets::~ResidencySets() = default; +ResidencySets::~ResidencySets() { + if (refresh_thread_.joinable()) { + { + std::lock_guard lock(mtx_); + stop_refresh_ = true; + } + refresh_cv_.notify_one(); + refresh_thread_.join(); + } +} -bool ResidencySets::add_set_locked(NS::Error** error_out) { +bool ResidencySets::add_set_locked(std::string* error_out) { NS::SharedPtr set; if (__builtin_available(macOS 15, iOS 18, *)) { auto pool = new_scoped_memory_pool(); @@ -58,8 +88,9 @@ bool ResidencySets::add_set_locked(NS::Error** error_out) { // A standing request, so allocations added to this set later are // covered without requesting residency again on every insert. set->requestResidency(); - } else if (error_out) { - *error_out = error; + } else if (error_out && error) { + // The error is autoreleased into this pool, so copy its text out now. + *error_out = error->localizedDescription()->utf8String(); } } if (!set) { diff --git a/mlx/backend/metal/resident.h b/mlx/backend/metal/resident.h index 23960ad134..3339307b6c 100644 --- a/mlx/backend/metal/resident.h +++ b/mlx/backend/metal/resident.h @@ -1,10 +1,13 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #pragma once #include +#include #include #include +#include +#include #include #include @@ -96,7 +99,7 @@ class ResidencySets { // gave us a set; the new set is the last one. add_to_set_locked returns the // set it used. Neither it nor remove_from_set_locked commits, so a bulk // resize costs one commit per set instead of one per allocation. - bool add_set_locked(NS::Error** error = nullptr); + bool add_set_locked(std::string* error = nullptr); uint32_t choose_set_locked(size_t bytes); uint32_t add_to_set_locked(const MTL::Allocation* buf, Placement& at); void remove_from_set_locked(const MTL::Allocation* buf, Placement& at); @@ -118,6 +121,9 @@ class ResidencySets { // taking the lock. std::atomic num_sets_{0}; mutable std::mutex mtx_; + std::condition_variable refresh_cv_; + bool stop_refresh_{false}; + std::thread refresh_thread_; }; } // namespace mlx::core::metal diff --git a/mlx/backend/metal/scaled_dot_product_attention.cpp b/mlx/backend/metal/scaled_dot_product_attention.cpp index c2ee37f29e..86b5b6df67 100644 --- a/mlx/backend/metal/scaled_dot_product_attention.cpp +++ b/mlx/backend/metal/scaled_dot_product_attention.cpp @@ -1,4 +1,5 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-26 Apple Inc. +#include #include #include "mlx/backend/common/compiled.h" @@ -7,6 +8,7 @@ #include "mlx/backend/metal/kernels.h" #include "mlx/backend/metal/kernels/defines.h" #include "mlx/backend/metal/kernels/steel/attn/params.h" +#include "mlx/backend/metal/matmul.h" #include "mlx/backend/metal/utils.h" #include "mlx/fast_primitives.h" #include "mlx/utils.h" @@ -15,6 +17,190 @@ namespace mlx::core::fast { namespace { +bool use_blocked_d512( + const array& q, + const array& k, + const array& v, + bool has_arr_mask, + bool do_causal, + bool has_sinks, + bool output_logsumexp, + Stream s) { + return s.device == Device::gpu && !metal::is_nax_available() && + (q.dtype() == float16 || q.dtype() == bfloat16) && q.shape(-1) == 512 && + v.shape(-1) == 512 && q.shape(2) >= 1024 && q.shape(2) <= k.shape(2) && + do_causal && !has_arr_mask && !has_sinks && !output_logsumexp; +} + +void sdpa_blocked_softmax(const Stream& s, metal::Device& d, array& scores) { + constexpr int looped_limit = 4096; + constexpr int simd_size = 32; + + int axis_size = scores.shape().back(); + int n_rows = scores.size() / axis_size; + std::string kernel_name = + axis_size > looped_limit ? "looped_softmax_" : "block_softmax_"; + if (scores.dtype() != float32) { + kernel_name += "precise_"; + } + kernel_name += type_to_name(scores); + + auto kernel = get_softmax_kernel(d, kernel_name, true, scores); + auto& compute_encoder = metal::get_command_encoder(s); + + size_t threadgroup_size; + if (axis_size <= looped_limit) { + size_t reads = (axis_size + SOFTMAX_N_READS - 1) / SOFTMAX_N_READS; + size_t simds = (reads + simd_size - 1) / simd_size; + threadgroup_size = simd_size * simds; + assert(threadgroup_size <= kernel->maxTotalThreadsPerThreadgroup()); + } else { + threadgroup_size = kernel->maxTotalThreadsPerThreadgroup(); + } + + compute_encoder.set_compute_pipeline_state(kernel); + compute_encoder.set_input_array(scores, 0); + compute_encoder.set_output_array(scores, 1); + compute_encoder.set_bytes(axis_size, 2); + compute_encoder.dispatch_threads( + MTL::Size(n_rows * threadgroup_size, 1, 1), + MTL::Size(threadgroup_size, 1, 1)); +} + +void sdpa_full_self_attention_blocked( + const Stream& s, + metal::Device& d, + const array& q, + const array& k, + const array& v, + float scale, + array& o) { + // This block size balances score-buffer memory and GEMM efficiency. + constexpr int block_rows = 256; + + int B = q.shape(0); + int H = q.shape(1); + int qL = q.shape(2); + int kL = k.shape(2); + int D = q.shape(3); + int kvH = k.shape(1); + int gqa = H / kvH; + + array score_buffer({B, H, block_rows, kL}, q.dtype(), nullptr, {}); + score_buffer.set_data(allocator::malloc(score_buffer.nbytes())); + array q_buffer({B, H, block_rows, D}, q.dtype(), nullptr, {}); + q_buffer.set_data(allocator::malloc(q_buffer.nbytes())); + array out_buffer({B, H, block_rows, D}, o.dtype(), nullptr, {}); + out_buffer.set_data(allocator::malloc(out_buffer.nbytes())); + + auto& compute_encoder = metal::get_command_encoder(s); + auto scale_kernel = + d.get_kernel("sdpa_blocked_scale_copy_" + type_to_name(q)); + auto mask_kernel = + d.get_kernel("sdpa_blocked_causal_mask_" + type_to_name(q)); + Shape batch_shape = {B, kvH}; + Strides k_batch_strides = {k.strides(0), k.strides(1)}; + Strides v_batch_strides = {v.strides(0), v.strides(1)}; + + std::vector copies; + for (int q_offset = 0; q_offset < qL; q_offset += block_rows) { + int rows = std::min(block_rows, qL - q_offset); + // Skip columns that are masked for every row in this query block. + int columns = std::min(kL, kL - qL + q_offset + rows); + + array q_block({B, H, rows, D}, q.dtype(), nullptr, {}); + q_block.copy_shared_buffer( + q_buffer, q_block.strides(), q_block.flags(), q_block.size()); + compute_encoder.set_compute_pipeline_state(scale_kernel); + compute_encoder.set_input_array(q, 0); + compute_encoder.set_output_array(q_block, 1); + compute_encoder.set_bytes(scale, 2); + compute_encoder.set_vector_bytes(q.strides(), 3); + compute_encoder.set_bytes(H, 4); + compute_encoder.set_bytes(rows, 5); + compute_encoder.set_bytes(D, 6); + compute_encoder.set_bytes(q_offset, 7); + auto scale_group_dims = get_block_dims(D, rows, B * H); + compute_encoder.dispatch_threads( + MTL::Size(D, rows, B * H), scale_group_dims); + + array scores({B, H, rows, columns}, q.dtype(), nullptr, {}); + scores.copy_shared_buffer( + score_buffer, scores.strides(), scores.flags(), scores.size()); + + Strides q_batch_strides = {int64_t(H) * rows * D, int64_t(gqa) * rows * D}; + steel_matmul( + /* const Stream& s = */ s, + /* metal::Device& d = */ d, + /* const array& a = */ q_block, + /* const array& b = */ k, + /* array& out = */ scores, + /* int M = */ gqa * rows, + /* int N = */ columns, + /* int K = */ D, + /* int batch_size_out = */ B * kvH, + /* int lda = */ D, + /* int ldb = */ k.strides(2), + /* bool transpose_a = */ false, + /* bool transpose_b = */ true, + /* std::vector& copies = */ copies, + /* Shape batch_shape = */ batch_shape, + /* Strides A_batch_stride = */ q_batch_strides, + /* Strides B_batch_stride = */ k_batch_strides); + + int total_rows = B * H * rows; + compute_encoder.set_compute_pipeline_state(mask_kernel); + compute_encoder.set_output_array(scores, 0); + compute_encoder.set_bytes(rows, 1); + compute_encoder.set_bytes(columns, 2); + auto mask_group_dims = get_block_dims(rows, total_rows, 1); + compute_encoder.dispatch_threads( + MTL::Size(rows, total_rows, 1), mask_group_dims); + + sdpa_blocked_softmax(s, d, scores); + + array out_block({B, H, rows, D}, o.dtype(), nullptr, {}); + out_block.copy_shared_buffer( + out_buffer, out_block.strides(), out_block.flags(), out_block.size()); + + Strides scores_batch_strides = { + int64_t(H) * rows * columns, int64_t(gqa) * rows * columns}; + steel_matmul( + /* const Stream& s = */ s, + /* metal::Device& d = */ d, + /* const array& a = */ scores, + /* const array& b = */ v, + /* array& out = */ out_block, + /* int M = */ gqa * rows, + /* int N = */ D, + /* int K = */ columns, + /* int batch_size_out = */ B * kvH, + /* int lda = */ columns, + /* int ldb = */ v.strides(2), + /* bool transpose_a = */ false, + /* bool transpose_b = */ false, + /* std::vector& copies = */ copies, + /* Shape batch_shape = */ batch_shape, + /* Strides A_batch_stride = */ scores_batch_strides, + /* Strides B_batch_stride = */ v_batch_strides); + copy_gpu_inplace( + /* const array& in = */ out_block, + /* array& out = */ o, + /* const Shape& data_shape = */ out_block.shape(), + /* const Strides& i_strides = */ out_block.strides(), + /* const Strides& o_strides = */ o.strides(), + /* int64_t i_offset = */ 0, + /* int64_t o_offset = */ int64_t(q_offset) * o.strides(2), + /* CopyType ctype = */ CopyType::GeneralGeneral, + /* const Stream& s = */ s); + } + + compute_encoder.add_temporaries(std::move(copies)); + compute_encoder.add_temporary(std::move(score_buffer)); + compute_encoder.add_temporary(std::move(q_buffer)); + compute_encoder.add_temporary(std::move(out_buffer)); +} + void sdpa_full_self_attention_nax( const Stream& s, metal::Device& d, @@ -25,17 +211,18 @@ void sdpa_full_self_attention_nax( array& o, bool do_causal_, const std::optional& mask, - const std::optional& sinks) { + const std::optional& sinks, + array* lse) { using namespace mlx::steel; int bd = q.shape(-1); - int bq = 64; + int bv = v.shape(-1); + int bq = bd == 512 ? 32 : 64; int bk = 32; - bool split_d = bd == 256; - int wm = 4; - int wn = split_d ? 2 : 1; - + bool split_d = (bd == 256 || bd == 512); + int wm = bd == 512 ? 2 : 4; + int wn = split_d ? bd / 128 : 1; int B = q.shape(0); int H = q.shape(1); int D = q.shape(3); @@ -79,13 +266,15 @@ void sdpa_full_self_attention_nax( const bool has_mask = mask.has_value(); const bool do_causal = do_causal_; const bool has_sinks = sinks.has_value(); + const bool save_lse = (lse != nullptr); metal::MTLFCList func_consts = { {&align_Q, MTL::DataType::DataTypeBool, 200}, {&align_K, MTL::DataType::DataTypeBool, 201}, {&has_mask, MTL::DataType::DataTypeBool, 300}, {&do_causal, MTL::DataType::DataTypeBool, 301}, - {&has_sinks, MTL::DataType::DataTypeBool, 302}}; + {&has_sinks, MTL::DataType::DataTypeBool, 302}, + {&save_lse, MTL::DataType::DataTypeBool, 303}}; std::string base_name; concatenate( @@ -98,6 +287,8 @@ void sdpa_full_self_attention_nax( bk, "_bd", bd, + "_bv", + bv, "_wm", wm, "_wn", @@ -118,7 +309,9 @@ void sdpa_full_self_attention_nax( "_do_causal_", (do_causal ? 't' : 'n'), "_has_sinks_", - (has_sinks ? 't' : 'n')); + (has_sinks ? 't' : 'n'), + "_save_lse_", + (save_lse ? 't' : 'n')); auto& compute_encoder = metal::get_command_encoder(s); @@ -131,6 +324,7 @@ void sdpa_full_self_attention_nax( bq, bk, bd, + bv, wm, wn, (has_mask ? *mask : q), @@ -188,6 +382,9 @@ void sdpa_full_self_attention_nax( if (has_sinks) { compute_encoder.set_input_array(*sinks, 7); } + if (save_lse) { + compute_encoder.set_output_array(*lse, 8); + } MTL::Size grid_dims = MTL::Size(NQ, H, B); MTL::Size group_dims = MTL::Size(32, wm, wn); @@ -206,17 +403,14 @@ void sdpa_full_self_attention_metal( array& o, bool do_causal_, const std::optional& mask, - const std::optional& sinks) { - int B = q.shape(0); - int H = q.shape(1); + const std::optional& sinks, + array* lse /* = nullptr */) { int D = q.shape(3); - int gqa_factor = q.shape(1) / k.shape(1); int qL = q.shape(2); int kL = k.shape(2); - if (metal::is_nax_available() && - (D == 64 || D == 96 || D == 128 || D == 256) && + (D == 64 || D == 96 || D == 128 || D == 256 || D == 512) && (env::enable_tf32() || q.dtype() != float32)) { return sdpa_full_self_attention_nax( /* const Stream& s = */ s, @@ -228,30 +422,113 @@ void sdpa_full_self_attention_metal( /* array& o = */ o, /* bool do_causal_ = */ do_causal_, /* const std::optional& mask = */ mask, - /* const std::optional& sinks = */ sinks); + /* const std::optional& sinks = */ sinks, + /* array* lse = */ lse); } - using namespace mlx::steel; + // Pad head dims 72 and 80 to 96 to reach the NAX kernel. The added lanes + // are zero and the caller's scale is retained. Enable by default only for + // long, unmasked half-precision attention, where the attention work can + // amortize the padding and output copy. The override is read per call. + // + // Skipped when the logsumexp is needed + bool pad_default = qL >= 512 && kL >= 512 && !do_causal_ && !mask && !sinks; + if ((D == 72 || D == 80) && lse == nullptr && metal::is_nax_available() && + (q.dtype() == float16 || q.dtype() == bfloat16) && + env::get_var("MLX_SDPA_PAD_HEAD_DIM", pad_default ? 1 : 0) == 1) { + constexpr int pad_to = 96; + auto& enc = metal::get_command_encoder(s); + array zero = array(0, q.dtype()); + + auto pad_head_dim = [&](const array& x) { + Shape padded_shape = x.shape(); + padded_shape.back() = pad_to; + array xp(std::move(padded_shape), x.dtype(), nullptr, {}); + fill_gpu(zero, xp, s); + // Explicit output strides: a [.., D] view over xp would be + // non-contiguous with span > size, so it cannot carry xp's flags. + copy_gpu_inplace( + /* const array& in = */ x, + /* array& out = */ xp, + /* const Shape& data_shape = */ x.shape(), + /* const Strides& i_strides = */ x.strides(), + /* const Strides& o_strides = */ xp.strides(), + /* int64_t i_offset = */ 0, + /* int64_t o_offset = */ 0, + /* CopyType ctype = */ CopyType::GeneralGeneral, + /* const Stream& s = */ s); + enc.add_temporary(xp); + return xp; + }; - int wm = 4; - int wn = 1; + array qp = pad_head_dim(q); + array kp = pad_head_dim(k); + array vp = pad_head_dim(v); + + Shape padded_out = o.shape(); + padded_out.back() = pad_to; + array op(std::move(padded_out), o.dtype(), nullptr, {}); + op.set_data(allocator::malloc(op.nbytes())); + sdpa_full_self_attention_nax( + /* const Stream& s = */ s, + /* metal::Device& d = */ d, + /* const array& q = */ qp, + /* const array& k = */ kp, + /* const array& v = */ vp, + /* const float scale = */ scale, + /* array& o = */ op, + /* bool do_causal_ = */ do_causal_, + /* const std::optional& mask = */ mask, + /* const std::optional& sinks = */ sinks, + /* array* lse = */ nullptr); + + // Slice the padded lanes back out into o's caller-chosen strides. + copy_gpu_inplace( + /* const array& in = */ op, + /* array& out = */ o, + /* const Shape& data_shape = */ o.shape(), + /* const Strides& i_strides = */ op.strides(), + /* const Strides& o_strides = */ o.strides(), + /* int64_t i_offset = */ 0, + /* int64_t o_offset = */ 0, + /* CopyType ctype = */ CopyType::GeneralGeneral, + /* const Stream& s = */ s); + enc.add_temporary(op); + enc.add_temporary(zero); + return; + } + + using namespace mlx::steel; + + int B = q.shape(0); + int H = q.shape(1); + int gqa_factor = q.shape(1) / k.shape(1); + char devc = d.get_architecture().back(); int bd = q.shape(-1); + int bv = v.shape(-1); int bq = 32; - int bk = bd < 128 ? 32 : 16; + int bk = (bd == 256) && (q.dtype() != float32) && (devc == 'd') + ? 32 + : (bd < 128 ? 32 : 16); + + int wm = 4; + int wn = (bd == 256) ? 2 : 1; const bool align_Q = (qL % bq) == 0; const bool align_K = (kL % bk) == 0; const bool has_mask = mask.has_value(); const bool do_causal = do_causal_; const bool has_sinks = sinks.has_value(); + const bool save_lse = (lse != nullptr); metal::MTLFCList func_consts = { {&align_Q, MTL::DataType::DataTypeBool, 200}, {&align_K, MTL::DataType::DataTypeBool, 201}, {&has_mask, MTL::DataType::DataTypeBool, 300}, {&do_causal, MTL::DataType::DataTypeBool, 301}, - {&has_sinks, MTL::DataType::DataTypeBool, 302}}; + {&has_sinks, MTL::DataType::DataTypeBool, 302}, + {&save_lse, MTL::DataType::DataTypeBool, 303}}; std::string base_name; concatenate( @@ -264,6 +541,8 @@ void sdpa_full_self_attention_metal( bk, "_bd", bd, + "_bv", + bv, "_wm", wm, "_wn", @@ -284,7 +563,9 @@ void sdpa_full_self_attention_metal( "_do_causal_", (do_causal ? 't' : 'n'), "_has_sinks_", - (has_sinks ? 't' : 'n')); + (has_sinks ? 't' : 'n'), + "_save_lse_", + (save_lse ? 't' : 'n')); auto& compute_encoder = metal::get_command_encoder(s); @@ -297,6 +578,7 @@ void sdpa_full_self_attention_metal( bq, bk, bd, + bv, wm, wn, (has_mask ? *mask : q)); @@ -353,6 +635,9 @@ void sdpa_full_self_attention_metal( if (has_sinks) { compute_encoder.set_input_array(*sinks, 7); } + if (save_lse) { + compute_encoder.set_output_array(*lse, 8); + } MTL::Size grid_dims = MTL::Size(NQ, H, B); MTL::Size group_dims = MTL::Size(32, wm, wn); @@ -361,7 +646,7 @@ void sdpa_full_self_attention_metal( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } -void sdpa_vector( +bool sdpa_vector( const Stream& s, metal::Device& d, const array& q, @@ -415,6 +700,9 @@ void sdpa_vector( // Get the kernel auto& compute_encoder = metal::get_command_encoder(s); auto kernel = d.get_kernel(kname, hash_name, func_consts); + if (kernel->maxTotalThreadsPerThreadgroup() < group_dims.width) { + return false; + } check_kernel_threadgroup_size(kernel, group_dims, hash_name); compute_encoder.set_compute_pipeline_state(kernel); @@ -449,6 +737,7 @@ void sdpa_vector( // Launch compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + return true; } void sdpa_vector_2pass( @@ -466,10 +755,15 @@ void sdpa_vector_2pass( std::string kname; kname.reserve(64); kname += "sdpa_vector_2pass_fp32partials_1"; - if (!mask && !sinks && q.shape(2) == 1 && q.shape(1) == 8 * k.shape(1) && - q.shape(-1) == v.shape(-1) && (q.shape(-1) == 64 || q.shape(-1) == 128) && - k.shape(2) >= 8192) { - kname += "_gqa"; + int gqa_factor = q.shape(1) / k.shape(1); + bool gqa_dims = + (gqa_factor == 8 && (q.shape(-1) == 64 || q.shape(-1) == 128)) || + ((gqa_factor == 12 || gqa_factor == 16) && q.shape(-1) == 128); + if (!mask && !sinks && q.shape(2) == 1 && + q.shape(1) == gqa_factor * k.shape(1) && q.shape(-1) == v.shape(-1) && + gqa_dims && k.shape(2) >= 8192) { + kname += "_gqa_"; + kname += std::to_string(gqa_factor); } kname += "_"; kname += get_type_string(q.dtype()); @@ -479,7 +773,6 @@ void sdpa_vector_2pass( kname += std::to_string(v.shape(-1)); // Compute the necessary sizes - int gqa_factor = q.shape(1) / k.shape(1); int n_simds = gqa_factor * q.shape(2); char devc = d.get_architecture().back(); @@ -571,6 +864,18 @@ void sdpa_vector_2pass( // Get the kernel auto kernel = d.get_kernel(kname, hash_name, func_consts); + // M1/M2 do not have enough threads per threadgroup for default TK=4 kernel + bool has_tk1_variant = ((q.dtype() == float16 || q.dtype() == bfloat16) && + q.shape(-1) == 256 && v.shape(-1) == 256) || + (q.dtype() == float32 && q.shape(-1) == v.shape(-1) && + (q.shape(-1) == 192 || q.shape(-1) == 256)); + if (has_tk1_variant && + group_dims.width * group_dims.height * group_dims.depth > + kernel->maxTotalThreadsPerThreadgroup()) { + kname += "_tk1"; + hash_name += "_tk1"; + kernel = d.get_kernel(kname, hash_name, func_consts); + } check_kernel_threadgroup_size(kernel, group_dims, hash_name); compute_encoder.set_compute_pipeline_state(kernel); @@ -643,11 +948,12 @@ std::tuple has_fused_kernel( if (s.device != Device::gpu) { return {false, "the fused kernels require a GPU (Metal) stream."}; } - if (output_logsumexp) { + + if (output_logsumexp && has_arr_mask) { return { false, - "the fused forward does not produce the logsumexp required for " - "the fused VJP; use default routing when training."}; + "the backward pass does not support an array mask; only causal masking " + "is implemented."}; } const int value_head_dim = v.shape(-1); @@ -660,15 +966,22 @@ std::tuple has_fused_kernel( std::ostringstream msg; if (query_sequence_length > 8) { - const bool supported_head_dim = query_head_dim == value_head_dim && - (query_head_dim == 64 || query_head_dim == 72 || query_head_dim == 80 || - query_head_dim == 96 || query_head_dim == 128 || - query_head_dim == 192 || query_head_dim == 256); + const bool supports_d512 = metal::is_nax_available() && + (env::enable_tf32() || q.dtype() != float32); + const bool asymmetric = query_head_dim == 96 && value_head_dim == 64; + const bool supported_head_dim = asymmetric || + (query_head_dim == value_head_dim && + (query_head_dim == 64 || query_head_dim == 72 || + query_head_dim == 80 || query_head_dim == 96 || + query_head_dim == 128 || query_head_dim == 192 || + query_head_dim == 256 || (query_head_dim == 512 && supports_d512))); if (!supported_head_dim) { msg << "the full attention kernel supports head dims " - << "{64, 72, 80, 96, 128, 192, 256} with matching query/value head " - << "dims; got query head dim " << query_head_dim - << " and value head dim " << value_head_dim << "."; + << "{64, 72, 80, 96, 128, 192, 256} with matching query/value dims, " + << "or (query, value) head dims (96, 64), " + << "plus head dim 512 on NAX GPUs (float32 also requires TF32); got " + << "query head dim " << query_head_dim << " and value head dim " + << value_head_dim << "."; return {false, msg.str()}; } if (has_mask && !has_arr_mask && @@ -684,13 +997,14 @@ std::tuple has_fused_kernel( (query_head_dim == value_head_dim && (query_head_dim == 64 || query_head_dim == 96 || query_head_dim == 128 || query_head_dim == 192 || - query_head_dim == 256)) || - (query_head_dim == 192 && value_head_dim == 128); + query_head_dim == 256 || query_head_dim == 512)) || + (query_head_dim == 192 && value_head_dim == 128) || + (query_head_dim == 96 && value_head_dim == 64); if (!supported_head_dim) { msg << "the vector attention kernel supports head dims " - << "{64, 96, 128, 192, 256} with matching query/value head dims, " - << "or query head dim 192 with value head dim 128; got query head " - << "dim " << query_head_dim << " and value head dim " + << "{64, 96, 128, 192, 256, 512} with matching query/value head " + << "dims, or (query, value) head dims (96, 64) or (192, 128); got " + << "query head dim " << query_head_dim << " and value head dim " << value_head_dim << "."; return {false, msg.str()}; } @@ -707,10 +1021,375 @@ std::tuple has_fused_kernel( << query_sequence_length << " and GQA factor " << gqa_factor << "."; return {false, msg.str()}; } + // Head dim 512 uses the generic vector kernel, reading K/V is its main + // cost. By default, use it only for one query, GQA factor 8, and no array + // mask. + if (query_head_dim == 512) { + int min_key_sequence_length = env::get_var("MLX_SDPA_D512_MIN_KL", 1024); + bool always = (min_key_sequence_length == 0); + if (!always && query_sequence_length != 1) { + msg << "the vector attention kernel for head dim 512 defaults to " + "single-token queries; got query length " + << query_sequence_length << "."; + return {false, msg.str()}; + } + if (!always && gqa_factor != 8) { + msg << "the vector attention kernel for head dim 512 defaults to " + "GQA factor 8; got GQA factor " + << gqa_factor << "."; + return {false, msg.str()}; + } + if (!always && has_arr_mask) { + msg << "the vector attention kernel for head dim 512 defaults to " + "calls without array masks."; + return {false, msg.str()}; + } + if (key_sequence_length < min_key_sequence_length) { + msg << "the vector attention kernel for head dim 512 requires at " + << "least " << min_key_sequence_length << " keys; got key length " + << key_sequence_length << "."; + return {false, msg.str()}; + } + } } return {true, ""}; } +/////////////////////////////////////////////////////////////////////////////// +// Backward pass +/////////////////////////////////////////////////////////////////////////////// + +struct SDPAVJPTileParams { + int bq; + int bk; + int qL; + int i0; + int j0; + float scale; + int diag_off; + int causal; +}; + +array ensure_row_contiguous(const array& x, metal::Device& d, const Stream& s) { + if (!x.flags().row_contiguous) { + array x_copy = contiguous_copy_gpu(x, s); + metal::get_command_encoder(s).add_temporary(x_copy); + return x_copy; + } else { + return x; + } +} + +array vjp_alloc(Shape shape, Dtype dt, const Stream& s) { + array a(std::move(shape), dt, nullptr, {}); + a.set_data(allocator::malloc(a.nbytes())); + metal::get_command_encoder(s).add_temporary(a); + return a; +} + +// Takes a view of the buffer +array vjp_view(const array& base, Shape shape) { + array v(shape, base.dtype(), nullptr, {}); + Strides st(shape.size()); + int64_t acc = 1; + for (int i = static_cast(shape.size()) - 1; i >= 0; --i) { + st[i] = acc; + acc *= shape[i]; + } + array::Flags f{1, 1, shape.size() <= 1}; + v.copy_shared_buffer(base, st, f, static_cast(acc), 0); + return v; +} + +// A [B, H, len, D] window of a row-contiguous [B, H, T, D] input, starting at +// sequence position t0. +array vjp_row_slice(const array& x, int t0, int len) { + const auto& shp = x.shape(); + int64_t Dx = shp[3]; + int64_t Tx = shp[2]; + Shape ns = {shp[0], shp[1], len, static_cast(Dx)}; + Strides st = {shp[1] * Tx * Dx, Tx * Dx, Dx, 1}; + array v(ns, x.dtype(), nullptr, {}); + array::Flags f{1, len == shp[2], false}; + size_t base = static_cast(x.offset()) / x.itemsize(); + v.copy_shared_buffer( + x, + st, + f, + x.data_size(), + base + static_cast(t0) * static_cast(Dx)); + return v; +} + +// Block sizes for the score tile. The best results are usually for 1024x1024 so +// I set those as default. This probably depends on the hardware so it may need +// to be tuned in the future. +std::pair sdpa_vjp_blocks(int B, int H, int qL, int kL, Dtype ctype) { + constexpr int kDefaultBlock = 1024; + + int blk = env::get_var("MLX_SDPA_VJP_BLOCK", kDefaultBlock); + + int bq = std::min(blk, qL); + int bk = std::min(blk, kL); + if (int e = env::get_var("MLX_SDPA_VJP_BQ", 0); e > 0) { + bq = std::min(e, qL); + } + if (int e = env::get_var("MLX_SDPA_VJP_BK", 0); e > 0) { + bk = std::min(e, kL); + } + return {bq, bk}; +} + +void sdpa_vjp_blocked( + const Stream& s, + metal::Device& d, + const array& q, + const array& k, + const array& v, + const array& odo, + const array& lse, + const array& cot_o, + array& dq, + array& dk, + array& dv, + float scale, + bool causal) { + auto& compute_encoder = metal::get_command_encoder(s); + + const int B = q.shape(0); + const int H = q.shape(1); + const int qL = q.shape(2); + const int D = q.shape(3); + const int Hk = k.shape(1); + const int kL = k.shape(2); + const int Dv = v.shape(3); + const int G = H / Hk; + const int BH = B * H; + const int BHk = B * Hk; + // Under a causal mask the diagonal sits at j == i + (kL - qL), which is + // nonzero whenever the queries are a suffix of the keys. + const int diag_off = kL - qL; + + auto [BQ, BK] = sdpa_vjp_blocks(B, H, qL, kL, q.dtype()); + + Dtype ctype = q.dtype(); + std::string tname = get_type_string(ctype); + + auto ds_kernel = d.get_kernel("sdpa_vjp_ds_" + tname); + auto red_add = d.get_kernel("sdpa_vjp_reduce_add_" + tname); + auto red_set = d.get_kernel("sdpa_vjp_reduce_set_" + tname); + + // Temporary tiles + array s_buf = vjp_alloc({BH, BQ, BK}, ctype, s); + array dp_buf = vjp_alloc({BH, BQ, BK}, ctype, s); + array p_buf = vjp_alloc({BH, BQ, BK}, ctype, s); + + // Output of the gemms + array dq_tile = vjp_alloc({BH, BQ, D}, ctype, s); + array dk_tile = vjp_alloc({BH, BK, D}, ctype, s); + array dv_tile = vjp_alloc({BH, BK, Dv}, ctype, s); + + // Accumulators for the result + array dq_acc = vjp_alloc({B, H, qL, D}, float32, s); + array dk_acc = vjp_alloc({B, Hk, kL, D}, float32, s); + array dv_acc = vjp_alloc({B, Hk, kL, Dv}, float32, s); + + std::vector copies; + + auto run_reduce = [&](const array& src, + array& acc, + array& out, + int rows, + int dim, + int group, + int acc_rows, + int row_off, + int nbh, + bool accum) { + compute_encoder.set_compute_pipeline_state(accum ? red_add : red_set); + compute_encoder.set_input_array(src, 0); + compute_encoder.set_input_array(acc, 1); + compute_encoder.set_output_array(acc, 1); + compute_encoder.set_output_array(out, 2); + compute_encoder.set_bytes(rows, 3); + compute_encoder.set_bytes(dim, 4); + compute_encoder.set_bytes(group, 5); + compute_encoder.set_bytes(acc_rows, 6); + compute_encoder.set_bytes(row_off, 7); + compute_encoder.dispatch_threads( + MTL::Size(dim, rows, nbh), MTL::Size(std::min(dim, 32), 8, 1)); + }; + + const int n_i = (qL + BQ - 1) / BQ; + + const Strides q_bs = { + H * int64_t(qL) * D, G * int64_t(qL) * D, int64_t(qL) * D}; + const Strides o_bs = { + H * int64_t(qL) * Dv, G * int64_t(qL) * Dv, int64_t(qL) * Dv}; + // A zero innermost batch stride broadcasts one kv head over its query group. + const Strides k_bs = {Hk * int64_t(kL) * D, int64_t(kL) * D, 0}; + const Strides v_bs = {Hk * int64_t(kL) * Dv, int64_t(kL) * Dv, 0}; + const Shape bshape = {B, Hk, G}; + + for (int j0 = 0; j0 < kL; j0 += BK) { + const int bk_len = std::min(BK, kL - j0); + + array k_sl = vjp_row_slice(k, j0, bk_len); + array v_sl = vjp_row_slice(v, j0, bk_len); + + bool kv_accum = false; + + for (int ii = 0; ii < n_i; ++ii) { + const int i0 = ii * BQ; + const int bq_len = std::min(BQ, qL - i0); + // Skip tiles that lie entirely above the causal diagonal. + if (causal && j0 > i0 + bq_len - 1 + diag_off) { + continue; + } + + array q_sl = vjp_row_slice(q, i0, bq_len); + array o_sl = vjp_row_slice(cot_o, i0, bq_len); + + array s_v = vjp_view(s_buf, {BH, bq_len, bk_len}); + // S = Q @ K.T + steel_matmul( + s, + d, + q_sl, + k_sl, + s_v, + bq_len, + bk_len, + D, + BH, + D, + D, + false, + true, + copies, + bshape, + q_bs, + k_bs); + + array dp_v = vjp_view(dp_buf, {BH, bq_len, bk_len}); + // dP = dO @ V.T + steel_matmul( + s, + d, + o_sl, + v_sl, + dp_v, + bq_len, + bk_len, + Dv, + BH, + Dv, + Dv, + false, + true, + copies, + bshape, + o_bs, + v_bs); + + array ds_v = vjp_view(s_buf, {BH, bq_len, bk_len}); + array p_v = vjp_view(p_buf, {BH, bq_len, bk_len}); + + SDPAVJPTileParams params{ + bq_len, bk_len, qL, i0, j0, scale, diag_off, causal ? 1 : 0}; + + // P = exp(scale * S - lse), dS = P * (dP - delta) * scale + compute_encoder.set_compute_pipeline_state(ds_kernel); + compute_encoder.set_input_array(s_v, 0); + compute_encoder.set_input_array(dp_v, 1); + compute_encoder.set_input_array(lse, 2); + compute_encoder.set_input_array(odo, 3); + compute_encoder.set_output_array(s_v, 4); + compute_encoder.set_output_array(p_v, 5); + compute_encoder.set_bytes(params, 6); + compute_encoder.dispatch_threads( + MTL::Size(bk_len, bq_len, BH), MTL::Size(32, 8, 1)); + + int64_t ss2 = static_cast(bq_len) * bk_len; + Strides sc_bs = {H * ss2, G * ss2, ss2}; + + array dq_v = vjp_view(dq_tile, {BH, bq_len, D}); + // dQ = dS @ K + steel_matmul( + s, + d, + ds_v, + k_sl, + dq_v, + bq_len, + D, + bk_len, + BH, + bk_len, + D, + false, + false, + copies, + bshape, + sc_bs, + k_bs); + + array dk_v = vjp_view(dk_tile, {BH, bk_len, D}); + // dK = dS.T @ Q + steel_matmul( + s, + d, + ds_v, + q_sl, + dk_v, + bk_len, + D, + bq_len, + BH, + bk_len, + D, + true, + false, + copies, + bshape, + sc_bs, + q_bs); + + array dv_v = vjp_view(dv_tile, {BH, bk_len, Dv}); + // dV = P.T @ dO + steel_matmul( + s, + d, + p_v, + o_sl, + dv_v, + bk_len, + Dv, + bq_len, + BH, + bk_len, + Dv, + true, + false, + copies, + bshape, + sc_bs, + o_bs); + + // dQ[i0] += dQ_tile, dK[j0] += sum_G dK_tile, dV[j0] += sum_G dV_tile + run_reduce(dq_v, dq_acc, dq, bq_len, D, 1, qL, i0, BH, j0 != 0); + run_reduce(dk_v, dk_acc, dk, bk_len, D, G, kL, j0, BHk, kv_accum); + run_reduce(dv_v, dv_acc, dv, bk_len, Dv, G, kL, j0, BHk, kv_accum); + + kv_accum = true; + } + } + + for (auto& c : copies) { + compute_encoder.add_temporary(c); + } +} + } // namespace bool ScaledDotProductAttention::use_fallback( @@ -720,6 +1399,7 @@ bool ScaledDotProductAttention::use_fallback( bool has_mask, bool has_arr_mask, bool do_causal, + bool has_sinks, bool is_training, bool output_logsumexp, bool force_fused, @@ -736,26 +1416,47 @@ bool ScaledDotProductAttention::use_fallback( } return false; } - - if (is_training) { - // It's faster for training on Metal to use the unfused SDPA for both - // forward and backward. - return true; + if (use_blocked_d512( + q, k, v, has_arr_mask, do_causal, has_sinks, output_logsumexp, s)) { + return false; } if (!has_fused) { return true; } + // The logsumexp only comes out of the fused forward + if (output_logsumexp) { + return false; + } + const int query_sequence_length = q.shape(2); const int query_head_dim = q.shape(-1); const int value_head_dim = v.shape(-1); + if (query_head_dim == 512 && query_sequence_length > 8) { + constexpr int64_t min_query_blocks = 1024; + const int64_t query_blocks = int64_t(q.shape(0)) * q.shape(1) * + int64_t(ceildiv(query_sequence_length, 32)); + // The D512 kernel needs this many query blocks to match fallback speed. + const bool eligible = metal::is_nax_available() && + (env::enable_tf32() || q.dtype() != float32) && + query_sequence_length >= 1024 && do_causal && !has_arr_mask && + query_blocks >= min_query_blocks; + return !eligible; + } + // Use headdim-split kernel when NAX is enabled and there are enough query // blocks to fill the machine. if (metal::is_nax_available() && (env::enable_tf32() || q.dtype() != float32) && - query_sequence_length >= 1024 && query_head_dim == 256 && do_causal && - !has_arr_mask) { + query_sequence_length >= 1024 && query_head_dim == 256 && + (do_causal || has_arr_mask)) { + return false; + } + + if (!metal::is_nax_available() && q.dtype() != float32 && do_causal && + query_head_dim == 256 && query_sequence_length >= 2048 && + query_sequence_length == k.shape(2)) { return false; } @@ -783,7 +1484,6 @@ void ScaledDotProductAttention::eval_gpu( auto& o = outputs[0]; std::vector copies; - // Define some copy functions to ensure the layout of the inputs is as // expected. copies.reserve(inputs.size()); @@ -811,6 +1511,12 @@ void ScaledDotProductAttention::eval_gpu( // We are in vector mode ie single query if (q_pre.shape(2) <= 8) { + if (outputs.size() > 1) { + throw std::runtime_error( + "[scaled_dot_product_attention] the vector kernels do not produce a " + "logsumexp; the VJP path requires the full-attention kernel."); + } + auto q_copy_unless = [](const array& arr) { if (arr.flags().row_contiguous) { return true; @@ -821,7 +1527,8 @@ void ScaledDotProductAttention::eval_gpu( // If either the batch or head dimension is a singleton, the other can // be transposed with the sequence dimension auto bidx = shape[0] == 1 ? 1 : 0; - return (strides[3] == 1) && (strides[2] == shape[3] * shape[bidx]) && + return (strides[3] == 1) && + (strides[2] == static_cast(shape[3]) * shape[bidx]) && (strides[bidx] == shape[3]); } return false; @@ -876,8 +1583,8 @@ void ScaledDotProductAttention::eval_gpu( if (((devc == 'd' || devc == 's') && k.shape(2) >= 1024) || (k.shape(1) < q.shape(1) && k.shape(2) >= 4096)) { sdpa_vector_2pass(s, d, q, k, v, o, scale_, do_causal, mask, sinks); - } else { - sdpa_vector(s, d, q, k, v, o, scale_, do_causal, mask, sinks); + } else if (!sdpa_vector(s, d, q, k, v, o, scale_, do_causal, mask, sinks)) { + sdpa_vector_2pass(s, d, q, k, v, o, scale_, do_causal, mask, sinks); } } @@ -909,21 +1616,103 @@ void ScaledDotProductAttention::eval_gpu( ? std::optional{copy_unless(is_matrix_contiguous, inputs[3])} : std::nullopt; - sdpa_full_self_attention_metal( - s, d, q, k, v, scale_, o, do_causal_, mask, sinks); + array* lse = nullptr; + if (outputs.size() > 1) { + outputs[1].set_data(allocator::malloc(outputs[1].nbytes())); + lse = &outputs[1]; + } + + if (use_blocked_d512( + q, + k, + v, + has_arr_mask, + do_causal_, + sinks.has_value(), + lse != nullptr, + s)) { + sdpa_full_self_attention_blocked(s, d, q, k, v, scale_, o); + } else { + sdpa_full_self_attention_metal( + s, d, q, k, v, scale_, o, do_causal_, mask, sinks, lse); + } } metal::get_command_encoder(s).add_temporaries(std::move(copies)); } +// The vjp uses matmuls directly so it should be fine to call it every time as +// it uses a lot less memory. It can be overriden by setting +// MLX_SDPA_VJP_FALLBACK=1 bool ScaledDotProductAttentionVJP::use_fallback(const array& q, Stream s) { - return true; + if (s.device != Device::gpu) { + return true; + } + if (env::get_var("MLX_SDPA_VJP_FALLBACK", 0) != 0) { + return true; + } + auto dt = q.dtype(); + return !(dt == float32 || dt == float16 || dt == bfloat16); } void ScaledDotProductAttentionVJP::eval_gpu( const std::vector& inputs, std::vector& outputs) { - throw std::runtime_error("NYI"); + auto& s = stream(); + auto& d = metal::device(s.device); + + if (has_sinks_) { + throw std::runtime_error( + "[ScaledDotProductAttentionVJP] NYI: attention sinks"); + } + + auto q = ensure_row_contiguous(inputs[0], d, s); + auto k = ensure_row_contiguous(inputs[1], d, s); + auto v = ensure_row_contiguous(inputs[2], d, s); + const int n_in = static_cast(inputs.size()); + auto o = ensure_row_contiguous(inputs[n_in - 3], d, s); + auto lse = ensure_row_contiguous(inputs[n_in - 2], d, s); + auto cot_o = ensure_row_contiguous(inputs[n_in - 1], d, s); + + const int B = q.shape(0); + const int H = q.shape(1); + const int qL = q.shape(2); + const int Dv = v.shape(3); + + auto& dq = outputs[0]; + auto& dk = outputs[1]; + auto& dv = outputs[2]; + + auto& compute_encoder = metal::get_command_encoder(s); + + dq.set_data(allocator::malloc(dq.nbytes())); + dk.set_data(allocator::malloc(dk.nbytes())); + dv.set_data(allocator::malloc(dv.nbytes())); + + array odo({B, H, qL}, float32, nullptr, {}); + odo.set_data(allocator::malloc(odo.nbytes())); + compute_encoder.add_temporary(odo); + + std::string odo_name; + concatenate( + odo_name, + "sdpa_vjp_odo_", + get_type_string(q.dtype()), + "_", + std::to_string(Dv)); + + auto odo_kernel = d.get_kernel(odo_name); + + compute_encoder.set_compute_pipeline_state(odo_kernel); + compute_encoder.set_input_array(o, 0); + compute_encoder.set_input_array(cot_o, 1); + compute_encoder.set_output_array(odo, 2); + compute_encoder.set_bytes(qL, 3); + compute_encoder.dispatch_threads( + MTL::Size(32, qL, B * H), MTL::Size(32, 1, 1)); + + sdpa_vjp_blocked( + s, d, q, k, v, odo, lse, cot_o, dq, dk, dv, scale_, do_causal_); } } // namespace mlx::core::fast diff --git a/mlx/backend/metal/scan.cpp b/mlx/backend/metal/scan.cpp index 18935191ff..7253d3c126 100644 --- a/mlx/backend/metal/scan.cpp +++ b/mlx/backend/metal/scan.cpp @@ -116,6 +116,11 @@ void scan_gpu_inplace( void Scan::eval_gpu(const std::vector& inputs, array& out) { assert(inputs.size() == 1); + if (out.size() == 0) { + out.set_data(allocator::malloc(0)); + return; + } + auto in = inputs[0]; if (in.flags().contiguous && in.strides()[axis_] != 0) { if (in.is_donatable() && in.itemsize() == out.itemsize()) { @@ -128,8 +133,9 @@ void Scan::eval_gpu(const std::vector& inputs, array& out) { in.flags()); } } else { - in = contiguous_copy_gpu(in, stream()); - out.copy_shared_buffer(in); + // Output type can be wider than input + copy_gpu(in, out, CopyType::General, stream()); + in = out; } scan_gpu_inplace( diff --git a/mlx/backend/metal/slicing.cpp b/mlx/backend/metal/slicing.cpp index f6ff41abc8..d5f8ef92f2 100644 --- a/mlx/backend/metal/slicing.cpp +++ b/mlx/backend/metal/slicing.cpp @@ -50,6 +50,13 @@ array compute_dynamic_offset( auto& d = metal::device(s.device); auto& compute_encoder = metal::get_command_encoder(s); + // The kernel reads the indices contiguously + if (!indices.flags().row_contiguous) { + auto copy = contiguous_copy_gpu(indices, s); + compute_encoder.add_temporary(copy); + return compute_dynamic_offset(copy, strides, axes, s); + } + // Kernel to compute offset here. array offset({1}, int64, nullptr, {}); bool donate = indices.is_donatable() && diff --git a/mlx/backend/metal/sort.cpp b/mlx/backend/metal/sort.cpp index 65f144c026..b38d3ac2bd 100644 --- a/mlx/backend/metal/sort.cpp +++ b/mlx/backend/metal/sort.cpp @@ -2,6 +2,7 @@ #include +#include "mlx/backend/common/utils.h" #include "mlx/backend/gpu/copy.h" #include "mlx/backend/metal/device.h" #include "mlx/backend/metal/kernels.h" @@ -39,17 +40,24 @@ void single_block_sort( int in_stride_sorted_axis = in.strides()[axis]; int out_stride_sorted_axis = out.strides()[axis]; - // We can only use the contiguous kernel if the sorted axis - // has the largest or smallest stride. - // We also need the input to be contiguous + // The contiguous kernel walks the rows with a single stride, so the axes + // that are not sorted have to collapse to a single dim. + auto single_dim = + [](const Shape& nc_shape, const Strides& nc_str, int64_t& stride) { + auto [shape, strides] = collapse_contiguous_dims(nc_shape, nc_str); + if (shape.size() > 1) { + return false; + } + if (shape.size() > 0) { + stride = strides[0]; + } + return true; + }; + int64_t in_stride_segment_axis = 0; + int64_t out_stride_segment_axis = 0; bool contiguous = in.flags().contiguous; - auto check_strides = [](array x, int sort_stride) { - int min_stride = *std::min_element(x.strides().begin(), x.strides().end()); - int max_stride = *std::max_element(x.strides().begin(), x.strides().end()); - return sort_stride == min_stride || sort_stride == max_stride; - }; - contiguous &= check_strides(in, in_stride_sorted_axis); - contiguous &= check_strides(out, out_stride_sorted_axis); + contiguous &= single_dim(nc_shape, in_nc_str, in_stride_segment_axis); + contiguous &= single_dim(nc_shape, out_nc_str, out_stride_segment_axis); // Prepare kernel name std::ostringstream kname; @@ -74,22 +82,12 @@ void single_block_sort( compute_encoder.set_bytes(out_stride_sorted_axis, 4); if (contiguous) { - int in_stride_segment_axis = INT32_MAX; - int out_stride_segment_axis = INT32_MAX; - for (int i = 0; i < in_nc_str.size(); i++) { - if (nc_shape[i] == 1) { - continue; - } - if (in_nc_str[i] > INT32_MAX || out_nc_str[i] > INT32_MAX) { - throw std::runtime_error("[Sort::eval_gpu] Stride too large."); - } - in_stride_segment_axis = - std::min(in_stride_segment_axis, static_cast(in_nc_str[i])); - out_stride_segment_axis = - std::min(out_stride_segment_axis, static_cast(out_nc_str[i])); + if (in_stride_segment_axis > INT32_MAX || + out_stride_segment_axis > INT32_MAX) { + throw std::runtime_error("[Sort::eval_gpu] Stride too large."); } - compute_encoder.set_bytes(in_stride_segment_axis, 5); - compute_encoder.set_bytes(out_stride_segment_axis, 6); + compute_encoder.set_bytes(static_cast(in_stride_segment_axis), 5); + compute_encoder.set_bytes(static_cast(out_stride_segment_axis), 6); } else { compute_encoder.set_bytes(nc_dim, 5); if (nc_shape.empty()) { @@ -278,6 +276,10 @@ void gpu_merge_sort( array& out, int axis_, bool argsort) { + if (out.size() == 0) { + return; + } + // Get size info int axis = axis_ < 0 ? axis_ + in.ndim() : axis_; int size_sorted_axis = in.shape(axis); diff --git a/mlx/backend/no_cpu/primitives.cpp b/mlx/backend/no_cpu/primitives.cpp index e522307156..2ad6461185 100644 --- a/mlx/backend/no_cpu/primitives.cpp +++ b/mlx/backend/no_cpu/primitives.cpp @@ -66,6 +66,7 @@ NO_CPU(Expm1) NO_CPU(FFT) NO_CPU(Flatten) NO_CPU(Floor) +NO_CPU(FloorDivide) NO_CPU(Full) NO_CPU(Gather) NO_CPU(GatherAxis) diff --git a/mlx/backend/no_gpu/fence.cpp b/mlx/backend/no_gpu/fence.cpp index 05852c860b..2e027032d9 100644 --- a/mlx/backend/no_gpu/fence.cpp +++ b/mlx/backend/no_gpu/fence.cpp @@ -16,15 +16,18 @@ Fence::Fence(Stream s) { fence_ = std::make_shared(0, s); } -void Fence::wait(Stream s, const array&) { - cast().event.wait(s); +void Fence::wait(Stream s, const array&, uint32_t value) { + auto event = cast().event; + event.set_value(value); + event.wait(s); } -void Fence::update(Stream s, const array&, bool) { +uint32_t Fence::update(Stream s, const array&, bool) { auto& f = cast(); f.count++; f.event.set_value(f.count); f.event.signal(s); + return f.count; } } // namespace mlx::core diff --git a/mlx/backend/no_gpu/primitives.cpp b/mlx/backend/no_gpu/primitives.cpp index f17f12cfaf..e3ee598ea3 100644 --- a/mlx/backend/no_gpu/primitives.cpp +++ b/mlx/backend/no_gpu/primitives.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include "mlx/primitives.h" #include "mlx/distributed/primitives.h" @@ -30,6 +30,7 @@ bool fast::ScaledDotProductAttention::use_fallback( bool has_mask, bool has_arr_mask, bool do_causal, + bool has_sinks, bool is_training, bool output_logsumexp, bool force_fused, @@ -52,6 +53,25 @@ bool fast::ScaledDotProductAttention::supports_bool_mask() { return false; } +bool fast::GatedDeltaUpdate::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + const bool has_mask, + Stream s) { + return true; +} + +bool fast::GatedDeltaUpdateVJP::use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + Stream s) { + return true; +} + NO_GPU(Abs) NO_GPU(Add) NO_GPU(AddMM) @@ -99,6 +119,7 @@ NO_GPU(Expm1) NO_GPU(FFT) NO_GPU(Flatten) NO_GPU(Floor) +NO_GPU(FloorDivide) NO_GPU(Full) NO_GPU(Gather) NO_GPU(GatherAxis) @@ -179,6 +200,8 @@ NO_GPU_MULTI(RMSNormVJP) NO_GPU_USE_FALLBACK(RoPE) NO_GPU_MULTI(ScaledDotProductAttention) NO_GPU_MULTI(ScaledDotProductAttentionVJP) +NO_GPU_MULTI(GatedDeltaUpdate) +NO_GPU_MULTI(GatedDeltaUpdateVJP) NO_GPU_MULTI(ConvertFP8) NO_GPU_MULTI(Quantize) NO_GPU_MULTI(CustomKernel) diff --git a/mlx/compile.cpp b/mlx/compile.cpp index 8a58c890bf..cd2ffdf9e5 100644 --- a/mlx/compile.cpp +++ b/mlx/compile.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -46,17 +47,16 @@ bool is_unary(const Primitive& p) { } bool is_binary(const Primitive& p) { - return ( - typeid(p) == typeid(Add) || typeid(p) == typeid(Divide) || - typeid(p) == typeid(Equal) || typeid(p) == typeid(Greater) || - typeid(p) == typeid(GreaterEqual) || typeid(p) == typeid(Less) || - typeid(p) == typeid(LessEqual) || typeid(p) == typeid(LogicalNot) || - typeid(p) == typeid(LogicalAnd) || typeid(p) == typeid(LogicalOr) || - typeid(p) == typeid(LogAddExp) || typeid(p) == typeid(Maximum) || - typeid(p) == typeid(Minimum) || typeid(p) == typeid(Multiply) || - typeid(p) == typeid(NotEqual) || typeid(p) == typeid(Power) || - typeid(p) == typeid(Subtract) || typeid(p) == typeid(BitwiseBinary) || - typeid(p) == typeid(ArcTan2)); + return typeid(p) == typeid(Add) || typeid(p) == typeid(ArcTan2) || + typeid(p) == typeid(BitwiseBinary) || typeid(p) == typeid(Divide) || + typeid(p) == typeid(Equal) || typeid(p) == typeid(FloorDivide) || + typeid(p) == typeid(Greater) || typeid(p) == typeid(GreaterEqual) || + typeid(p) == typeid(Less) || typeid(p) == typeid(LessEqual) || + typeid(p) == typeid(LogicalNot) || typeid(p) == typeid(LogicalAnd) || + typeid(p) == typeid(LogicalOr) || typeid(p) == typeid(LogAddExp) || + typeid(p) == typeid(Maximum) || typeid(p) == typeid(Minimum) || + typeid(p) == typeid(Multiply) || typeid(p) == typeid(NotEqual) || + typeid(p) == typeid(Power) || typeid(p) == typeid(Subtract); } bool is_ternary(const Primitive& p) { @@ -323,9 +323,9 @@ std::uintptr_t get_function_address(const std::function& fun) { class CompileCache { public: struct CacheEntry { - CacheEntry(Stream stream, bool shapeless) - : stream(stream), shapeless(shapeless) {}; - Stream stream; + CacheEntry(std::optional stream, bool shapeless) + : stream(stream), shapeless(shapeless) {} + std::optional stream; bool shapeless; std::vector inputs; std::vector outputs; @@ -396,7 +396,7 @@ class CompileCache { // Loop over entries and check: // - Default stream and device match the entry's default stream // - Inputs match i.e. shapes and types must be equal. - auto stream = default_stream(default_device()); + auto stream = peek_default_stream(default_device()); for (CacheEntry& entry : entries) { // Check that the default stream and device match if (entry.stream != stream) { @@ -700,11 +700,16 @@ void compile_simplify( return pa.is_equivalent(pb); }; - // Merge scalars + std::unordered_map output_map; + for (auto& o : outputs) { + output_map.insert({o.id(), o}); + } + + // Merge scalars, except outputs std::vector new_tape; for (auto& arr : tape) { // Check if we can merge scalars - if (is_scalar(arr)) { + if (is_scalar(arr) && output_map.find(arr.id()) == output_map.end()) { auto scalar = scalars.find(get_scalar_rep(arr)); if (scalar->second.id() != arr.id()) { merge(scalar->second, arr, parents_map); @@ -718,10 +723,6 @@ void compile_simplify( // Remove no-ops { - std::unordered_map output_map; - for (auto& o : outputs) { - output_map.insert({o.id(), o}); - } for (auto& arr : tape) { if (!arr.has_primitive() || !is_noop(arr.primitive())) { new_tape.push_back(std::move(arr)); @@ -743,11 +744,6 @@ void compile_simplify( tape_order.insert({tape[i].id(), i}); } - std::unordered_set output_set; - for (auto& o : outputs) { - output_set.insert(o.id()); - } - // Multi-pass merge only keeping non-orphaned arrays in the tape for (int pass = 0; pass < passes; ++pass) { for (auto& arr : tape) { @@ -767,7 +763,7 @@ void compile_simplify( auto& src = parents->second[src_idx].first; auto& dst = parents->second[dst_idx].first; if (src.id() != dst.id() && array_equivalent(src, dst) && - output_set.find(src.id()) == output_set.end()) { + output_map.find(src.id()) == output_map.end()) { merge(dst, src, parents_map); mask[src_idx] = true; } @@ -833,7 +829,7 @@ void compile_simplify( } return false; } else { - return output_set.find(a.id()) == output_set.end(); + return output_map.find(a.id()) == output_map.end(); } }; bool discard = maybe_merge_parents(arr); diff --git a/mlx/distributed/distributed.cpp b/mlx/distributed/distributed.cpp index 34be2ec600..d8fca8b160 100644 --- a/mlx/distributed/distributed.cpp +++ b/mlx/distributed/distributed.cpp @@ -148,12 +148,11 @@ get_backends() { } Group register_group(std::shared_ptr group, std::string bk) { - auto& backends = get_backends(); if (group == nullptr) { - group = std::make_shared(); - } else { - backends.insert({"any", group}); + return Group(std::make_shared()); } + auto& backends = get_backends(); + backends.insert({"any", group}); backends.insert({std::move(bk), group}); return Group(group); } diff --git a/mlx/distributed/jaccl/lib/jaccl/jaccl.cpp b/mlx/distributed/jaccl/lib/jaccl/jaccl.cpp index 7715022fcc..17bc350a16 100644 --- a/mlx/distributed/jaccl/lib/jaccl/jaccl.cpp +++ b/mlx/distributed/jaccl/lib/jaccl/jaccl.cpp @@ -180,14 +180,25 @@ bool Config::is_valid() const { (is_valid_mesh() || is_valid_ring()); } -std::vector Config::get_mesh_connectivity() const { +std::vector> Config::get_mesh_connectivity() const { if (!is_valid_mesh()) { throw std::runtime_error("[jaccl] The devices do not form a valid mesh."); } - std::vector devices(size_); - for (int dst = 0; dst < size_; dst++) { - if (dst != rank_) { - devices[dst] = devices_[rank_][dst][0]; + size_t n_wires = devices_[0][1].size(); + for (int src = 0; src < size_; src++) { + for (int dst = 0; dst < size_; dst++) { + if (src != dst) { + n_wires = std::min(n_wires, devices_[src][dst].size()); + } + } + } + std::vector> devices( + n_wires, std::vector(size_)); + for (int w = 0; w < devices.size(); w++) { + for (int dst = 0; dst < size_; dst++) { + if (dst != rank_) { + devices[w][dst] = devices_[rank_][dst][w]; + } } } return devices; diff --git a/mlx/distributed/jaccl/lib/jaccl/jaccl.h b/mlx/distributed/jaccl/lib/jaccl/jaccl.h index 39feb34b47..dc430c336e 100644 --- a/mlx/distributed/jaccl/lib/jaccl/jaccl.h +++ b/mlx/distributed/jaccl/lib/jaccl/jaccl.h @@ -51,7 +51,7 @@ class Config { friend std::shared_ptr init(const Config& cfg, bool strict); private: - std::vector get_mesh_connectivity() const; + std::vector> get_mesh_connectivity() const; std::pair, std::vector> get_ring_connectivity() const; SideChannel get_side_channel() const; diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh.cpp b/mlx/distributed/jaccl/lib/jaccl/mesh.cpp index 5b749f2bd9..fe856faf97 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh.cpp +++ b/mlx/distributed/jaccl/lib/jaccl/mesh.cpp @@ -8,12 +8,13 @@ namespace jaccl { MeshGroup::MeshGroup( int rank, - const std::vector& device_names, + const std::vector>& device_names, SideChannel sc) : rank_(rank), - size_(device_names.size()), + size_(device_names[0].size()), + n_wires_(device_names.size()), side_channel_(std::move(sc)), - connections_(create_connections(device_names)) { + pool_(n_wires_ - 1) { if (size_ > MESH_MAX_PEERS) { std::ostringstream msg; msg << "[jaccl] The JACCL mesh supports up to " << MESH_MAX_PEERS @@ -21,54 +22,69 @@ MeshGroup::MeshGroup( throw std::runtime_error(msg.str()); } + for (auto& names : device_names) { + connections_.push_back(create_connections(names)); + } + // Initialize all the connections and allocate buffers initialize(); // Make sure every node has reached here before continuing side_channel_.barrier(); - // Create the mesh implementation object - mesh_ = MeshImpl(rank_, size_, connections_, buffers_, scatter_buffers_); + // Create the mesh implementation objects + for (int w = 0; w < n_wires_; w++) { + meshes_.emplace_back( + rank_, size_, connections_[w], buffers_[w], scatter_buffers_[w]); + } } void MeshGroup::initialize() { // Create the queue pairs - for (auto& conn : connections_) { - if (conn.ctx == nullptr) { - continue; + for (auto& wire : connections_) { + for (auto& conn : wire) { + if (conn.ctx == nullptr) { + continue; + } + conn.allocate_protection_domain(); + conn.create_completion_queue(MAX_SEND_WR + MAX_RECV_WR); + conn.create_queue_pair(); } - conn.allocate_protection_domain(); - conn.create_completion_queue(MAX_SEND_WR + MAX_RECV_WR); - conn.create_queue_pair(); } allocate_buffers(); // First init all connections - for (int peer = 0; peer < size_; peer++) { - if (peer == rank_) { - continue; + for (auto& wire : connections_) { + for (int peer = 0; peer < size_; peer++) { + if (peer == rank_) { + continue; + } + wire[peer].queue_pair_init(); } - connections_[peer].queue_pair_init(); } // Gather the information to be exchanged, this also serves as a barrier // so that all peers have initialized their connections before attempting // to transition to RTS. std::vector info; - for (auto& conn : connections_) { - info.emplace_back(conn.info()); + for (auto& wire : connections_) { + for (auto& conn : wire) { + info.emplace_back(conn.info()); + } } auto all_infos = side_channel_.all_gather(info); // Transition queue pairs to RTS - for (int peer = 0; peer < size_; peer++) { - if (peer == rank_) { - continue; + for (int w = 0; w < n_wires_; w++) { + for (int peer = 0; peer < size_; peer++) { + if (peer == rank_) { + continue; + } + auto peer_info = all_infos[peer][w * size_ + rank_]; + connections_[w][peer].queue_pair_rtr(peer_info); + connections_[w][peer].queue_pair_rts(); } - auto peer_info = all_infos[peer][rank_]; - connections_[peer].queue_pair_rtr(peer_info); - connections_[peer].queue_pair_rts(); } } @@ -76,54 +92,62 @@ void MeshGroup::allocate_buffers() { // Deregister any buffers and free the memory buffers_.clear(); scatter_buffers_.clear(); + buffers_.resize(n_wires_); + scatter_buffers_.resize(n_wires_); - // Allocate the memory - for (int k = 0; k < BUFFER_SIZES; k++) { - for (int i = 0; i < NUM_BUFFERS; i++) { - // Mesh buffers - for (int j = 0; j < size_; j++) { - buffers_.emplace_back(FRAME_SIZE * (1 << k)); - } - // Scatter buffers (size_ send slots followed by size_ recv slots) - for (int j = 0; j < 2 * size_; j++) { - scatter_buffers_.emplace_back(FRAME_SIZE * (1 << k)); + for (int w = 0; w < n_wires_; w++) { + auto& conns = connections_[w]; + auto& buffers = buffers_[w]; + auto& scatter_buffers = scatter_buffers_[w]; + + // Allocate the memory + for (int k = 0; k < BUFFER_SIZES; k++) { + for (int i = 0; i < NUM_BUFFERS; i++) { + // Mesh buffers + for (int j = 0; j < size_; j++) { + buffers.emplace_back(FRAME_SIZE * (1 << k)); + } + // Scatter buffers (size_ send slots followed by size_ recv slots) + for (int j = 0; j < 2 * size_; j++) { + scatter_buffers.emplace_back(FRAME_SIZE * (1 << k)); + } } } - } - for (int k = 0; k < BUFFER_SIZES; k++) { - for (int i = 0; i < NUM_BUFFERS; i++) { - // Mesh buffers - for (int j = 0; j < size_; j++) { - if (j == rank_) { - // This is our send buffer so register it with all pds so we can - // send it to all connected devices. - for (auto& conn : connections_) { - if (conn.ctx != nullptr) { - buffers_[k * NUM_BUFFERS * size_ + i * size_ + j] - .register_to_protection_domain(conn.protection_domain); + for (int k = 0; k < BUFFER_SIZES; k++) { + for (int i = 0; i < NUM_BUFFERS; i++) { + // Mesh buffers + for (int j = 0; j < size_; j++) { + if (j == rank_) { + // This is our send buffer so register it with all pds so we can + // send it to all connected devices. + for (auto& conn : conns) { + if (conn.ctx != nullptr) { + buffers[k * NUM_BUFFERS * size_ + i * size_ + j] + .register_to_protection_domain(conn.protection_domain); + } } + } else { + // This is the recv buffer from rank j so register it to rank j's + // protection domain. + buffers[k * NUM_BUFFERS * size_ + i * size_ + j] + .register_to_protection_domain(conns[j].protection_domain); } - } else { - // This is the recv buffer from rank j so register it to rank j's - // protection domain. - buffers_[k * NUM_BUFFERS * size_ + i * size_ + j] - .register_to_protection_domain(connections_[j].protection_domain); } - } - // Scatter buffers. Slot p (send to peer p) and slot size_ + p (recv from - // peer p) are both registered to peer p's protection domain. The slots - // for our own rank are unused but kept for uniform indexing. - int scatter_base = k * NUM_BUFFERS * 2 * size_ + i * 2 * size_; - for (int j = 0; j < size_; j++) { - if (j == rank_) { - continue; + // Scatter buffers. Slot p (send to peer p) and slot size_ + p (recv + // from peer p) are both registered to peer p's protection domain. The + // slots for our own rank are unused but kept for uniform indexing. + int scatter_base = k * NUM_BUFFERS * 2 * size_ + i * 2 * size_; + for (int j = 0; j < size_; j++) { + if (j == rank_) { + continue; + } + scatter_buffers[scatter_base + j].register_to_protection_domain( + conns[j].protection_domain); + scatter_buffers[scatter_base + size_ + j] + .register_to_protection_domain(conns[j].protection_domain); } - scatter_buffers_[scatter_base + j].register_to_protection_domain( - connections_[j].protection_domain); - scatter_buffers_[scatter_base + size_ + j] - .register_to_protection_domain(connections_[j].protection_domain); } } } @@ -163,8 +187,11 @@ void MeshGroup::all_min( } void MeshGroup::all_gather(const void* input, void* output, size_t n_bytes) { - mesh_.all_gather( - static_cast(input), static_cast(output), n_bytes); + auto in_ptr = static_cast(input); + auto out_ptr = static_cast(output); + split_wires(n_bytes, n_bytes, [&](int w, int64_t offset, int64_t n) { + meshes_[w].all_gather(in_ptr + offset, out_ptr + offset, n, n_bytes); + }); } void MeshGroup::sum_scatter( @@ -179,11 +206,17 @@ void MeshGroup::sum_scatter( } void MeshGroup::send(const void* input, size_t n_bytes, int dst) { - mesh_.send(static_cast(input), n_bytes, dst); + auto in_ptr = static_cast(input); + split_wires(n_bytes, n_bytes, [&](int w, int64_t offset, int64_t n) { + meshes_[w].send(in_ptr + offset, n, dst); + }); } void MeshGroup::recv(void* output, size_t n_bytes, int src) { - mesh_.recv(static_cast(output), n_bytes, src); + auto out_ptr = static_cast(output); + split_wires(n_bytes, n_bytes, [&](int w, int64_t offset, int64_t n) { + meshes_[w].recv(out_ptr + offset, n, src); + }); } void MeshGroup::barrier() { @@ -191,6 +224,16 @@ void MeshGroup::barrier() { all_sum(&b, &b, sizeof(b), Dtype::UInt8); } +template +void MeshGroup::split_wires(size_t n_bytes, int64_t total, Fn&& fn) { + int n_wires = n_bytes >= MESH_MULTI_WIRE_MIN_BYTES ? n_wires_ : 1; + int64_t per_wire = (total + n_wires - 1) / n_wires; + dispatch_wires(&pool_, n_wires, [&](int w) { + int64_t offset = std::min(total, w * per_wire); + fn(w, offset, std::min(per_wire, total - offset)); + }); +} + template void MeshGroup::all_reduce( const void* input, @@ -200,16 +243,19 @@ void MeshGroup::all_reduce( auto in_ptr = static_cast(input); auto out_ptr = static_cast(output); int64_t count = n_bytes / sizeof(T); - if (size_ > 2 && n_bytes > 32 * 1024) { - // Large messages are bandwidth bound so use the reduce scatter + all gather - // path which moves size_x less data per link than the fully connected - // all_reduce. - mesh_.all_reduce_scatter_gather(in_ptr, out_ptr, count, reduce_op); - } else { - // Small messages are latency bound so use the single phase fully - // connected all_reduce cause it is a bit better. - mesh_.all_reduce(in_ptr, out_ptr, count, reduce_op); - } + split_wires(n_bytes, count, [&](int w, int64_t offset, int64_t n) { + if (size_ > 2 && n * sizeof(T) > 32 * 1024) { + // Large messages are bandwidth bound so use the reduce scatter + all + // gather path which moves size_x less data per link than the fully + // connected all_reduce. + meshes_[w].all_reduce_scatter_gather( + in_ptr + offset, out_ptr + offset, n, reduce_op); + } else { + // Small messages are latency bound so use the single phase fully + // connected all_reduce cause it is a bit better. + meshes_[w].all_reduce(in_ptr + offset, out_ptr + offset, n, reduce_op); + } + }); } template @@ -223,7 +269,10 @@ void MeshGroup::reduce_scatter( auto in_ptr = static_cast(input); auto out_ptr = static_cast(output); int64_t count = n_bytes / sizeof(T); - mesh_.sum_scatter(in_ptr, out_ptr, count, reduce_op); + split_wires(n_bytes, count, [&](int w, int64_t offset, int64_t n) { + meshes_[w].sum_scatter( + in_ptr + offset, out_ptr + offset, n, count, reduce_op); + }); } } // namespace jaccl diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh.h b/mlx/distributed/jaccl/lib/jaccl/mesh.h index 8e5164aee2..aa19fddb8c 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh.h @@ -5,13 +5,14 @@ #include "jaccl/group.h" #include "jaccl/mesh_impl.h" #include "jaccl/rdma.h" +#include "jaccl/threadpool.h" namespace jaccl { /** - * The JACCL communication group for a fully connected mesh. We expect one - * connection per peer and it should be the lowest latency communication group - * for small to medium size messages. + * The JACCL communication group for a fully connected mesh. We expect one or + * more connections per peer and it should be the lowest latency communication + * group for small to medium size messages. * * Like all JACCL groups it uses a side channel to exchange the necessary * information and then configure the connections to be ready for RDMA @@ -21,7 +22,7 @@ class MeshGroup : public Group { public: MeshGroup( int rank, - const std::vector& device_names, + const std::vector>& device_names, SideChannel sc); int rank() override { @@ -66,6 +67,9 @@ class MeshGroup : public Group { size_t n_bytes, ReduceOp reduce_op); + template + void split_wires(size_t n_bytes, int64_t total, Fn&& fn); + /** * Performs the connection initialization. Namely, after this call all * Connection objects should have a queue pair in RTS state and all buffers @@ -80,12 +84,13 @@ class MeshGroup : public Group { int rank_; int size_; + int n_wires_; SideChannel side_channel_; - std::vector connections_; - std::vector buffers_; - std::vector scatter_buffers_; - - MeshImpl mesh_; + std::vector> connections_; + std::vector> buffers_; + std::vector> scatter_buffers_; + ThreadPool pool_; + std::vector meshes_; }; } // namespace jaccl diff --git a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h index 75c540e917..7beed48e64 100644 --- a/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/mesh_impl.h @@ -10,6 +10,7 @@ constexpr int MESH_MAX_PEERS = 8; constexpr int MESH_PIPELINE = 2; constexpr int64_t MAX_BUFFER_SIZE = FRAME_SIZE * (1 << (BUFFER_SIZES - 1)); +constexpr size_t MESH_MULTI_WIRE_MIN_BYTES = 512 * 1024; namespace jaccl { @@ -201,17 +202,21 @@ class MeshImpl { } } - void all_gather(const char* in_ptr, char* out_ptr, int64_t n_bytes) { + void all_gather( + const char* in_ptr, + char* out_ptr, + int64_t n_bytes, + int64_t stride) { // Copy our data to the appropriate place. Skip when in place (the scatter // gather all reduce passes our own reduced shard which already lives at - // out_ptr + rank_ * n_bytes). - if (in_ptr != out_ptr + rank_ * n_bytes) { - std::memcpy(out_ptr + rank_ * n_bytes, in_ptr, n_bytes); + // out_ptr + rank_ * stride). + char* data = out_ptr; + char* our_data = out_ptr + rank_ * stride; + if (in_ptr != our_data) { + std::memcpy(our_data, in_ptr, n_bytes); } // Fully connected all gather - char* data = out_ptr; - char* our_data = out_ptr + rank_ * n_bytes; auto [sz, N] = buffer_size_from_message(n_bytes); constexpr int PIPELINE = 2; constexpr int WC_NUM = PIPELINE * MESH_MAX_PEERS * 2; @@ -274,7 +279,7 @@ class MeshImpl { recv_buffer(sz, buff, rank).begin(), recv_buffer(sz, buff, rank).begin() + std::min(N, total - write_offset[rank]), - data + rank * n_bytes + write_offset[rank]); + data + rank * stride + write_offset[rank]); write_offset[rank] += N; if (write_offset[rank] + N * (PIPELINE - 1) < total) { recv_from(sz, rank, buff); @@ -286,20 +291,26 @@ class MeshImpl { } template - void sum_scatter(const T* in, T* out, int64_t count, ReduceOp reduce_op) { + void sum_scatter( + const T* in, + T* out, + int64_t count, + int64_t stride, + ReduceOp reduce_op) { // Fully connected reduce scatter. // - // The input holds size_ contiguous chunks of `count` elements each. Every - // rank keeps chunk rank_ and needs the elementwise reduction of that chunk - // across all ranks. To that end each rank p sends its chunk j to rank j and - // receives every peer's chunk rank_. The output is seeded with this rank's - // own chunk rank_ and every received chunk is reduced into it. + // The input holds size_ chunks of `count` elements each, `stride` elements + // apart. Every rank keeps chunk rank_ and needs the elementwise reduction + // of that chunk across all ranks. To that end each rank p sends its chunk j + // to rank j and receives every peer's chunk rank_. The output is seeded + // with this rank's own chunk rank_ and every received chunk is reduced + // into it. // // Unlike all_reduce/all_gather each peer receives a *different* chunk, so // we use the dedicated scatter buffers: per (sz, buff) tile there are size_ // send slots (slot p -> peer p) and size_ recv slots (slot p <- peer p). - const T* our_chunk = in + static_cast(rank_) * count; + const T* our_chunk = in + static_cast(rank_) * stride; auto [sz, buffer_size] = buffer_size_from_message(count * sizeof(T)); int64_t N = buffer_size / sizeof(T); @@ -328,7 +339,7 @@ class MeshImpl { if (p == rank_) { continue; } - const T* src = in + static_cast(p) * count + read_offset; + const T* src = in + static_cast(p) * stride + read_offset; std::copy( src, src + elems, scatter_send_buffer(sz, buff, p).begin()); } @@ -362,7 +373,8 @@ class MeshImpl { if (p == rank_) { continue; } - const T* src = in + static_cast(p) * count + read_offset; + const T* src = + in + static_cast(p) * stride + read_offset; std::copy( src, src + elems, @@ -424,7 +436,7 @@ class MeshImpl { // output. sum_scatter only reads `in` and writes out + rank_ * chunk so // this is safe even when in aliases out. T* shard = out + static_cast(rank_) * chunk; - sum_scatter(in, shard, chunk, reduce_op); + sum_scatter(in, shard, chunk, chunk, reduce_op); // All gather every rank's reduced chunk into the output. Our own shard is // already in place so all_gather skips the self copy and only fills the @@ -432,6 +444,7 @@ class MeshImpl { all_gather( reinterpret_cast(shard), reinterpret_cast(out), + chunk * sizeof(T), chunk * sizeof(T)); } diff --git a/mlx/distributed/jaccl/lib/jaccl/ring.cpp b/mlx/distributed/jaccl/lib/jaccl/ring.cpp index a08035f3f3..ae25d80904 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring.cpp +++ b/mlx/distributed/jaccl/lib/jaccl/ring.cpp @@ -218,7 +218,7 @@ void RingGroup::all_reduce( auto out_ptr = static_cast(output); int64_t count = n_bytes / sizeof(T); - if (n_bytes <= 32768 || count < size_ * 2 * n_conns_) { + if (n_bytes <= 32768 || count < static_cast(size_) * 2 * n_conns_) { ring_.all_reduce<1, T, ReduceOp>(in_ptr, out_ptr, count, 1, reduce_op); return; } @@ -246,7 +246,7 @@ void RingGroup::reduce_scatter( // Mirror the all_reduce heuristics: use a single wire for small messages and // scale up to n_conns_ wires for large ones where bandwidth dominates. - if (total < size_ * 2 * n_conns_ || n_bytes <= 65536) { + if (total < static_cast(size_) * 2 * n_conns_ || n_bytes <= 65536) { ring_.reduce_scatter(in_ptr, out_ptr, total, 1, reduce_op); return; } diff --git a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h index 15b81a2177..5863de4006 100644 --- a/mlx/distributed/jaccl/lib/jaccl/ring_impl.h +++ b/mlx/distributed/jaccl/lib/jaccl/ring_impl.h @@ -2,7 +2,6 @@ #pragma once -#include #include #include "jaccl/rdma.h" @@ -90,7 +89,7 @@ class RingImpl { // Split the reduce scatter + all gather across the available wires. Each // wire handles a contiguous slice of each chunk in every direction. - dispatch_wires(n_wires, [&](int lw) { + dispatch_wires(pool_, n_wires, [&](int lw) { all_reduce_wire( in_ptr, out_ptr, @@ -129,10 +128,10 @@ class RingImpl { int64_t send_offset[MAX_DIR]; int64_t recv_offset[MAX_DIR]; for (int lr = 0; lr < MAX_DIR; lr++) { - wire_offset[lr] = lr * n_wires * size_per_wire + + wire_offset[lr] = static_cast(lr) * n_wires * size_per_wire + static_cast(lw) * size_per_wire; - int64_t region_end = - std::min(chunk_size, (lr + 1) * n_wires * size_per_wire); + int64_t region_end = std::min( + chunk_size, static_cast(lr + 1) * n_wires * size_per_wire); wire_end[lr] = std::min(region_end, wire_offset[lr] + size_per_wire); send_offset[lr] = rank_ * chunk_size; } @@ -196,9 +195,13 @@ class RingImpl { // Split the all gather across the available wires. Each wire handles a // contiguous slice of every rank's data in both directions. size_t n_bytes_per_wire = (n_bytes + (2 * n_wires) - 1) / (2 * n_wires); - dispatch_wires(n_wires, [&](int lw) { + dispatch_wires(pool_, n_wires, [&](int lw) { all_gather_wire( - out_ptr, n_bytes, static_cast(n_bytes_per_wire), lw); + out_ptr, + n_bytes, + static_cast(n_bytes_per_wire), + n_wires, + lw); }); } @@ -215,14 +218,21 @@ class RingImpl { char* out_ptr, int64_t n_bytes, int64_t n_bytes_per_wire, + int n_wires, int lw) { - // Both directions send the same contiguous slice of each rank's region. - int64_t slice = static_cast(lw) * n_bytes_per_wire; - int64_t wire_offset[2] = {slice, slice}; - // Clamp to this wire's slice end so the last frame can't spill into the - // next wire's slice. - int64_t wire_end_bytes = std::min(n_bytes, slice + n_bytes_per_wire); - int64_t wire_end[2] = {wire_end_bytes, wire_end_bytes}; + // Each rank's region is divided into 2 directional halves, each split + // into n_wires contiguous slices - mirroring all_reduce_wire. Without + // the lr term both directions cover the same lower-half slice and the + // upper half of every peer's region is never transferred. + int64_t wire_offset[2]; + int64_t wire_end[2]; + for (int lr = 0; lr < 2; lr++) { + wire_offset[lr] = static_cast(lr) * n_wires * n_bytes_per_wire + + static_cast(lw) * n_bytes_per_wire; + int64_t region_end = std::min( + n_bytes, static_cast(lr + 1) * n_wires * n_bytes_per_wire); + wire_end[lr] = std::min(region_end, wire_offset[lr] + n_bytes_per_wire); + } int64_t send_offset[2] = {rank_ * n_bytes, rank_ * n_bytes}; int64_t recv_offset[2] = { ((rank_ + size_ - 1) % size_) * n_bytes, @@ -230,7 +240,7 @@ class RingImpl { ring_pass<2, char>( lw, - n_bytes, + n_bytes * size_, n_bytes, n_bytes * size_, n_bytes_per_wire, @@ -262,7 +272,7 @@ class RingImpl { // Two directional regions, each split across the wires. int64_t size_per_wire = (chunk + (2 * n_wires) - 1) / (2 * n_wires); - dispatch_wires(n_wires, [&](int lw) { + dispatch_wires(pool_, n_wires, [&](int lw) { reduce_scatter_wire( in_ptr, out_ptr, chunk, size_per_wire, n_wires, lw, reduce_op); }); @@ -307,9 +317,10 @@ class RingImpl { int64_t wire_offset[MAX_DIR]; int64_t wire_end[MAX_DIR]; for (int lr = 0; lr < MAX_DIR; lr++) { - wire_offset[lr] = lr * n_wires * size_per_wire + + wire_offset[lr] = static_cast(lr) * n_wires * size_per_wire + static_cast(lw) * size_per_wire; - int64_t region_end = std::min(chunk, (lr + 1) * n_wires * size_per_wire); + int64_t region_end = std::min( + chunk, static_cast(lr + 1) * n_wires * size_per_wire); wire_end[lr] = std::min(region_end, wire_offset[lr] + size_per_wire); } @@ -584,7 +595,7 @@ class RingImpl { // Split the send across the available wires. Each wire handles the // contiguous slice [lw * bytes_per_wire, (lw + 1) * bytes_per_wire). - dispatch_wires(n_wires, [&](int lw) { + dispatch_wires(pool_, n_wires, [&](int lw) { send_wire(in_ptr, n_bytes, dir, bytes_per_wire, lw); }); } @@ -663,7 +674,7 @@ class RingImpl { // Split the recv across the available wires. Each wire handles the // contiguous slice [lw * bytes_per_wire, (lw + 1) * bytes_per_wire). - dispatch_wires(n_wires, [&](int lw) { + dispatch_wires(pool_, n_wires, [&](int lw) { recv_wire(out_ptr, n_bytes, dir, bytes_per_wire, lw); }); } @@ -769,38 +780,6 @@ class RingImpl { work_completions); } - // Run fn(lw) for each wire, the first n_wires - 1 on the pool and the last - // inline, then wait for the pool calls before returning. - template - void dispatch_wires(int n_wires, Fn&& fn) { - if (n_wires <= 1 || pool_ == nullptr) { - for (int lw = 0; lw < n_wires; lw++) { - fn(lw); - } - return; - } - - std::vector> futures; - futures.reserve(n_wires - 1); - for (int lw = 0; lw < n_wires - 1; lw++) { - futures.emplace_back(pool_->enqueue(fn, lw)); - } - - // Wait for the pool calls even if the inline one throws, so they never - // outlive this frame. - try { - fn(n_wires - 1); - } catch (...) { - for (auto& f : futures) { - f.wait(); - } - throw; - } - for (auto& f : futures) { - f.wait(); - } - } - int rank_; int size_; int n_conns_; diff --git a/mlx/distributed/jaccl/lib/jaccl/threadpool.h b/mlx/distributed/jaccl/lib/jaccl/threadpool.h index b5d05153e2..6e96152cb5 100644 --- a/mlx/distributed/jaccl/lib/jaccl/threadpool.h +++ b/mlx/distributed/jaccl/lib/jaccl/threadpool.h @@ -134,4 +134,36 @@ inline void ThreadPool::start_threads(size_t threads) { } } +// Run fn(lw) for each wire, the first n_wires - 1 on the pool and the last +// inline, then wait for the pool calls before returning. +template +void dispatch_wires(ThreadPool* pool, int n_wires, Fn&& fn) { + if (n_wires <= 1 || pool == nullptr) { + for (int lw = 0; lw < n_wires; lw++) { + fn(lw); + } + return; + } + + std::vector> futures; + futures.reserve(n_wires - 1); + for (int lw = 0; lw < n_wires - 1; lw++) { + futures.emplace_back(pool->enqueue(fn, lw)); + } + + // Wait for the pool calls even if the inline one throws, so they never + // outlive this frame. + try { + fn(n_wires - 1); + } catch (...) { + for (auto& f : futures) { + f.wait(); + } + throw; + } + for (auto& f : futures) { + f.wait(); + } +} + } // namespace jaccl diff --git a/mlx/distributed/ring/ring.cpp b/mlx/distributed/ring/ring.cpp index 9a81010e34..0726478ebf 100644 --- a/mlx/distributed/ring/ring.cpp +++ b/mlx/distributed/ring/ring.cpp @@ -80,7 +80,10 @@ class SocketThread { fcntl(fd, F_SETFL, flags | O_NONBLOCK); } ~SocketThread() { - stop_ = true; + { + std::unique_lock lock(queue_mutex_); + stop_ = true; + } condition_.notify_all(); worker_.join(); int flags = fcntl(fd_, F_GETFL, 0); @@ -151,6 +154,8 @@ class SocketThread { bool delete_recv = false; bool delete_send = false; while (true) { + SocketTask* recv_task = nullptr; + SocketTask* send_task = nullptr; { std::unique_lock lock(queue_mutex_); @@ -175,10 +180,17 @@ class SocketThread { return; } } + + if (!recvs_.empty()) { + recv_task = &recvs_.front(); + } + if (!sends_.empty()) { + send_task = &sends_.front(); + } } - if (!recvs_.empty()) { - auto& task = recvs_.front(); + if (recv_task) { + auto& task = *recv_task; ssize_t r = ::recv(fd_, task.buffer, std::min(task.size, MAX_IO_BYTES), 0); if (r > 0) { @@ -195,8 +207,8 @@ class SocketThread { true, "Receiving from socket", fd_, "failed with errno", errno); } } - if (!sends_.empty()) { - auto& task = sends_.front(); + if (send_task) { + auto& task = *send_task; ssize_t r = ::send(fd_, task.buffer, std::min(task.size, MAX_IO_BYTES), 0); if (r > 0) { @@ -218,6 +230,7 @@ class SocketThread { // Throw exception in invoker's thread. auto error = std::make_exception_ptr( std::runtime_error("[ring] connection to a peer was lost")); + std::unique_lock lock(queue_mutex_); for (auto& task : recvs_) { task.promise.set_exception(error); } diff --git a/mlx/export.cpp b/mlx/export.cpp index 06ff99a7b5..f4fc08b1b8 100644 --- a/mlx/export.cpp +++ b/mlx/export.cpp @@ -384,6 +384,7 @@ struct PrimitiveFactory { SERIALIZE_PRIMITIVE(FFT), SERIALIZE_PRIMITIVE(Flatten), SERIALIZE_PRIMITIVE(Floor), + SERIALIZE_PRIMITIVE(FloorDivide), SERIALIZE_PRIMITIVE(Full), SERIALIZE_PRIMITIVE(Gather), SERIALIZE_PRIMITIVE(GatherAxis), @@ -703,6 +704,7 @@ FunctionExporter::FunctionExporter( fun(std::move(fun)), ftable(std::make_shared(shapeless)), metadata_(std::move(metadata)) { + os.open(); if (!os.is_open()) { throw std::runtime_error("[export_function] Failed to open " + file); } diff --git a/mlx/fast.cpp b/mlx/fast.cpp index f45724dc92..2afb834166 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -1,4 +1,4 @@ -// Copyright © 2023-2024 Apple Inc. +// Copyright © 2023-2026 Apple Inc. #include #include @@ -352,7 +352,7 @@ array layer_norm( auto xc = subtract(x, mu, s); auto v = mean(square(xc, s), /* axis= */ -1, /* keepdims= */ true, s); - x = multiply(xc, rsqrt(add(v, array(eps, float32), s), s)); + x = multiply(xc, rsqrt(add(v, array(eps, float32), s), s), s); x = astype(x, out_type, s); // If the LN is affine then transform x according to the weight and bias @@ -934,6 +934,7 @@ array scaled_dot_product_attention( has_mask, has_arr_mask, do_causal, + has_sinks, is_training, output_logsumexp, force_fused, @@ -944,8 +945,9 @@ array scaled_dot_product_attention( array& mask = inputs[3]; mask = where( mask, - full_like(mask, 0, final_type, s), - full_like(mask, -inf, final_type, s)); + full_like(mask, 0, final_type, stream), + full_like(mask, -inf, final_type, stream), + stream); } Shape out_shape{q.shape(0), q.shape(1), q.shape(2), v.shape(-1)}; auto primitive = std::make_shared( @@ -977,13 +979,16 @@ std::vector ScaledDotProductAttention::vjp( const std::vector& outputs) { assert(primals.size() >= 3); assert(cotangents.size() == outputs.size()); - auto s = stream(); if (ScaledDotProductAttentionVJP::use_fallback(primals[0], s)) { assert(outputs.size() == 1); return Custom::vjp(primals, cotangents, argnums, outputs); } + if (outputs.size() != 2) { + return Custom::vjp(primals, cotangents, argnums, outputs); + } + auto fallback = [sdpa = fallback_, s](const std::vector& inputs) { std::vector primals(inputs.begin(), std::prev(inputs.end())); auto [_, vjps] = mlx::core::vjp(sdpa, primals, {inputs.back()}); @@ -1032,6 +1037,181 @@ bool ScaledDotProductAttentionVJP::is_equivalent(const Primitive& other) const { has_sinks_ == a_other.has_sinks_; } +std::vector gated_delta_update( + const array& queries, + const array& keys, + const array& values, + const array& gates, + const array& beta_, + const std::optional& initial_state, /* = std::nullopt */ + const std::optional& mask_, /* = std::nullopt */ + StreamOrDevice s_ /* = {} */) { + // determine output dtype + auto s = to_stream(s_); + + auto promoted = promote_types(queries.dtype(), keys.dtype()); + auto out_dtype = issubdtype(promoted, floating) + ? promoted + : promote_types(promoted, float32); + + // cast all inputs + auto q = astype(queries, out_dtype, s); + auto k = astype(keys, out_dtype, s); + auto v = astype(values, out_dtype, s); + auto g = astype(gates, out_dtype, s); + auto beta = astype(beta_, out_dtype, s); + + int B = q.shape(0); + int T = q.shape(1); + int Hk = q.shape(2); + int Dk = q.shape(3); + int Hv = v.shape(2); + int Dv = v.shape(3); + + auto h0 = initial_state.has_value() ? astype(*initial_state, float32, s) + : zeros({B, Hv, Dv, Dk}, float32, s); + + bool has_mask = mask_.has_value(); + auto mask = has_mask ? astype(*mask_, bool_, s) : array(false); + + auto fallback = [B, T, Hk, Dk, Hv, Dv, has_mask, s]( + std::vector inputs) { + auto out_dtype = inputs[0].dtype(); + auto q = inputs[0]; + auto k = inputs[1]; + auto v = inputs[2]; + auto g = inputs[3]; + auto beta = inputs[4]; + auto state = astype(inputs[5], float32, s); + + if (Hv != Hk) { + int repeat_factor = Hv / Hk; + q = repeat(q, repeat_factor, 2, s); + k = repeat(k, repeat_factor, 2, s); + } + + array mask = has_mask ? astype(inputs[6], bool_, s) : array(false); + const array zero = array(0.0f, float32); + + std::vector outputs; + for (int t = 0; t < T; t++) { + auto get_t = [&](const array& a, int t) { + Shape start(a.ndim(), 0), stop = a.shape(); + start[1] = t; + stop[1] = t + 1; + return squeeze(slice(a, start, stop, s), 1, s); + }; + auto q_t = get_t(q, t); + auto k_t = get_t(k, t); + auto v_t = get_t(v, t); + auto g_t = get_t(g, t); + auto beta_t = get_t(beta, t); + array mask_t = has_mask ? get_t(mask, t) : array(true); + + auto state_prev = state; + + auto decay = (g_t.ndim() == 2) + ? expand_dims(g_t, {-1, -2}, s) // [B,H,1,1] + : expand_dims(g_t, -2, s); // [B,H,1,Dk] + + auto state_next = multiply(state_prev, decay, s); + + auto kv = + sum(multiply(state_next, expand_dims(k_t, -2, s), s), + -1, + false, + s); // [B,H,Dv] + + auto delta = subtract(v_t, kv, s); + delta = multiply(delta, expand_dims(beta_t, -1, s), s); + + state_next = + add(state_next, + multiply(expand_dims(delta, -1, s), expand_dims(k_t, -2, s), s), + s); + + if (has_mask) { + auto state_mask = expand_dims(mask_t, {-1, -2, -3}, s); + state = where(state_mask, state_next, state_prev, s); + } else { + state = state_next; + } + + auto o_t = sum(multiply(state, expand_dims(q_t, -2, s), s), -1, false, s); + + if (has_mask) { + auto out_mask = expand_dims(mask_t, {-1, -2}, s); + o_t = where(out_mask, o_t, zero, s); + } + outputs.push_back(astype(o_t, out_dtype, s)); + } + auto out = stack(outputs, 1, s); + return std::vector{out, state}; + }; + + if (!GatedDeltaUpdate::use_fallback(Hk, Dk, Hv, Dv, has_mask, s)) { + auto result = array::make_arrays( + /* output shapes */ {{B, T, Hv, Dv}, {B, Hv, Dv, Dk}}, + /* dtypes */ {out_dtype, float32}, + /* primitive */ + std::make_shared(s, fallback), + /* inputs */ {q, k, v, g, beta, h0}); + + return result; + } + + auto result = fallback({q, k, v, g, beta, h0, mask}); + return result; +} +std::vector GatedDeltaUpdate::vjp( + const std::vector& primals, + const std::vector& cotangents, + const std::vector& argnums, + const std::vector& outputs) { + const int Hk = primals[0].shape(2); + const int Dk = primals[0].shape(3); + const int Hv = primals[2].shape(2); + const int Dv = primals[2].shape(3); + + if (GatedDeltaUpdateVJP::use_fallback(Hk, Dk, Hv, Dv, stream())) { + return Custom::vjp(primals, cotangents, argnums, outputs); + } + + if (primals.size() != 6) { + throw std::runtime_error( + "[GatedDeltaUpdate::vjp] expected 6 primals (q,k,v,g,beta,h0), got " + + std::to_string(primals.size())); + } + if (cotangents.size() != 2) { + throw std::runtime_error( + "[GatedDeltaUpdate::vjp] expected 2 cotangents (out, state), got " + + std::to_string(cotangents.size())); + } + + std::vector inputs = primals; // q,k,v,g,beta,h0 (indices 0..5) + inputs.push_back(cotangents[0]); // cot_o -> index 6 + inputs.push_back(cotangents[1]); // cot_h -> index 7 + + std::vector shapes; + std::vector dtypes; + for (int i = 0; i < 6; ++i) { + shapes.push_back(primals[i].shape()); + dtypes.push_back(i == 5 ? float32 : primals[i].dtype()); // dh is float32 + } + + auto vjps = array::make_arrays( + std::move(shapes), + std::move(dtypes), + std::make_shared(stream(), fallback_), + std::move(inputs)); + + std::vector returned_vjps; + for (int arg : argnums) { + returned_vjps.push_back(std::move(vjps[arg])); + } + return returned_vjps; +} + bool Quantize::is_equivalent(const Primitive& other) const { const Quantize& p_other = static_cast(other); return ( diff --git a/mlx/fast.h b/mlx/fast.h index aca6da3aed..8f026c6c48 100644 --- a/mlx/fast.h +++ b/mlx/fast.h @@ -60,6 +60,16 @@ MLX_API array scaled_dot_product_attention( bool force_fused = false, StreamOrDevice s = {}); +MLX_API std::vector gated_delta_update( + const array& queries, + const array& keys, + const array& values, + const array& gates, + const array& beta_, + const std::optional& initial_state = std::nullopt, + const std::optional& mask = std::nullopt, + StreamOrDevice s = {}); + using TemplateArg = std::variant; using ScalarArg = std::variant; diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 0a1a945cdd..bbe7d5b0c9 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1,4 +1,4 @@ -// Copyright © 2024 Apple Inc. +// Copyright © 2024-2026 Apple Inc. #include #include @@ -289,6 +289,7 @@ class ScaledDotProductAttention : public Custom { bool has_mask, bool has_arr_mask, bool do_causal, + bool has_sinks, bool is_training, bool output_logsumexp, bool force_fused, @@ -395,6 +396,77 @@ class ConvertFP8 : public Primitive { bool to_fp8_; }; +class GatedDeltaUpdate : public Custom { + public: + GatedDeltaUpdate( + Stream stream, + std::function(std::vector)> fallback) + : Custom(stream, std::move(fallback)) {} + + static bool use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + const bool has_mask, + Stream s); + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { + throw std::runtime_error("NYI"); + } + + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + std::vector vjp( + const std::vector& primals, + const std::vector& cotangents, + const std::vector& argnums, + const std::vector& outputs) override; + + DEFINE_NAME(GatedDeltaUpdate); + DEFINE_INPUT_OUTPUT_SHAPE() + auto state() const { + return std::make_tuple(nullptr); /* TODO */ + } + + private: + bool is_training_; +}; + +class GatedDeltaUpdateVJP : public Custom { + public: + GatedDeltaUpdateVJP( + Stream stream, + std::function(std::vector)> fallback) + : Custom(stream, std::move(fallback)) {} + + static bool use_fallback( + const int Hk, + const int Dk, + const int Hv, + const int Dv, + Stream s); + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { + throw std::runtime_error("NYI"); + } + + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + DEFINE_NAME(GatedDeltaUpdateVJP); + DEFINE_INPUT_OUTPUT_SHAPE() + auto state() const { + return std::make_tuple(nullptr); /* TODO */ + } + + private: + bool has_cache_; +}; + class Quantize : public Custom { public: explicit Quantize( diff --git a/mlx/fence.h b/mlx/fence.h index 3fd5da333b..fd6bc116a4 100644 --- a/mlx/fence.h +++ b/mlx/fence.h @@ -1,6 +1,6 @@ // Copyright © 2024 Apple Inc. -#include +#include #include "mlx/array.h" @@ -8,12 +8,9 @@ namespace mlx::core { /* A fence to be used for synchronizing work between streams. * - * Calls to `wait` wait in the given stream until all previous calls to update - * are complete on their given stream. - * - * The array passed to `update` is computed and visible after the call to - * `wait` returns. The array passed to `wait` will not be read until all - * previous calls to `update` have completed. + * `update` returns a value that marks when its array is computed and visible. + * `wait` orders work in the consumer stream after that value is signaled. + * Later updates do not extend an earlier array's wait. * * Note, calls to `update` should always be from the same thread or explicitly * synchronized so that they occur in sequence. Calls to `wait` can be on any @@ -29,8 +26,8 @@ class Fence { Fence() {}; explicit Fence(Stream stream); - void update(Stream stream, const array& x, bool cross_device); - void wait(Stream stream, const array& x); + uint32_t update(Stream stream, const array& x, bool cross_device); + void wait(Stream stream, const array& x, uint32_t value); template auto& cast() const { diff --git a/mlx/fft.cpp b/mlx/fft.cpp index 06860a0e3a..e1c5756e1b 100644 --- a/mlx/fft.cpp +++ b/mlx/fft.cpp @@ -1,4 +1,5 @@ // Copyright © 2023 Apple Inc. +#include #include #include #include @@ -61,7 +62,7 @@ array fft_impl( std::ostringstream msg; msg << "[fftn] Invalid axis received for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } // In the following shape manipulations there are three cases to consider: @@ -114,7 +115,12 @@ array fft_impl( auto out = array( out_shape, out_type, - std::make_shared(to_stream(s), valid_axes, inverse, real), + std::make_shared( + to_stream(s), + valid_axes, + inverse, + real, + real && inverse && (n.back() % 2 != 0)), {astype(in, in_type, s)}); auto scale = fft_scale_factor(n, norm, inverse); if (scale != 1.0) { @@ -262,7 +268,7 @@ array fftshift_impl( std::ostringstream msg; msg << "[" << name << "] Invalid axis " << ax << " for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } // Match NumPy's implementation int shift = a.shape(axis) / 2; @@ -335,4 +341,230 @@ array rfftfreq(int n, double d /* = 1.0 */, StreamOrDevice s /* = {} */) { return multiply(freqs, scale, s); } +namespace { + +// Center a window of length <= n_fft inside an n_fft-length frame. +array prepare_window( + const std::optional& window, + int win_length, + int n_fft, + const std::string& op, + StreamOrDevice s) { + array win = + window.has_value() ? window.value() : ones({win_length}, float32, s); + if (win.ndim() != 1) { + throw std::invalid_argument( + "[" + op + "] window must be a one-dimensional array."); + } + int wl = win.shape(0); + if (wl > n_fft) { + throw std::invalid_argument( + "[" + op + "] window length must not exceed n_fft."); + } + if (wl < n_fft) { + int pad_left = (n_fft - wl) / 2; + int pad_right = n_fft - wl - pad_left; + win = + pad(win, + {0}, + {pad_left}, + {pad_right}, + array(0, win.dtype()), + "constant", + s); + } + return win; +} + +} // namespace + +array stft( + const array& x_in, + int n_fft /* = 2048 */, + const std::optional& hop_length_ /* = std::nullopt */, + const std::optional& win_length_ /* = std::nullopt */, + const std::optional& window /* = std::nullopt */, + bool center /* = true */, + const std::string& pad_mode /* = "reflect" */, + FFTNorm norm /* = FFTNorm::Backward */, + const std::optional& onesided_ /* = std::nullopt */, + StreamOrDevice s /* = {} */) { + if (n_fft <= 0) { + throw std::invalid_argument("[stft] n_fft must be positive."); + } + if (x_in.ndim() < 1) { + throw std::invalid_argument( + "[stft] Input must have at least one dimension."); + } + int hop_length = hop_length_.value_or(n_fft / 4); + int win_length = win_length_.value_or(n_fft); + if (hop_length <= 0) { + throw std::invalid_argument("[stft] hop_length must be positive."); + } + bool onesided = onesided_.value_or(x_in.dtype() != complex64); + + array win = prepare_window(window, win_length, n_fft, "stft", s); + + // Collapse leading dims into a single batch axis. + Shape lead = x_in.shape(); + lead.pop_back(); + int t = x_in.shape(-1); + array x = reshape(x_in, {-1, t}, s); + + if (center) { + int p = n_fft / 2; + x = pad(x, {1}, {p}, {p}, array(0, x.dtype()), pad_mode, s); + } + int tp = x.shape(-1); + if (tp < n_fft) { + throw std::invalid_argument( + "[stft] Input is too short for the given n_fft."); + } + int n_frames = 1 + (tp - n_fft) / hop_length; + int b = x.shape(0); + + // Overlapping frames via as_strided (element strides: tp, hop, 1). + array frames = as_strided( + x, + {b, n_frames, n_fft}, + Strides{static_cast(tp), static_cast(hop_length), 1}, + 0, + s); + frames = multiply(frames, win, s); + + array spec = onesided ? rfftn(frames, Shape{n_fft}, {-1}, norm, s) + : fftn(frames, Shape{n_fft}, {-1}, norm, s); + spec = swapaxes(spec, -1, -2, s); + + Shape out_shape = lead; + out_shape.push_back(spec.shape(-2)); + out_shape.push_back(n_frames); + return reshape(spec, out_shape, s); +} + +array istft( + const array& stft_matrix, + const std::optional& n_fft_ /* = std::nullopt */, + const std::optional& hop_length_ /* = std::nullopt */, + const std::optional& win_length_ /* = std::nullopt */, + const std::optional& window /* = std::nullopt */, + bool center /* = true */, + FFTNorm norm /* = FFTNorm::Backward */, + const std::optional& onesided_ /* = std::nullopt */, + const std::optional& length_ /* = std::nullopt */, + StreamOrDevice s /* = {} */) { + if (stft_matrix.ndim() < 2) { + throw std::invalid_argument( + "[istft] Input must have at least two dimensions (freq, frames)."); + } + bool onesided = onesided_.value_or(true); + int n_freq = stft_matrix.shape(-2); + int n_fft = n_fft_.value_or(onesided ? (n_freq - 1) * 2 : n_freq); + if (n_fft <= 0) { + throw std::invalid_argument("[istft] n_fft must be positive."); + } + int hop_length = hop_length_.value_or(n_fft / 4); + int win_length = win_length_.value_or(n_fft); + if (hop_length <= 0) { + throw std::invalid_argument("[istft] hop_length must be positive."); + } + + array win = prepare_window(window, win_length, n_fft, "istft", s); + + Shape lead = stft_matrix.shape(); + int n_frames = lead.back(); + lead.pop_back(); + lead.pop_back(); + array z = reshape(stft_matrix, {-1, n_freq, n_frames}, s); + int b = z.shape(0); + z = swapaxes(z, -1, -2, s); + + array frames = onesided ? irfftn(z, Shape{n_fft}, {-1}, norm, s) + : real(ifftn(z, Shape{n_fft}, {-1}, norm, s), s); + frames = multiply(frames, win, s); + + // Overlap-add: sub-block k of frame i lands on output block i + k, so + // summing seg = ceil(n_fft / hop) shifted copies is independent of n_frames. + int seg = (n_fft + hop_length - 1) / hop_length; + int wp = seg * hop_length; + if (wp > n_fft) { + frames = + pad(frames, + {2}, + {0}, + {wp - n_fft}, + array(0, frames.dtype()), + "constant", + s); + } + array c = reshape(frames, {b, n_frames, seg, hop_length}, s); + + array win_sq = square(win, s); + if (wp > n_fft) { + win_sq = + pad(win_sq, + {0}, + {0}, + {wp - n_fft}, + array(0, win_sq.dtype()), + "constant", + s); + } + array cw = broadcast_to( + reshape(win_sq, {1, 1, seg, hop_length}, s), + {1, n_frames, seg, hop_length}, + s); + + int out_blocks = n_frames + seg - 1; + int out_len = out_blocks * hop_length; + array signal = zeros({b, out_len}, frames.dtype(), s); + array envelope = zeros({1, out_len}, frames.dtype(), s); + for (int k = 0; k < seg; ++k) { + array ck = reshape( + slice(c, {0, 0, k, 0}, {b, n_frames, k + 1, hop_length}, s), + {b, n_frames, hop_length}, + s); + ck = pad(ck, {1}, {k}, {seg - 1 - k}, array(0, ck.dtype()), "constant", s); + signal = add(signal, reshape(ck, {b, out_len}, s), s); + + array wk = reshape( + slice(cw, {0, 0, k, 0}, {1, n_frames, k + 1, hop_length}, s), + {1, n_frames, hop_length}, + s); + wk = pad(wk, {1}, {k}, {seg - 1 - k}, array(0, wk.dtype()), "constant", s); + envelope = add(envelope, reshape(wk, {1, out_len}, s), s); + } + signal = + divide(signal, maximum(envelope, array(1e-8f, envelope.dtype()), s), s); + + // Drop the centering pad from the start. The end is bounded by `length` when + // given, otherwise by removing the centering pad from the end as well. The + // full reconstruction spans n_fft + (n_frames - 1) * hop before centering. + int sig_len = n_fft + (n_frames - 1) * hop_length; + int start = center ? n_fft / 2 : 0; + if (length_.has_value()) { + int length = length_.value(); + int stop = std::min(sig_len, start + length); + signal = slice(signal, {0, start}, {b, stop}, s); + int cur = signal.shape(-1); + if (cur < length) { + signal = + pad(signal, + {1}, + {0}, + {length - cur}, + array(0, signal.dtype()), + "constant", + s); + } + } else { + int stop = center ? sig_len - n_fft / 2 : sig_len; + signal = slice(signal, {0, start}, {b, stop}, s); + } + + Shape out_shape = lead; + out_shape.push_back(signal.shape(-1)); + return reshape(signal, out_shape, s); +} + } // namespace mlx::core::fft diff --git a/mlx/fft.h b/mlx/fft.h index f69b8aa2c4..f067ff49c5 100644 --- a/mlx/fft.h +++ b/mlx/fft.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include "array.h" @@ -212,6 +213,7 @@ inline array irfft2( StreamOrDevice s = {}) { return irfftn(a, axes, norm, s); } + /** Compute the discrete Fourier Transform sample frequencies. */ MLX_API array fftfreq(int n, double d = 1.0, StreamOrDevice s = {}); @@ -234,4 +236,30 @@ MLX_API array ifftshift(const array& a, StreamOrDevice s = {}); MLX_API array ifftshift(const array& a, const std::vector& axes, StreamOrDevice s = {}); +/** Compute the Short-Time Fourier Transform of the last axis of `x`. */ +MLX_API array stft( + const array& x, + int n_fft = 2048, + const std::optional& hop_length = std::nullopt, + const std::optional& win_length = std::nullopt, + const std::optional& window = std::nullopt, + bool center = true, + const std::string& pad_mode = "reflect", + FFTNorm norm = FFTNorm::Backward, + const std::optional& onesided = std::nullopt, + StreamOrDevice s = {}); + +/** Compute the inverse Short-Time Fourier Transform. */ +MLX_API array istft( + const array& stft_matrix, + const std::optional& n_fft = std::nullopt, + const std::optional& hop_length = std::nullopt, + const std::optional& win_length = std::nullopt, + const std::optional& window = std::nullopt, + bool center = true, + FFTNorm norm = FFTNorm::Backward, + const std::optional& onesided = std::nullopt, + const std::optional& length = std::nullopt, + StreamOrDevice s = {}); + } // namespace mlx::core::fft diff --git a/mlx/io/gguf.cpp b/mlx/io/gguf.cpp index 6c27c46987..bc54056248 100644 --- a/mlx/io/gguf.cpp +++ b/mlx/io/gguf.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "mlx/io/gguf.h" @@ -47,16 +48,35 @@ std::optional gguf_type_to_dtype(const uint32_t& gguf_type) { } } +[[noreturn]] void tensor_error( + const gguf_tensor& tensor, + const std::string& what) { + std::ostringstream msg; + msg << "[load_gguf] Tensor '" << std::string(tensor.name, tensor.namelen) + << "' " << what << ". Perhaps an incomplete download or corrupt file?"; + throw std::runtime_error(msg.str()); +} + Shape get_shape(const gguf_tensor& tensor) { Shape shape; + uint64_t num_weights = 1; // The dimension order in GGML is the reverse of the order used in MLX. for (int i = tensor.ndim - 1; i >= 0; i--) { - shape.push_back(tensor.dim[i]); + auto dim = tensor.dim[i]; + if (dim > std::numeric_limits::max()) { + tensor_error(tensor, "has a dimension that is too large"); + } + if (dim != 0 && num_weights > std::numeric_limits::max() / dim) { + tensor_error( + tensor, "has a dimension product that does not fit in 64 bits"); + } + num_weights *= dim; + shape.push_back(dim); } return shape; } -std::tuple extract_tensor_data(gguf_tensor* tensor) { +std::tuple extract_tensor_data(gguf_tensor* tensor) { if (tensor == nullptr) { throw std::invalid_argument( "[extract_tensor_data] Input tensor pointer is null."); @@ -67,12 +87,12 @@ std::tuple extract_tensor_data(gguf_tensor* tensor) { if (tensor->weights_data == nullptr) { throw std::runtime_error("[load_gguf] NULL tensor data pointer"); } - allocator::Buffer buffer = allocator::malloc(tensor->bsize); + auto out = allocator::malloc(tensor->bsize); memcpy( - buffer.raw_ptr(), + out.buffer().raw_ptr(), tensor->weights_data, tensor->num_weights * equivalent_dtype.value().size()); - return {buffer, equivalent_dtype.value()}; + return {std::move(out), equivalent_dtype.value()}; } // Otherwise, we convert to float16. // TODO: Add other dequantization options. @@ -81,10 +101,10 @@ std::tuple extract_tensor_data(gguf_tensor* tensor) { throw std::runtime_error("[load_gguf] gguf_tensor_to_f16 failed"); } const size_t new_size = tensor->num_weights * sizeof(int16_t); - allocator::Buffer buffer = allocator::malloc(new_size); - memcpy(buffer.raw_ptr(), data, new_size); + auto out = allocator::malloc(new_size); + memcpy(out.buffer().raw_ptr(), data, new_size); free(data); - return {buffer, float16}; + return {std::move(out), float16}; } void set_mx_value_from_gguf( @@ -303,20 +323,14 @@ std::unordered_map load_metadata(gguf_ctx* ctx) { } void check_tensor_in_file(const gguf_ctx* ctx, const gguf_tensor& tensor) { - auto fail = [&tensor](const std::string& what) { - std::ostringstream msg; - msg << "[load_gguf] Tensor '" << std::string(tensor.name, tensor.namelen) - << "' " << what << ". Perhaps an incomplete download or corrupt file?"; - throw std::runtime_error(msg.str()); - }; if (tensor.offset < ctx->data_off) { - fail("has a data offset that overflows the data section"); + tensor_error(tensor, "has a data offset that overflows the data section"); } if (tensor.offset > ctx->size) { - fail("has a data offset past the end of the file"); + tensor_error(tensor, "has a data offset past the end of the file"); } if (tensor.bsize > ctx->size - tensor.offset) { - fail("extends past the end of the file"); + tensor_error(tensor, "extends past the end of the file"); } } @@ -340,8 +354,8 @@ std::unordered_map load_arrays(gguf_ctx* ctx) { gguf_load_quantized(array_map, tensor); } else { std::string name(tensor.name, tensor.namelen); - const auto& [data, dtype] = extract_tensor_data(&tensor); - array loaded_array = array(data, get_shape(tensor), dtype); + auto [data, dtype] = extract_tensor_data(&tensor); + array loaded_array = array(std::move(data), get_shape(tensor), dtype); check_insert(array_map.insert({name, loaded_array})); } } diff --git a/mlx/io/gguf_quants.cpp b/mlx/io/gguf_quants.cpp index 83dfe1f822..1717be5601 100644 --- a/mlx/io/gguf_quants.cpp +++ b/mlx/io/gguf_quants.cpp @@ -112,6 +112,11 @@ void gguf_load_quantized( std::string name(tensor.name, tensor.namelen); auto shape = get_shape(tensor); + if (shape.empty()) { + std::ostringstream msg; + msg << "[load_gguf] quantized tensor " << name << " has no dimensions"; + throw std::runtime_error(msg.str()); + } const uint64_t weights_per_block = 32; if (shape[shape.size() - 1] % weights_per_block != 0) { std::ostringstream msg; @@ -125,15 +130,17 @@ void gguf_load_quantized( auto w_nbytes = uint32.size() * std::accumulate(weights_shape.begin(), weights_shape.end(), - 1, + size_t{1}, std::multiplies()); array weights(allocator::malloc(w_nbytes), std::move(weights_shape), uint32); // For scales and bias shape[shape.size() - 1] = shape[shape.size() - 1] / weights_per_block; - auto sb_nbytes = float16.size() * - std::accumulate(shape.begin(), shape.end(), 1, std::multiplies()); + auto sb_nbytes = + float16.size() * + std::accumulate( + shape.begin(), shape.end(), size_t{1}, std::multiplies()); array scales(allocator::malloc(sb_nbytes), shape, float16); array biases(allocator::malloc(sb_nbytes), std::move(shape), float16); diff --git a/mlx/io/load.cpp b/mlx/io/load.cpp index a9379c3079..f5472b55c4 100644 --- a/mlx/io/load.cpp +++ b/mlx/io/load.cpp @@ -1,9 +1,11 @@ // Copyright © 2023-2026 Apple Inc. #include +#include #include #include #include #include +#include // Used by pread implementation. #ifdef _WIN32 @@ -148,6 +150,10 @@ void save(std::shared_ptr out_stream, array a) { a = contiguous(a, true); a.eval(); + // Open only after the inputs are evaluated: opening a FileWriter + // truncates the file and lazy inputs may still read from it. + out_stream->open(); + //////////////////////////////////////////////////////// // Check file if (!out_stream->good() || !out_stream->is_open()) { @@ -286,10 +292,23 @@ array load(std::shared_ptr in_stream, StreamOrDevice s) { size_t ed = header.find_last_of(')'); std::string shape_str = header.substr(st, ed - st); + size_t max_size = std::numeric_limits::max() / size_of(dtype); + size_t total_size = 1; while (!shape_str.empty()) { // Read current number and get position of comma size_t pos; int dim = std::stoi(shape_str, &pos); + + // Reject negative dims and a total byte count that overflows size_t + if (dim < 0) { + throw std::runtime_error( + "[load] Negative dimension in shape in " + in_stream->label()); + } + if (dim != 0 && total_size > max_size / dim) { + throw std::runtime_error( + "[load] Shape is too large in " + in_stream->label()); + } + total_size *= dim; shape.push_back(dim); // Skip the comma and space and read the next number @@ -334,6 +353,40 @@ array load(std::string file, StreamOrDevice s) { namespace io { +namespace { + +// The reads to keep in flight while reading a file in batches. The disk, not +// the cpu, is the limit here: a thread waits for it most of the time, but a +// queue deeper than the device can serve only adds latency. Half the cores +// saturates the storage of a machine, which is faster on the machines that +// have more cores. +size_t batch_thread_count() { + size_t n_cores = std::thread::hardware_concurrency(); + return std::clamp(n_cores / 2, 4, 16); +} + +// The pool of the batched reads. Every reader shares it, because the disk is +// one resource: a pool per file would multiply the reads in flight by the +// number of open files, which is how a sharded model is read. +// +// It is held with a weak reference, so the threads start with the first +// batched read and stop once the readers that use them are destroyed. Reading +// a file is a startup task, and this keeps no thread for the rest of the run. +std::shared_ptr acquire_batch_pool() { + static std::mutex mtx; + static std::weak_ptr weak_pool; + + std::lock_guard lock(mtx); + auto pool = weak_pool.lock(); + if (!pool) { + pool = std::make_shared(batch_thread_count()); + weak_pool = pool; + } + return pool; +} + +} // namespace + ThreadPool& thread_pool() { // Leak - see Scheduler singleton comment in scheduler.cpp. static ThreadPool* pool_ = new ThreadPool{4}; @@ -341,15 +394,22 @@ ThreadPool& thread_pool() { } ThreadPool& ParallelFileReader::thread_pool() { - // Leak - see Scheduler singleton comment in scheduler.cpp. - static ThreadPool* thread_pool = new ThreadPool{4}; - return *thread_pool; + std::call_once(pool_once_, [this]() { pool_ = acquire_batch_pool(); }); + return *pool_; } void ParallelFileReader::read(char* data, size_t n) { while (n != 0) { auto m = ::read(fd_, data, std::min(n, static_cast(INT32_MAX))); - if (m <= 0) { + if (m < 0) { + if (errno == EINTR) { + continue; + } + std::ostringstream msg; + msg << "[read] Unable to read " << n << " bytes from file."; + throw std::runtime_error(msg.str()); + } + if (m == 0) { std::ostringstream msg; msg << "[read] Unable to read " << n << " bytes from file."; throw std::runtime_error(msg.str()); @@ -363,34 +423,37 @@ void ParallelFileReader::read(char* data, size_t n, size_t offset) { auto readfn = [fd = fd_](size_t offset, size_t size, char* buffer) -> bool { while (size != 0) { auto m = pread(fd, buffer, size, offset); - if (m <= 0) { + if (m < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + if (m == 0) { return false; } buffer += m; size -= m; + offset += m; } return true; }; + // Read the whole batches in the pool and what is left in this thread. std::vector> futs; - while (n != 0) { - if (n < batch_size_) { - if (!readfn(offset, n, data)) { - throw std::runtime_error("[read] Unable to read from file."); - } - break; - } else { - size_t m = batch_size_; - futs.emplace_back( - ParallelFileReader::thread_pool().enqueue(readfn, offset, m, data)); - data += m; - n -= m; - offset += m; - } + while (n >= batch_size_) { + futs.emplace_back(thread_pool().enqueue(readfn, offset, batch_size_, data)); + data += batch_size_; + offset += batch_size_; + n -= batch_size_; } + bool ok = n == 0 || readfn(offset, n, data); + + // Wait for every batch, they all write into |data|. for (auto& f : futs) { - if (!f.get()) { - throw std::runtime_error("[read] Unable to read from file."); - } + ok = f.get() && ok; + } + if (!ok) { + throw std::runtime_error("[read] Unable to read from file."); } } diff --git a/mlx/io/load.h b/mlx/io/load.h index 2e13efe114..6b9c9f477b 100644 --- a/mlx/io/load.h +++ b/mlx/io/load.h @@ -3,10 +3,12 @@ #pragma once #include +#include #include +#include #include -#ifdef _MSC_VER +#ifdef _WIN32 #include #else #include @@ -53,6 +55,8 @@ class Writer { std::ios_base::seekdir way = std::ios_base::beg) = 0; virtual void write(const char* data, size_t n) = 0; virtual std::string label() const = 0; + virtual void open() {} + virtual ~Writer() = default; }; @@ -75,20 +79,30 @@ class ParallelFileReader : public Reader { } size_t tell() override { +#ifdef _WIN32 + return _lseeki64(fd_, 0, SEEK_CUR); +#else return lseek(fd_, 0, SEEK_CUR); +#endif } // Warning: do not use this function from multiple threads as // it advances the file descriptor void seek(int64_t off, std::ios_base::seekdir way = std::ios_base::beg) override { + int origin; if (way == std::ios_base::beg) { - lseek(fd_, off, SEEK_SET); + origin = SEEK_SET; } else if (way == std::ios_base::end) { - lseek(fd_, off, SEEK_END); + origin = SEEK_END; } else { - lseek(fd_, off, SEEK_CUR); + origin = SEEK_CUR; } +#ifdef _WIN32 + _lseeki64(fd_, off, origin); +#else + lseek(fd_, off, origin); +#endif } // Warning: do not use this function from multiple threads as @@ -102,34 +116,49 @@ class ParallelFileReader : public Reader { } private: + // Reads larger than this are split in batches and read in parallel. static constexpr size_t batch_size_ = 1 << 25; - static ThreadPool& thread_pool(); + + // The pool that reads the batches, held from the first batched read until + // the reader is destroyed. It cannot be io::thread_pool(), the tasks that + // run there wait for these batches and would deadlock in the same pool. + ThreadPool& thread_pool(); + int fd_; std::string label_; + std::once_flag pool_once_; + std::shared_ptr pool_; }; class FileWriter : public Writer { public: explicit FileWriter() {} explicit FileWriter(std::string file_path) - : fd_(open( - file_path.c_str(), - O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, - 0644)), - label_(std::move(file_path)) {} + : file_path_(std::move(file_path)) {} FileWriter(const FileWriter&) = delete; FileWriter& operator=(const FileWriter&) = delete; - FileWriter(FileWriter&& other) { - std::swap(fd_, other.fd_); + FileWriter(FileWriter&& other) + : fd_(std::exchange(other.fd_, -1)), + file_path_(std::move(other.file_path_)) { + other.file_path_.clear(); } ~FileWriter() override { - if (fd_ != 0) { + if (fd_ >= 0) { close(fd_); } } + // Kept separate from construction so lazy inputs can be evaluated first, + // they may still read from the file. + void open() override { + if (fd_ < 0 && !file_path_.empty()) { + fd_ = ::open( + file_path_.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, 0644); + } + } + bool is_open() const override { return fd_ >= 0; } @@ -139,21 +168,34 @@ class FileWriter : public Writer { } size_t tell() override { + check_open(); +#ifdef _WIN32 + return _lseeki64(fd_, 0, SEEK_CUR); +#else return lseek(fd_, 0, SEEK_CUR); +#endif } void seek(int64_t off, std::ios_base::seekdir way = std::ios_base::beg) override { + check_open(); + int origin; if (way == std::ios_base::beg) { - lseek(fd_, off, SEEK_SET); + origin = SEEK_SET; } else if (way == std::ios_base::end) { - lseek(fd_, off, SEEK_END); + origin = SEEK_END; } else { - lseek(fd_, off, SEEK_CUR); + origin = SEEK_CUR; } +#ifdef _WIN32 + _lseeki64(fd_, off, origin); +#else + lseek(fd_, off, origin); +#endif } void write(const char* data, size_t n) override { + check_open(); while (n != 0) { auto m = ::write(fd_, data, std::min(n, static_cast(INT32_MAX))); if (m <= 0) { @@ -167,12 +209,18 @@ class FileWriter : public Writer { } std::string label() const override { - return "file " + label_; + return "file " + file_path_; } private: - int fd_{0}; - std::string label_; + void check_open() const { + if (!is_open()) { + throw std::runtime_error("[write] File " + file_path_ + " is not open."); + } + } + + int fd_{-1}; + std::string file_path_; }; } // namespace io diff --git a/mlx/io/safetensors.cpp b/mlx/io/safetensors.cpp index 75c8a6ddc2..319579c48f 100644 --- a/mlx/io/safetensors.cpp +++ b/mlx/io/safetensors.cpp @@ -221,6 +221,20 @@ void save_safetensors( std::shared_ptr out_stream, std::unordered_map a, std::unordered_map metadata /* = {} */) { + { + std::vector to_eval; + to_eval.reserve(a.size()); + for (auto& p : a) { + p.second = contiguous(p.second); + to_eval.push_back(p.second); + } + eval(std::move(to_eval)); + } + + // Open only after the inputs are evaluated: opening a FileWriter + // truncates the file and lazy inputs may still read from it. + out_stream->open(); + //////////////////////////////////////////////////////// // Check file if (!out_stream->good() || !out_stream->is_open()) { @@ -238,16 +252,6 @@ void save_safetensors( } parent["__metadata__"] = _metadata; - { - std::vector to_eval; - to_eval.reserve(a.size()); - for (auto& p : a) { - p.second = contiguous(p.second); - to_eval.push_back(p.second); - } - eval(std::move(to_eval)); - } - size_t offset = 0; for (auto& [key, arr] : a) { json child; diff --git a/mlx/linalg.cpp b/mlx/linalg.cpp index 0d06b56469..c4213c93bc 100644 --- a/mlx/linalg.cpp +++ b/mlx/linalg.cpp @@ -4,6 +4,7 @@ #include #include +#include "mlx/backend/cuda/cuda.h" #include "mlx/linalg.h" #include "mlx/primitives.h" #include "mlx/utils.h" @@ -18,6 +19,18 @@ void check_cpu_stream(const StreamOrDevice& s, const std::string& prefix) { "Explicitly pass a CPU stream to run it."); } } + +// For ops that have a CUDA implementation but no Metal one yet. +void check_cpu_or_cuda_stream( + const StreamOrDevice& s, + const std::string& prefix) { + if (to_stream(s).device == Device::gpu && !cu::is_available()) { + throw std::invalid_argument( + prefix + + " This op is not yet supported on the GPU. " + "Explicitly pass a CPU stream to run it."); + } +} void check_float(Dtype dtype, const std::string& prefix) { if (dtype != float32 && dtype != float64) { std::ostringstream msg; @@ -336,7 +349,7 @@ array cholesky( const array& a, bool upper /* = false */, StreamOrDevice s /* = {} */) { - check_cpu_stream(s, "[linalg::cholesky]"); + check_cpu_or_cuda_stream(s, "[linalg::cholesky]"); check_float(a.dtype(), "[linalg::cholesky]"); if (a.ndim() < 2) { std::ostringstream msg; diff --git a/mlx/memory.cpp b/mlx/memory.cpp new file mode 100644 index 0000000000..700cc2729f --- /dev/null +++ b/mlx/memory.cpp @@ -0,0 +1,30 @@ +// Copyright © 2026 Apple Inc. + +#include +#include + +#include "mlx/memory.h" + +namespace mlx::core { + +size_t get_array_buffer_size(const std::vector& arrays) { + std::unordered_set buffers; + buffers.reserve(arrays.size()); + + size_t total = 0; + for (const auto& arr : arrays) { + if (arr.status() == array::Status::unscheduled) { + throw std::invalid_argument( + "[get_array_buffer_size] Arrays must be evaluated before querying " + "buffer size."); + } + + const auto& buffer = arr.buffer(); + if (buffer.ptr() != nullptr && buffers.insert(buffer.ptr()).second) { + total += arr.buffer_size(); + } + } + return total; +} + +} // namespace mlx::core diff --git a/mlx/memory.h b/mlx/memory.h index d36201b51a..6f2cde8889 100644 --- a/mlx/memory.h +++ b/mlx/memory.h @@ -1,12 +1,14 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. #pragma once #include #include #include +#include #include "mlx/api.h" +#include "mlx/array.h" #include "mlx/backend/common/process_allocation_cap.h" namespace mlx::core { @@ -100,6 +102,14 @@ MLX_API AllocationFootprintPolicy get_allocation_footprint_policy() noexcept; * */ MLX_API size_t get_active_memory(); +/* Get the size of the buffers backing the given arrays in bytes. + * + * Each unique buffer is counted once. The full allocator size of each buffer + * is used, which can exceed the logical size of its arrays. The arrays must be + * evaluated before calling this function. + * */ +MLX_API size_t get_array_buffer_size(const std::vector& arrays); + /* Get the peak amount of used memory in bytes. * * The maximum memory used recorded from the beginning of the program @@ -142,6 +152,9 @@ MLX_API size_t get_resource_limit(); * When Metal is available the memory limit defaults to 1.5 times the maximum * recommended working set size reported by the device. * + * On native Windows with CUDA the memory limit is also bounded by the current + * video memory budget reported by the operating system. + * * Returns the previous memory limit. * */ MLX_API size_t set_memory_limit(size_t limit); diff --git a/mlx/ops.cpp b/mlx/ops.cpp index 5fe3d9be59..b67fbd0342 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -96,7 +96,7 @@ array indices_or_default( << " Got indices with invalid dtype. Indices must be integral."; throw std::invalid_argument(msg.str()); } - return astype(indices.value(), uint32); + return astype(indices.value(), uint32, s); } Shape shape(x.shape().begin(), x.shape().end() - 2); @@ -333,8 +333,7 @@ array as_strided( dtype, std::make_shared( to_stream(s), std::move(shape), std::move(strides), offset), - // Force the input array to be contiguous. - {flatten(std::move(a), s)}); + {std::move(a)}); } array copy(array a, StreamOrDevice s /* = {} */) { @@ -482,7 +481,7 @@ array unflatten( std::ostringstream msg; msg << "[unflatten] Invalid axes " << ax << " for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } size_t size = 1; @@ -726,7 +725,7 @@ array flip(const array& a, StreamOrDevice s /* = {} */) { namespace { inline auto -normalize_slice(const Shape& shape, Shape& start, Shape stop, Shape& strides) { +normalize_slice(const Shape& shape, Shape& start, Shape& stop, Shape& strides) { // - Start indices are normalized // - End indices are unchanged as -1 means something different // pre-normalization (the end of the axis) versus post normalization (the @@ -774,7 +773,13 @@ normalize_slice(const Shape& shape, Shape& start, Shape stop, Shape& strides) { } // Simplify the stride if it's unused if (out_shape[i] == 1) { - strides[i] = 1; + if (strides[i] < 0 && start[i] > 0) { + strides[i] = -1; + stop[i] = start[i] - 1; + } else { + strides[i] = 1; + stop[i] = start[i] + 1; + } } } @@ -817,7 +822,7 @@ void normalize_dynamic_slice_inputs( std::ostringstream msg; msg << prefix << " Invalid axis " << ax << " for array with dimension " << a.ndim() << "."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } ax = new_ax; } @@ -1465,7 +1470,7 @@ array reflect_pad( Shape starts(a.ndim(), 0); auto stops = a.shape(); for (size_t i = 0; i < axes.size(); i++) { - int ax = axes[i]; + int ax = normalize_axis_index(axes[i], a.ndim(), "[pad] "); starts[ax] = low_pad_size[i]; stops[ax] += low_pad_size[i]; } @@ -1473,7 +1478,7 @@ array reflect_pad( array padded = slice_update(out, a, starts, stops, s); for (size_t i = 0; i < axes.size(); i++) { - int ax = axes[i]; + int ax = normalize_axis_index(axes[i], a.ndim(), "[pad] "); int n = a.shape(ax); int L = low_pad_size[i]; int H = high_pad_size[i]; @@ -1546,37 +1551,41 @@ array edge_pad( const Shape& out_shape, StreamOrDevice s /* = {}*/) { array out = zeros(out_shape, a.dtype(), s); - auto stops = a.shape(); - for (int i = 0; i < stops.size(); i++) { - stops[i] += low_pad_size[i]; + Shape in_starts(a.ndim(), 0); + auto in_stops = a.shape(); + for (size_t i = 0; i < axes.size(); i++) { + int ax = normalize_axis_index(axes[i], a.ndim(), "[pad] "); + in_starts[ax] = low_pad_size[i]; + in_stops[ax] += low_pad_size[i]; } // Copy over values from the unpadded array - array padded = slice_update(out, a, low_pad_size, stops, s); + array padded = slice_update(out, a, in_starts, in_stops, s); - for (int axis = 0; axis < a.ndim(); axis++) { - if (low_pad_size[axis] > 0) { + for (size_t i = 0; i < axes.size(); i++) { + int ax = normalize_axis_index(axes[i], a.ndim(), "[pad] "); + if (low_pad_size[i] > 0) { Shape starts(a.ndim(), 0); - starts[axis] = low_pad_size[axis]; + starts[ax] = low_pad_size[i]; auto stops = out.shape(); - stops[axis] = low_pad_size[axis] + 1; + stops[ax] = low_pad_size[i] + 1; // Fetch edge values array edge_value = slice(padded, starts, stops, s); - starts[axis] = 0; - stops[axis] = low_pad_size[axis]; + starts[ax] = 0; + stops[ax] = low_pad_size[i]; // Update edge values in the padded array padded = slice_update(padded, edge_value, starts, stops, s); } - if (high_pad_size[axis] > 0) { + if (high_pad_size[i] > 0) { Shape starts(a.ndim(), 0); - starts[axis] = -high_pad_size[axis] - 1; + starts[ax] = -high_pad_size[i] - 1; auto stops = out.shape(); - stops[axis] = -high_pad_size[axis]; + stops[ax] = -high_pad_size[i]; array edge_value = slice(padded, starts, stops, s); - starts[axis] = -high_pad_size[axis]; - stops[axis] = out.shape(axis); + starts[ax] = -high_pad_size[i]; + stops[ax] = out.shape(ax); padded = slice_update(padded, edge_value, starts, stops, s); } } @@ -1618,7 +1627,7 @@ array pad( throw std::invalid_argument(msg.str()); } - auto ax = axes[i] < 0 ? a.ndim() + axes[i] : axes[i]; + auto ax = normalize_axis_index(axes[i], a.ndim(), "[pad] "); out_shape[ax] = safe_cast( static_cast(out_shape[ax]) + low_pad_size[i] + high_pad_size[i], @@ -1754,7 +1763,7 @@ array transpose( } if (axes.size() != a.ndim()) { std::ostringstream msg; - msg << "[transpose] Recived " << axes.size() << " axes for array with " + msg << "[transpose] Received " << axes.size() << " axes for array with " << a.ndim() << " dimensions."; throw std::invalid_argument(msg.str()); } @@ -1766,7 +1775,7 @@ array transpose( std::ostringstream msg; msg << "[transpose] Invalid axis (" << ax << ") for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } if (shape[ax] != 0) { throw std::invalid_argument("[transpose] Repeat axes not allowed."); @@ -1790,6 +1799,17 @@ array transpose(const array& a, StreamOrDevice s /* = {} */) { return transpose(a, std::move(axes), to_stream(s)); } +array matrix_transpose(const array& a, StreamOrDevice s /* = {} */) { + if (a.ndim() < 2) { + throw std::invalid_argument( + "[matrix_transpose] Input array must have at least 2 dimensions."); + } + std::vector axes(a.ndim()); + std::iota(axes.begin(), axes.end(), 0); + std::swap(axes[a.ndim() - 1], axes[a.ndim() - 2]); + return transpose(a, std::move(axes), to_stream(s)); +} + array broadcast_to( const array& a, const Shape& shape, @@ -2329,7 +2349,7 @@ array mean( std::ostringstream msg; msg << "[mean] axis " << axis << " is out of bounds for array with " << ndim << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } } auto dtype = at_least_float(a.dtype()); @@ -2363,7 +2383,7 @@ array median( std::ostringstream msg; msg << "[median] axis " << axis << " is out of bounds for array with " << ndim << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } set_axes.insert(axis < 0 ? axis + ndim : axis); } @@ -2636,6 +2656,31 @@ array min( return min(a, std::vector{axis}, keepdims, s); } +std::tuple +minmax(const array& a, bool keepdims, StreamOrDevice s /* = {}*/) { + std::vector axes(a.ndim()); + std::iota(axes.begin(), axes.end(), 0); + return {min(a, axes, keepdims, s), max(a, axes, keepdims, s)}; +} + +std::tuple minmax( + const array& a, + const std::vector& axes, + bool keepdims /* = false */, + StreamOrDevice s /* = {}*/) { + return {min(a, axes, keepdims, s), max(a, axes, keepdims, s)}; +} + +std::tuple minmax( + const array& a, + int axis, + bool keepdims /* = false */, + StreamOrDevice s /* = {} */) { + return { + min(a, std::vector{axis}, keepdims, s), + max(a, std::vector{axis}, keepdims, s)}; +} + array argmin(const array& a, bool keepdims, StreamOrDevice s /* = {} */) { auto result = argmin(flatten(a, s), 0, true, s); if (keepdims) { @@ -2940,6 +2985,148 @@ array topk(const array& a, int k, int axis, StreamOrDevice s /* = {}*/) { return slice(a_partitioned, slice_starts, slice_ends, s); } +std::vector unique( + const array& a, + int size, + bool return_index /* = false */, + bool return_inverse /* = false */, + bool return_counts /* = false */, + const std::optional& fill_value /* = std::nullopt */, + StreamOrDevice s /* = {} */) { + // Validate args + if (size < 0) { + std::ostringstream msg; + msg << "[unique] Received negative size " << size << "."; + throw std::invalid_argument(msg.str()); + } + if (fill_value && fill_value->size() != 1) { + std::ostringstream msg; + msg << "[unique] Fill value must have one element, but got shape " + << fill_value->shape() << "."; + throw std::invalid_argument(msg.str()); + } + const auto flat = flatten(a, s); + const int n = flat.size(); + + // Handle the edge case of an empty array. + if (n == 0) { + // Without an element there is no default fill value. + if (size > 0 && !fill_value) { + throw std::invalid_argument( + "[unique] A fill value is required for an empty input with a" + " non-zero size."); + } + std::vector out; + out.push_back( + size == 0 ? flat + : full( + {size}, + astype(reshape(*fill_value, {}, s), flat.dtype(), s), + flat.dtype(), + s)); + if (return_index) { + out.push_back(zeros({size}, uint32, s)); + } + if (return_inverse) { + out.push_back(zeros(a.shape(), uint32, s)); + } + if (return_counts) { + out.push_back(zeros({size}, int32, s)); + } + return out; + } + + // Sort the array. The values stay differentiable, the permutation does not. + std::optional order; + if (return_index || return_inverse) { + order = stop_gradient(argsort(flat, 0, s), s); + } + const auto sorted = order ? take(flat, *order, 0, s) : sort(flat, 0, s); + + // Edge detection on the sorted array, true where a new unique + // value starts in the sorted array. + const auto boundary = concatenate( + {array({true}), + not_equal( + slice(sorted, {1}, {n}, s), slice(sorted, {0}, {n - 1}, s), s)}, + 0, + s); + + // Cumsum on boundary gives each sorted element the index of the unique + // value it belongs to. It indexes the output, so it is not differentiable. + const auto group = stop_gradient( + subtract( + cumsum(astype(boundary, uint32, s), 0, false, true, s), + array(1, uint32), + s), + s); + + // Use smallest element of the sorted array (index 0) as padding by default. + const auto fill = fill_value + ? astype(reshape(*fill_value, {}, s), flat.dtype(), s) + : slice(sorted, {0}, {1}, s); + + const int buffer_size = std::max(n, size); + // Scatter positions rather than values in the sorted array (64 bit values + // would fail to scatter on the GPU). + const auto slots = stop_gradient( + slice( + scatter_max( + zeros({buffer_size}, uint32, s), + group, + expand_dims( + where( + boundary, + add(arange(n, uint32, s), array(1, uint32), s), + array(0, uint32), + s), + 1, + s), + 0, + s), + {0}, + {size}, + s), + s); + const auto used = greater(slots, array(0, uint32), s); + const auto positions = + subtract(maximum(slots, array(1, uint32), s), array(1, uint32), s); + + // Build the output arrays. + std::vector out; + out.push_back(where(used, take(sorted, positions, 0, s), fill, s)); + if (return_index) { + // The sort is stable, so the first sorted position of a group holds the + // first occurrence in the input. Unused slots point at position zero, + // which pads with the index of the smallest unique value. + out.push_back(take(*order, positions, 0, s)); + } + if (return_inverse) { + // Clamp so that the indices stay inside a truncated output. Without a + // truncation every group index is already smaller than size. + const auto clamped = + minimum(group, array(std::max(size - 1, 0), uint32), s); + const auto inverse = scatter( + zeros({n}, uint32, s), *order, expand_dims(clamped, 1, s), 0, s); + out.push_back(reshape(inverse, a.shape(), s)); + } + // Padding entries count zero, so counts sum to the input size unless the + // output was truncated. + if (return_counts) { + out.push_back(slice( + scatter_add( + zeros({buffer_size}, int32, s), + group, + ones({n, 1}, int32, s), + 0, + s), + {0}, + {size}, + s)); + } + return out; +} + array logsumexp(const array& a, bool keepdims, StreamOrDevice s /* = {}*/) { std::vector axes(a.ndim()); std::iota(axes.begin(), axes.end(), 0); @@ -3144,14 +3331,13 @@ array floor_divide( const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); - if (issubdtype(dtype, inexact)) { - return floor(divide(a, b, s), s); - } - auto inputs = broadcast_arrays({astype(a, dtype, s), astype(b, dtype, s)}, s); auto shape = inputs[0].shape(); return array( - shape, dtype, std::make_shared(to_stream(s)), std::move(inputs)); + shape, + dtype, + std::make_shared(to_stream(s)), + std::move(inputs)); } array remainder(const array& a, const array& b, StreamOrDevice s /* = {} */) { @@ -3673,7 +3859,7 @@ array take( std::ostringstream msg; msg << "[take] Received invalid axis " << axis << " for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } // Check for valid take @@ -3718,7 +3904,7 @@ array take(const array& a, int index, int axis, StreamOrDevice s /* = {} */) { std::ostringstream msg; msg << "[take] Received invalid axis " << axis << " for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } // Check for valid take @@ -3727,8 +3913,9 @@ array take(const array& a, int index, int axis, StreamOrDevice s /* = {} */) { "[take] Cannot do a non-empty take from an array with zero elements."); } - // Handle negative axis + // Handle negative axis and index axis = axis < 0 ? a.ndim() + axis : axis; + index = index < 0 ? a.shape(axis) + index : index; Shape starts(a.ndim(), 0); Shape stops = a.shape(); @@ -4144,14 +4331,7 @@ array cumsum( bool inclusive /* = true*/, std::optional dtype /* = std::nullopt*/, StreamOrDevice s /* = {}*/) { - int ndim = a.ndim(); - if (axis >= ndim || axis < -ndim) { - std::ostringstream msg; - msg << "[cumsum] Axis " << axis << " is out of bounds for array with " - << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); - } - axis = (axis + a.ndim()) % a.ndim(); + axis = normalize_axis_index(axis, a.ndim(), "[cumsum] "); auto x = dtype ? astype(a, *dtype, s) : a; auto out_type = x.dtype() == bool_ ? int32 : x.dtype(); return array( @@ -4179,14 +4359,7 @@ array cumprod( bool inclusive /* = true*/, std::optional dtype /* = std::nullopt*/, StreamOrDevice s /* = {}*/) { - int ndim = a.ndim(); - if (axis >= ndim || axis < -ndim) { - std::ostringstream msg; - msg << "[cumprod] Axis " << axis << " is out of bounds for array with " - << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); - } - axis = (axis + a.ndim()) % a.ndim(); + axis = normalize_axis_index(axis, a.ndim(), "[cumprod] "); auto x = dtype ? astype(a, *dtype, s) : a; return array( x.shape(), @@ -4211,14 +4384,7 @@ array cummax( bool reverse /* = false*/, bool inclusive /* = true*/, StreamOrDevice s /* = {}*/) { - int ndim = a.ndim(); - if (axis >= ndim || axis < -ndim) { - std::ostringstream msg; - msg << "[cummax] Axis " << axis << " is out of bounds for array with " - << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); - } - axis = (axis + a.ndim()) % a.ndim(); + axis = normalize_axis_index(axis, a.ndim(), "[cummax] "); return array( a.shape(), a.dtype(), @@ -4241,14 +4407,7 @@ array cummin( bool reverse /* = false*/, bool inclusive /* = true*/, StreamOrDevice s /* = {}*/) { - int ndim = a.ndim(); - if (axis >= ndim || axis < -ndim) { - std::ostringstream msg; - msg << "[cummin] Axis " << axis << " is out of bounds for array with " - << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); - } - axis = (axis + a.ndim()) % a.ndim(); + axis = normalize_axis_index(axis, a.ndim(), "[cummin] "); return array( a.shape(), a.dtype(), @@ -4273,7 +4432,7 @@ array diff( int ndim = static_cast(a.ndim()); int ax = axis < 0 ? axis + ndim : axis; if (ax < 0 || ax >= ndim) { - throw std::invalid_argument("[diff] Axis is out of bounds for the array."); + throw std::out_of_range("[diff] Axis is out of bounds for the array."); } if (n < 0) { throw std::invalid_argument("[diff] Order `n` must be non-negative."); @@ -4298,20 +4457,14 @@ array logcumsumexp( bool reverse /* = false*/, bool inclusive /* = true*/, StreamOrDevice s /* = {}*/) { - int ndim = a.ndim(); - if (axis >= ndim || axis < -ndim) { - std::ostringstream msg; - msg << "[logcumsumexp] Axis " << axis << " is out of bounds for array with " - << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); - } - axis = (axis + a.ndim()) % a.ndim(); + axis = normalize_axis_index(axis, a.ndim(), "[logcumsumexp] "); + auto out_type = at_least_float(a.dtype()); return array( a.shape(), - a.dtype(), + out_type, std::make_shared( to_stream(s), Scan::ReduceType::LogAddExp, axis, reverse, inclusive), - {a}); + {astype(a, out_type, s)}); } array logcumsumexp( @@ -4953,6 +5106,12 @@ array qqmm( // validate inputs validate_qqmm_inputs( x, w, scales_w, group_size, bits, global_scale_x, global_scale_w, qmode); + // The CPU kernel has no global scale input. Refuse rather than ignore it. + if ((global_scale_x.has_value() || global_scale_w.has_value()) && + stream.device != Device::gpu) { + throw std::invalid_argument( + "[qqmm] Global scale is only supported on the GPU."); + } // validate and extract shapes auto [w_inner_dims, w_outer_dims] = extract_qqmm_dims(x, w, scales_w, group_size, bits); @@ -5042,10 +5201,10 @@ affine_quantize(const array& w, int group_size, int bits, StreamOrDevice s_) { throw std::invalid_argument(msg.str()); } - if (bits < 2 || bits > 8 || bits == 7) { + if (bits < 1 || bits > 8 || bits == 7) { std::ostringstream msg; msg << "[quantize] The requested number of bits " << bits - << " is not supported. The supported bits are 2, 3, 4, 5, 6 and 8."; + << " is not supported. The supported bits are 1, 2, 3, 4, 5, 6 and 8."; throw std::invalid_argument(msg.str()); } @@ -5066,14 +5225,22 @@ affine_quantize(const array& w, int group_size, int bits, StreamOrDevice s_) { w_max = astype(w_max, float32, s); w_min = astype(w_min, float32, s); - array mask = greater(abs(w_min, s), abs(w_max, s), s); - array scales = - maximum(divide(subtract(w_max, w_min, s), n_bins, s), eps, s); - scales = where(mask, scales, negative(scales, s), s); - array edge = where(mask, w_min, w_max, s); - array q0 = round(divide(edge, scales, s), s); - scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales); - array biases = where(equal(q0, zero, s), zero, edge, s); + array scales(0, float32); + array biases(0, float32); + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scales = maximum(subtract(w_max, w_min, s), eps, s); + biases = w_min; + } else { + array mask = greater(abs(w_min, s), abs(w_max, s), s); + scales = maximum(divide(subtract(w_max, w_min, s), n_bins, s), eps, s); + scales = where(mask, scales, negative(scales, s), s); + array edge = where(mask, w_min, w_max, s); + array q0 = round(divide(edge, scales, s), s); + scales = where(not_equal(q0, zero, s), divide(edge, q0, s), scales); + biases = where(equal(q0, zero, s), zero, edge, s); + } packed_w = pack_and_quantize(packed_w, scales, biases, bits, s); @@ -5567,9 +5734,14 @@ array gather_qmm( std::optional group_size_ /* = std::nullopt */, std::optional bits_ /* = std::nullopt */, const std::string& mode /* = "affine" */, + const std::optional& global_scale /* = std::nullopt */, bool sorted_indices /* = false */, StreamOrDevice s /* = {} */) { if (!lhs_indices_ && !rhs_indices_) { + if (global_scale) { + throw std::invalid_argument( + "[gather_qmm] Global scale is not supported without indices."); + } return quantized_matmul( x, w, scales, biases, transpose, group_size_, bits_, mode, s); } @@ -5580,6 +5752,32 @@ array gather_qmm( quantization_params_from_mode(qmode, group_size_, bits_); auto [w_inner_dims, w_outer_dims] = extract_quantized_matmul_dims( "gather_qmm", x, w, scales, biases, transpose, group_size, bits); + if (global_scale) { + if (qmode != QuantizationMode::Nvfp4) { + throw std::invalid_argument( + "[gather_qmm] Global scale is only supported for 'nvfp4' " + "quantization mode."); + } + if (global_scale->dtype() != float32) { + std::ostringstream msg; + msg << "[gather_qmm] Global scale must have dtype float32 but got " + << global_scale->dtype() << "."; + throw std::invalid_argument(msg.str()); + } + // One scale per expert, so it matches the batch dimensions of w. + Shape expected(w.shape().begin(), w.shape().end() - 2); + if (global_scale->shape() != expected) { + std::ostringstream msg; + msg << "[gather_qmm] Global scale must have one entry per expert with " + << "shape " << expected << " but got " << global_scale->shape() + << "."; + throw std::invalid_argument(msg.str()); + } + if (to_stream(s).device != Device::gpu) { + throw std::invalid_argument( + "[gather_qmm] Global scale is only supported on the GPU."); + } + } if (qmode == QuantizationMode::Affine) { out_type = promote_types(x.dtype(), out_type); } else { @@ -5613,12 +5811,12 @@ array gather_qmm( std::move(lhs_indices), std::move(rhs_indices)}; } else { - inputs = { - astype(x, out_type, s), - std::move(w), - std::move(scales), - std::move(lhs_indices), - std::move(rhs_indices)}; + inputs = {astype(x, out_type, s), std::move(w), std::move(scales)}; + if (global_scale) { + inputs.push_back(*global_scale); + } + inputs.push_back(std::move(lhs_indices)); + inputs.push_back(std::move(rhs_indices)); } return array( std::move(out_shape), @@ -5680,7 +5878,13 @@ array gather_qqmm( return array( std::move(out_shape), x.dtype(), - std::make_shared(stream, group_size, bits, qmode), + std::make_shared( + stream, + group_size, + bits, + qmode, + sorted_indices && !rhs_indices_, + sorted_indices && !lhs_indices_), std::move(inputs)); } @@ -5796,7 +6000,7 @@ array vecdot( } int ax = axis < 0 ? axis + a.ndim() : axis; if (ax < 0 || ax >= a.ndim()) { - throw std::invalid_argument("[vecdot] axis is out of bounds."); + throw std::out_of_range("[vecdot] axis is out of bounds."); } if (axis < 0 ? axis + b.ndim() != ax : axis >= b.ndim()) { throw std::invalid_argument("[vecdot] axis is out of bounds."); @@ -6677,7 +6881,7 @@ array roll( std::ostringstream msg; msg << "[roll] Invalid axis " << axes[i] << " for array with " << a.ndim() << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } auto sh = shift[i]; diff --git a/mlx/ops.h b/mlx/ops.h index f597753b1e..017fcbd706 100644 --- a/mlx/ops.h +++ b/mlx/ops.h @@ -381,6 +381,9 @@ inline array transpose( return transpose(a, std::vector(axes), s); } +/** Permutes last two dimensions of an array. */ +MLX_API array matrix_transpose(const array& a, StreamOrDevice s = {}); + /** Swap two axes of an array. */ MLX_API array swapaxes(const array& a, int axis1, int axis2, StreamOrDevice s = {}); @@ -783,6 +786,23 @@ min(const array& a, MLX_API array min(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {}); +MLX_API std::tuple +minmax(const array& a, bool keepdims, StreamOrDevice s = {}); +inline std::tuple minmax(const array& a, StreamOrDevice s = {}) { + return minmax(a, false, to_stream(s)); +} + +/** The minimum and maximum of the elements of an array along the given axes. */ +MLX_API std::tuple minmax( + const array& a, + const std::vector& axes, + bool keepdims = false, + StreamOrDevice s = {}); + +/** The minimum and maximum of the elements of an array along the given axis. */ +MLX_API std::tuple +minmax(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {}); + /** Returns the Hanning window of size M. */ MLX_API array hanning(int M, StreamOrDevice s = {}); @@ -878,6 +898,27 @@ MLX_API array topk(const array& a, int k, StreamOrDevice s = {}); /** Returns topk elements of the array along a given axis. */ MLX_API array topk(const array& a, int k, int axis, StreamOrDevice s = {}); +/** + * Returns the sorted unique elements of the flattened array, and optionally + * the index of the first occurrence of each, the inverse indices and the + * counts. The output has the given size, and + * is truncated if ``size`` is smaller than the number of unique values. + * If ``size`` is larger, the result is padded with ``fill_value``, or the + * first of the sorted unique values if no fill value is provided. An empty + * input has none, so it throws unless ``size`` is zero or a fill value is + * given. + * A truncated output loses the counts of the values it drops, and its inverse + * indices are clamped to the last entry. + */ +MLX_API std::vector unique( + const array& a, + int size, + bool return_index = false, + bool return_inverse = false, + bool return_counts = false, + const std::optional& fill_value = std::nullopt, + StreamOrDevice s = {}); + /** Cumulative logsumexp of an array. */ MLX_API array logcumsumexp( const array& a, @@ -1626,6 +1667,7 @@ MLX_API array gather_qmm( std::optional group_size = std::nullopt, std::optional bits = std::nullopt, const std::string& mode = "affine", + const std::optional& global_scale = std::nullopt, bool sorted_indices = false, StreamOrDevice s = {}); diff --git a/mlx/primitives.cpp b/mlx/primitives.cpp index 9a1771394e..b6f603dd7a 100644 --- a/mlx/primitives.cpp +++ b/mlx/primitives.cpp @@ -390,7 +390,10 @@ std::vector ArcCos::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcCos::jvp( @@ -418,7 +421,10 @@ std::vector ArcCosh::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcCosh::jvp( @@ -428,6 +434,14 @@ std::vector ArcCosh::jvp( assert(primals.size() == 1); assert(argnums.size() == 1); array one = array(1., primals[0].dtype()); + if (issubdtype(primals[0].dtype(), complexfloating)) { + // rsqrt(x^2 - 1) has the wrong sign for complex x with Re(x) < 0. + array d = multiply( + rsqrt(subtract(primals[0], one, stream()), stream()), + rsqrt(add(primals[0], one, stream()), stream()), + stream()); + return {multiply(tangents[0], d, stream())}; + } array t = subtract(square(primals[0], stream()), one, stream()); return {multiply(tangents[0], rsqrt(t, stream()), stream())}; } @@ -445,7 +459,10 @@ std::vector ArcSin::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcSin::jvp( @@ -472,7 +489,10 @@ std::vector ArcSinh::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcSinh::jvp( @@ -499,7 +519,10 @@ std::vector ArcTan::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcTan::jvp( @@ -587,7 +610,10 @@ std::vector ArcTanh::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return jvp(primals, cotangents, argnums); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector ArcTanh::jvp( @@ -1477,7 +1503,7 @@ std::vector Convolution::vjp( int64_t in_size = dilate_size(in.shape(1 + i), input_dilation_[i]); int64_t out_size = dilate_size(cotan.shape(1 + i), kernel_strides_[i]); - padding_hi[i] = safe_cast(in_size - out_size + padding_hi_[i], "conv"); + padding_hi[i] = safe_cast(in_size - out_size + padding_lo_[i], "conv"); } // Check for negative padding @@ -1489,13 +1515,21 @@ std::vector Convolution::vjp( has_neg_padding |= (pd < 0); } + // Negative padding is cropped from the output below + std::vector conv_padding_lo = padding_lo; + std::vector conv_padding_hi = padding_hi; + for (int i = 0; i < conv_padding_lo.size(); ++i) { + conv_padding_lo[i] = std::max(conv_padding_lo[i], 0); + conv_padding_hi[i] = std::max(conv_padding_hi[i], 0); + } + auto wt_trans = group_transpose(wt, 0, 1, -1); auto grad = conv_general( /* const array& input = */ cotan, /* const array& weight = */ wt_trans, /* std::vector stride = */ input_dilation_, - /* std::vector padding_lo = */ padding_lo, - /* std::vector padding_hi = */ padding_hi, + /* std::vector padding_lo = */ conv_padding_lo, + /* std::vector padding_hi = */ conv_padding_hi, /* std::vector kernel_dilation = */ kernel_dilation_, /* std::vector input_dilation = */ kernel_strides_, /* int groups = */ groups_, @@ -1693,7 +1727,10 @@ std::vector Cos::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - return {jvp(primals, cotangents, argnums)}; + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). + return {conjugate( + jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0], + stream())}; } std::vector Cos::jvp( @@ -2192,12 +2229,6 @@ std::vector Flatten::output_shapes(const std::vector& inputs) { return {Flatten::output_shape(inputs[0], start_axis_, end_axis_)}; } -bool FFT::is_equivalent(const Primitive& other) const { - const FFT& r_other = static_cast(other); - return axes_ == r_other.axes_ && inverse_ == r_other.inverse_ && - real_ == r_other.real_; -} - std::vector Unflatten::vjp( const std::vector&, const std::vector& cotangents, @@ -2263,13 +2294,13 @@ std::pair, std::vector> FFT::vmap( // Only the last transformed axis changes size in a real transform if (real_) { auto n = out_shape[fft_axes.back()]; - out_shape[fft_axes.back()] = inverse_ ? 2 * (n - 1) : n / 2 + 1; + out_shape[fft_axes.back()] = inverse_ ? 2 * (n - 1) + odd_out_ : n / 2 + 1; } return { {array( out_shape, real_ && inverse_ ? float32 : complex64, - std::make_shared(stream(), fft_axes, inverse_, real_), + std::make_shared(stream(), fft_axes, inverse_, real_, odd_out_), {in})}, {ax}}; } @@ -2380,6 +2411,12 @@ std::vector FFT::jvp( } } +bool FFT::is_equivalent(const Primitive& other) const { + const FFT& r_other = static_cast(other); + return axes_ == r_other.axes_ && inverse_ == r_other.inverse_ && + real_ == r_other.real_ && odd_out_ == r_other.odd_out_; +} + std::vector Floor::vjp( const std::vector& primals, const std::vector& cotangents, @@ -2405,6 +2442,32 @@ std::pair, std::vector> Floor::vmap( return {{floor(inputs[0], stream())}, axes}; } +std::vector FloorDivide::vjp( + const std::vector& primals, + const std::vector&, + const std::vector& argnums, + const std::vector&) { + std::vector vjps; + for (auto arg : argnums) { + vjps.push_back(zeros_like(primals[arg], stream())); + } + return vjps; +} + +std::vector FloorDivide::jvp( + const std::vector& primals, + const std::vector&, + const std::vector&) { + return {zeros_like(primals[0], stream())}; +} + +std::pair, std::vector> FloorDivide::vmap( + const std::vector& inputs, + const std::vector& axes) { + auto [a, b, to_ax] = vmap_binary_op(inputs, axes, stream()); + return {{floor_divide(a, b, stream())}, {to_ax}}; +} + std::vector Full::vjp( const std::vector& primals, const std::vector& cotangents, @@ -3329,36 +3392,54 @@ std::vector Pad::vjp( const std::vector& cotangents, const std::vector& argnums, const std::vector&) { - assert(argnums.size() == 1 && argnums[0] == 0); - auto& cotan = cotangents[0]; Shape start(cotan.ndim(), 0); auto stop = cotan.shape(); - for (auto i : axes_) { - start[i] = low_pad_size_[i]; - stop[i] -= high_pad_size_[i]; + for (size_t i = 0; i < axes_.size(); i++) { + auto ax = normalize_axis_index(axes_[i], cotan.ndim(), "[pad] "); + start[ax] = low_pad_size_[i]; + stop[ax] -= high_pad_size_[i]; } - auto out = slice(cotan, start, stop, stream()); + auto interior = slice(cotan, start, stop, stream()); - return {out}; + auto value_grad = [&]() { + // Sum only the padded positions, a difference of sums cancels in fp16 + auto padded = slice_update( + cotan, zeros_like(interior, stream()), start, stop, stream()); + return reshape(sum(padded, false, stream()), primals[1].shape(), stream()); + }; + + if (argnums == std::vector{0}) { + return {interior}; + } + if (argnums == std::vector{1}) { + return {value_grad()}; + } + assert((argnums == std::vector{0, 1})); + return {interior, value_grad()}; } std::vector Pad::jvp( const std::vector& primals, const std::vector& tangents, const std::vector& argnums) { - assert(argnums.size() == 1 && argnums[0] == 0); + assert(tangents.size() == argnums.size()); - return { - pad(tangents[0], - axes_, - low_pad_size_, - high_pad_size_, - array(0, tangents[0].dtype()), - "constant", - stream())}; + auto pad_tangent = [&](const array& a, const array& v) { + return pad( + a, axes_, low_pad_size_, high_pad_size_, v, "constant", stream()); + }; + + if (argnums == std::vector{0}) { + return {pad_tangent(tangents[0], zeros_like(primals[1], stream()))}; + } + if (argnums == std::vector{1}) { + return {pad_tangent(zeros_like(primals[0], stream()), tangents[0])}; + } + assert((argnums == std::vector{0, 1})); + return {pad_tangent(tangents[0], tangents[1])}; } std::pair, std::vector> Pad::vmap( @@ -3732,9 +3813,13 @@ std::vector GatherQMM::vjp( auto biases = (mode_ == QuantizationMode::Affine) ? std::optional(primals[3]) : std::nullopt; + auto global_scale = (mode_ != QuantizationMode::Affine && primals.size() == 6) + ? std::optional(primals[3]) + : std::nullopt; int M = cotan.shape(-2); int K = x.shape(-1); + int first_index_arg = primals.size() - 2; bool sorted = left_sorted_ || right_sorted_; bool no_broadcast = rhs_indices.size() * M * K == x.size(); @@ -3754,6 +3839,7 @@ std::vector GatherQMM::vjp( group_size_, bits_, quantization_mode_to_string(mode_), + global_scale, sorted, stream()); if (sorted && no_broadcast) { @@ -3772,15 +3858,18 @@ std::vector GatherQMM::vjp( } // gradient wrt to the indices is undefined - else if (arg > 3) { + else if (arg >= first_index_arg) { throw std::runtime_error( "[GatherQMM::vjp] cannot compute the gradient wrt the indices."); } - // gradient wrt to w_q, scales or biases + // gradient wrt to w_q, scales, biases or the global scale else if (arg == 1) { throw std::runtime_error( "[GatherQMM::vjp] no gradient wrt the quantized weights."); + } else if (global_scale && arg == 3) { + throw std::runtime_error( + "[GatherQMM::vjp] no gradient wrt the global scale."); } else { if (mode_ != QuantizationMode::Affine) { std::ostringstream msg; @@ -3852,8 +3941,7 @@ bool GatherQMM::is_equivalent(const Primitive& other) const { std::vector GatherQMM::output_shapes(const std::vector& inputs) { const auto& x = inputs[0]; const auto& w = inputs[1]; - const auto& lhs_indices = - (mode_ == QuantizationMode::Affine) ? inputs[4] : inputs[3]; + const auto& lhs_indices = inputs[inputs.size() - 2]; int w_outer = transpose_ ? w.shape(-2) : w.shape(-1) * 32 / bits_; auto out_shape = lhs_indices.shape(); out_shape.push_back(x.shape(-2)); @@ -4435,6 +4523,49 @@ std::vector Scan::jvp( if (reduce_type_ == Scan::Sum) { return {cumsum(tangents[0], axis_, reverse_, inclusive_, stream())}; + } else if (reduce_type_ == Scan::LogAddExp) { + if (issubdtype(tangents[0].dtype(), complexfloating)) { + throw std::invalid_argument( + "[logcumsumexp] JVP is not supported for complex inputs."); + } + auto x = primals[0]; + auto t = tangents[0]; + auto y = logcumsumexp(x, axis_, reverse_, inclusive_, stream()); + + auto zero = zeros({1}, t.dtype(), stream()); + auto t_min = array(finfo(t.dtype()).min, t.dtype()); + auto log_abs_t = log(abs(t, stream()), stream()); + auto log_t_positive = + where(greater(t, zero, stream()), log_abs_t, t_min, stream()); + auto log_t_negative = + where(less(t, zero, stream()), log_abs_t, t_min, stream()); + + auto out_pos = exp(subtract( + logcumsumexp( + add(log_t_positive, x, stream()), + axis_, + reverse_, + inclusive_, + stream()), + y, + stream())); + + auto out_neg = exp(subtract( + logcumsumexp( + add(log_t_negative, x, stream()), + axis_, + reverse_, + inclusive_, + stream()), + y, + stream())); + + return {where( + isneginf(y, stream()), + zeros_like(y, stream()), + subtract(out_pos, out_neg, stream()), + stream())}; + } else { throw std::runtime_error( "JVP is not implemented for cumulative prod/min/max"); @@ -4602,14 +4733,19 @@ std::pair, std::vector> Scatter::vmap( // Clone updates along the vmap dimension so they can be applied to each // source tensor in the vmap. auto& updates = inputs.back(); + int idx_ndim = static_cast(inputs[1].ndim()); + int upd_src_ax = idx_ndim + src_ax; if (vmap_axes.back() < 0) { - updates = expand_dims( - updates, {0, static_cast(inputs[1].ndim())}, stream()); + updates = expand_dims(updates, {0, upd_src_ax}, stream()); updates = repeat(updates, vmap_size, 0, stream()); } else { - updates = - expand_dims(updates, static_cast(inputs[1].ndim()), stream()); - updates = moveaxis(updates, vmap_axes.back(), 0, stream()); + int upd_vmap_ax = vmap_axes.back(); + // expand_dims shifts any axis at or after the insertion point + if (upd_vmap_ax >= upd_src_ax) { + upd_vmap_ax++; + } + updates = expand_dims(updates, upd_src_ax, stream()); + updates = moveaxis(updates, upd_vmap_ax, 0, stream()); } } @@ -5593,16 +5729,17 @@ std::vector Sqrt::vjp( assert(primals.size() == 1); assert(cotangents.size() == 1); auto dtype = primals[0].dtype(); + // The vjp conjugates the jvp's multiplier (a no-op for real inputs). if (recip_) { auto one_over_x_root_x = divide(outputs[0], primals[0], stream()); return {multiply( multiply(array(-0.5, dtype), cotangents[0], stream()), - one_over_x_root_x, + conjugate(one_over_x_root_x, stream()), stream())}; } else { return {divide( multiply(array(0.5, dtype), cotangents[0], stream()), - outputs[0], + conjugate(outputs[0], stream()), stream())}; } } @@ -5611,10 +5748,21 @@ std::vector Sqrt::jvp( const std::vector& primals, const std::vector& tangents, const std::vector& argnums) { + assert(primals.size() == 1); + assert(tangents.size() == 1); + auto dtype = primals[0].dtype(); if (recip_) { - return vjp(primals, tangents, argnums, {rsqrt(primals[0], stream())}); + auto one_over_x_root_x = + divide(rsqrt(primals[0], stream()), primals[0], stream()); + return {multiply( + multiply(array(-0.5, dtype), tangents[0], stream()), + one_over_x_root_x, + stream())}; } else { - return vjp(primals, tangents, argnums, {sqrt(primals[0], stream())}); + return {divide( + multiply(array(0.5, dtype), tangents[0], stream()), + sqrt(primals[0], stream()), + stream())}; } } @@ -6253,7 +6401,15 @@ std::pair, std::vector> View::vmap( const std::vector& axes) { assert(inputs.size() == 1); assert(axes.size() == 1); - return {{view(inputs[0], dtype_, stream())}, axes}; + auto a = inputs[0]; + int ax = axes[0]; + // Changing the item size resizes the last axis, so move the vmapped axis + if (ax == static_cast(a.ndim()) - 1 && + size_of(a.dtype()) != size_of(dtype_)) { + a = moveaxis(a, ax, 0, stream()); + ax = 0; + } + return {{view(a, dtype_, stream())}, {ax}}; } const char* View::name() const { diff --git a/mlx/primitives.h b/mlx/primitives.h index 0cfc71bf04..68995b7503 100644 --- a/mlx/primitives.h +++ b/mlx/primitives.h @@ -443,7 +443,7 @@ class AsStrided : public UnaryPrimitive { Strides strides_; size_t offset_; - void eval(const std::vector& inputs, array& out); + void eval(const array& in, array& out); }; class BitwiseBinary : public UnaryPrimitive { @@ -1079,8 +1079,13 @@ class FFT : public UnaryPrimitive { Stream stream, const std::vector& axes, bool inverse, - bool real) - : UnaryPrimitive(stream), axes_(axes), inverse_(inverse), real_(real) {} + bool real, + bool odd_out = false) + : UnaryPrimitive(stream), + axes_(axes), + inverse_(inverse), + real_(real), + odd_out_(odd_out) {} void eval_cpu(const std::vector& inputs, array& out) override; void eval_gpu(const std::vector& inputs, array& out) override; @@ -1091,13 +1096,16 @@ class FFT : public UnaryPrimitive { bool is_equivalent(const Primitive& other) const override; auto state() const { - return std::make_tuple(axes_, inverse_, real_); + return std::make_tuple(axes_, inverse_, real_, odd_out_); } private: std::vector axes_; bool inverse_; bool real_; + // The output length of an inverse real transform is not recoverable from + // the input shape. + bool odd_out_; }; class Flatten : public UnaryPrimitive { @@ -1139,6 +1147,20 @@ class Floor : public UnaryPrimitive { DEFINE_INPUT_OUTPUT_SHAPE() }; +class FloorDivide : public UnaryPrimitive { + public: + explicit FloorDivide(Stream stream) : UnaryPrimitive(stream) {} + + void eval_cpu(const std::vector& inputs, array& out) override; + void eval_gpu(const std::vector& inputs, array& out) override; + + DEFINE_VMAP() + DEFINE_GRADS() + DEFINE_NAME(FloorDivide) + DEFINE_DEFAULT_IS_EQUIVALENT() + DEFINE_INPUT_OUTPUT_SHAPE() +}; + class Full : public UnaryPrimitive { public: explicit Full(Stream stream) : UnaryPrimitive(stream) {} @@ -1888,6 +1910,7 @@ class Scan : public UnaryPrimitive { DEFINE_VMAP() DEFINE_GRADS(); + DEFINE_INPUT_OUTPUT_SHAPE() const char* name() const override { switch (reduce_type_) { diff --git a/mlx/random.cpp b/mlx/random.cpp index 2932b3eaf8..280d55c350 100644 --- a/mlx/random.cpp +++ b/mlx/random.cpp @@ -183,6 +183,19 @@ array normal( const std::optional& scale, const std::optional& key, StreamOrDevice s /* = {} */) { + auto out_shape = shape; + if (loc) { + out_shape = broadcast_shapes(out_shape, loc->shape()); + } + if (scale) { + out_shape = broadcast_shapes(out_shape, scale->shape()); + } + if (out_shape != shape) { + std::ostringstream msg; + msg << "[normal] Cannot generate random values of shape " << shape + << " from broadcasted shape " << out_shape << "."; + throw std::invalid_argument(msg.str()); + } if (dtype == complex64) { return complex_normal(shape, loc, scale, key, s); } else if (!issubdtype(dtype, floating)) { @@ -383,7 +396,7 @@ int get_valid_axis(int axis, int ndim) { std::ostringstream msg; msg << "[categorical] Invalid axis " << axis << " for logits with " << ndim << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } return ax; } diff --git a/mlx/scheduler.cpp b/mlx/scheduler.cpp index 572e236bbe..1516f8ef60 100644 --- a/mlx/scheduler.cpp +++ b/mlx/scheduler.cpp @@ -39,6 +39,20 @@ void clear_streams() { namespace scheduler { +namespace { + +thread_local int defer_stream_errors = 0; + +} // namespace + +DeferStreamErrors::DeferStreamErrors() { + ++defer_stream_errors; +} + +DeferStreamErrors::~DeferStreamErrors() { + --defer_stream_errors; +} + struct StreamThread { std::mutex mtx; std::queue> q; @@ -76,7 +90,7 @@ struct StreamThread { } void enqueue(std::function f) { - if (is_main_thread()) { + if (is_main_thread() && defer_stream_errors == 0) { error.check(); } { diff --git a/mlx/scheduler.h b/mlx/scheduler.h index 7bce5a9fe6..c05765e433 100644 --- a/mlx/scheduler.h +++ b/mlx/scheduler.h @@ -98,6 +98,17 @@ inline void check_error(Stream s) { scheduler().check_error(s); } +// While an object of this class lives, enqueue on this thread does not throw +// the error that an earlier stream task stored. synchronize throws it later. +// async_eval uses it so that it never throws a stream task error. +class MLX_API DeferStreamErrors { + public: + DeferStreamErrors(); + ~DeferStreamErrors(); + DeferStreamErrors(const DeferStreamErrors&) = delete; + DeferStreamErrors& operator=(const DeferStreamErrors&) = delete; +}; + inline int n_active_tasks() { return scheduler().n_active_tasks(); } diff --git a/mlx/stream.cpp b/mlx/stream.cpp index b78ee67d67..902015cbf0 100644 --- a/mlx/stream.cpp +++ b/mlx/stream.cpp @@ -50,6 +50,10 @@ Stream default_stream(Device d) { return s.value(); } +std::optional peek_default_stream(Device d) { + return default_stream_storage(d); +} + void set_default_stream(Stream s) { if (!gpu::is_available() && s.device == Device::gpu) { throw std::invalid_argument( diff --git a/mlx/stream.h b/mlx/stream.h index 3099ee2682..331af60a61 100644 --- a/mlx/stream.h +++ b/mlx/stream.h @@ -2,6 +2,7 @@ #pragma once +#include #include #include @@ -29,6 +30,9 @@ struct MLX_API ThreadLocalStream : public Stream { /** Get the default stream of current thread for the given device. */ MLX_API Stream default_stream(Device d); +/** Get the default stream of current thread if it exists. */ +MLX_API std::optional peek_default_stream(Device d); + /** Make the stream the default for its device on current thread. */ MLX_API void set_default_stream(Stream s); diff --git a/mlx/transforms.cpp b/mlx/transforms.cpp index 694bca53d8..70dbe1e246 100644 --- a/mlx/transforms.cpp +++ b/mlx/transforms.cpp @@ -80,17 +80,23 @@ thread_local int detail::RetainGraph::tracing_counter{0}; array eval_impl(std::vector outputs, bool async) { std::deque tape; - // Make an effort to choose a good output stream - Stream stream = default_stream(default_device()); - for (auto& o : outputs) { - if (o.status() == array::Status::unscheduled && o.has_primitive()) { - stream = o.primitive().stream(); - break; + // Make an effort to choose a good output stream, and only create the default + // stream when there is no other choice. + Stream stream = [&outputs]() { + for (auto& o : outputs) { + if (o.status() == array::Status::unscheduled && o.has_primitive()) { + return o.primitive().stream(); + } } - } + return default_stream(default_device()); + }(); - // Map of array id that needs fence and stream it's computed on - std::unordered_map> needs_fence; + struct FenceInfo { + int stream_index; + bool cross_device; + uint32_t value{0}; + }; + std::unordered_map needs_fence; auto synchronizer = array( {}, bool_, std::make_shared(stream), std::move(outputs)); @@ -146,9 +152,9 @@ array eval_impl(std::vector outputs, bool async) { a.primitive().stream().device != in.primitive().stream().device; auto [it, inserted] = needs_fence.emplace( in.id(), - std::make_pair(in.primitive().stream().index, device_switch)); + FenceInfo{in.primitive().stream().index, device_switch}); if (!inserted) { - it->second.second |= device_switch; + it->second.cross_device |= device_switch; } } } @@ -251,7 +257,8 @@ array eval_impl(std::vector outputs, bool async) { // Use fence to wait within a single eval // Get the input array's stream fence and wait on the // output arrays stream - fences[it->second.first].wait(stream, in); + auto& info = it->second; + fences.at(info.stream_index).wait(stream, in, info.value); } else if (in.event().valid()) { if (in.event().is_signaled()) { in.detach_event(); @@ -291,7 +298,8 @@ array eval_impl(std::vector outputs, bool async) { if (it == fences.end()) { it = fences.emplace(stream.index, Fence{stream}).first; } - it->second.update(stream, a, nf->second.second); + nf->second.value = + it->second.update(stream, a, nf->second.cross_device); } }; @@ -324,6 +332,15 @@ array eval_impl(std::vector outputs, bool async) { } catch (...) { } } + // Commit GPU streams before the wait. + for (auto& s : open_streams) { + if (s.device == Device::gpu) { + try { + gpu::finalize(s); + } catch (...) { + } + } + } for (auto& s : open_streams) { try { synchronize(s); @@ -358,6 +375,9 @@ void async_eval(std::vector outputs) { return; } + // A stream task can fail while async_eval still enqueues later tasks. + // synchronize raises that error, not async_eval. + scheduler::DeferStreamErrors defer; eval_impl(std::move(outputs), true); } diff --git a/mlx/types/complex.h b/mlx/types/complex.h index 51101cc97b..ee1af4dfd5 100644 --- a/mlx/types/complex.h +++ b/mlx/types/complex.h @@ -45,6 +45,11 @@ struct complex64_t : public std::complex { operator float() const { return real(); }; + + // Explicit, so int casts still go through operator float + explicit operator bool() const { + return real() != 0 || imag() != 0; + }; }; inline bool operator>=(const complex64_t& a, const complex64_t& b) { @@ -106,8 +111,23 @@ inline complex64_t operator-(const complex64_t& v) { complex_binop_helper(_op_, _operator_, float16_t) \ complex_binop_helper(_op_, _operator_, bfloat16_t) \ complex_binop_helper(_op_, _operator_, float) -// clang-format on complex_binop(+, operator+) +template +constexpr bool is_complex = false; + +template +constexpr bool is_complex().real())>> = true; +// clang-format on + +template +inline bool isnan(T v) { + if constexpr (is_complex) { + return std::isnan(std::real(v)) || std::isnan(std::imag(v)); + } else { + return std::isnan(v); + } +} + } // namespace mlx::core diff --git a/mlx/types/half_types.h b/mlx/types/half_types.h index 560f737359..aa1e56690a 100644 --- a/mlx/types/half_types.h +++ b/mlx/types/half_types.h @@ -56,13 +56,6 @@ fp16_bf16_binop_helper(/, operator/) #endif -template -constexpr bool is_complex = false; - -template -constexpr bool is_complex().real())>> = - true; - template constexpr bool is_signed_v = std::is_signed_v || std::is_same_v || std::is_same_v; diff --git a/mlx/utils.cpp b/mlx/utils.cpp index 4e29e8847b..07130fa690 100644 --- a/mlx/utils.cpp +++ b/mlx/utils.cpp @@ -179,7 +179,7 @@ int normalize_axis_index( std::ostringstream msg; msg << msg_prefix << "Axis " << axis << " is out of bounds for array with " << ndim << " dimensions."; - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } return axis < 0 ? axis + ndim : axis; } diff --git a/mlx/utils.h b/mlx/utils.h index 0c62ba30d9..4b7e6d12d9 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "mlx/api.h" @@ -28,7 +29,9 @@ MLX_API Stream to_stream(StreamOrDevice s, Device default_); struct StreamContext { public: - StreamContext(StreamOrDevice s) : _stream(default_stream(default_device())) { + StreamContext(StreamOrDevice s) + : _stream(default_stream(default_device())), + _owner(std::this_thread::get_id()) { if (std::holds_alternative(s)) { throw std::runtime_error( "[StreamContext] Invalid argument, please specify a stream or device."); @@ -38,13 +41,21 @@ struct StreamContext { set_default_stream(_s); } - ~StreamContext() { + // noexcept(false) so the thread check below can throw. A destructor that + // throws while another exception unwinds this thread calls std::terminate. + ~StreamContext() noexcept(false) { + if (std::this_thread::get_id() != _owner) { + throw std::runtime_error( + "[StreamContext] Destroyed in a different thread than it was " + "constructed in."); + } set_default_device(_stream.device); set_default_stream(_stream); } private: Stream _stream; + std::thread::id _owner; }; struct MLX_API PrintOptions { diff --git a/mlx/version.h b/mlx/version.h index 9de9f2e558..14d8cf3cfb 100644 --- a/mlx/version.h +++ b/mlx/version.h @@ -6,7 +6,7 @@ #define MLX_VERSION_MAJOR 0 #define MLX_VERSION_MINOR 32 -#define MLX_VERSION_PATCH 2 +#define MLX_VERSION_PATCH 5 #define MLX_VERSION_NUMERIC \ (100000 * MLX_VERSION_MAJOR + 1000 * MLX_VERSION_MINOR + MLX_VERSION_PATCH) diff --git a/pyproject.toml b/pyproject.toml index 45675ae856..dd13cfab22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,3 +5,13 @@ requires = [ "typing_extensions", ] build-backend = "setuptools.build_meta" + +[tool.ruff.lint] +select = ["E", "F", "I"] + +[tool.ruff.lint.per-file-ignores] +# These modules expose imports as their public API. +"python/mlx/nn/__init__.py" = ["F401", "F403"] +"python/mlx/nn/layers/__init__.py" = ["F401"] +"python/mlx/optimizers/__init__.py" = ["F403"] +"examples/extensions/mlx_sample_extensions/__init__.py" = ["F401"] diff --git a/python/mlx/_distributed_utils/common.py b/python/mlx/_distributed_utils/common.py index 6289da0c46..6294a67da1 100644 --- a/python/mlx/_distributed_utils/common.py +++ b/python/mlx/_distributed_utils/common.py @@ -48,10 +48,13 @@ def from_file(cls, hostfile): "MLX_METAL_FAST_SYNCH=1" ], "hosts": [ - {"ssh": "hostname1", "ips": ["123.123.123.1"], "rdma": [null, "rdma_en2", "rdma_en3"]}, - {"ssh": "hostname2", "ips": ["123.123.123.2"], "rdma": ["rdma_en2", null, "rdma_en3"]}, + {"ssh": "hostname1", "ips": ["123.123.123.1"], + "rdma": [null, "rdma_en2", "rdma_en3"]}, + {"ssh": "hostname2", "ips": ["123.123.123.2"], + "rdma": ["rdma_en2", null, "rdma_en3"]}, ... - {"ssh": "hostnameN", "ips": ["123.123.123.N"], "rdma": ["rdma_en2", "rdma_en3", null]}, + {"ssh": "hostnameN", "ips": ["123.123.123.N"], + "rdma": ["rdma_en2", "rdma_en3", null]}, ] } diff --git a/python/mlx/_distributed_utils/config.py b/python/mlx/_distributed_utils/config.py index a4dabed629..ce595a49d2 100644 --- a/python/mlx/_distributed_utils/config.py +++ b/python/mlx/_distributed_utils/config.py @@ -10,8 +10,6 @@ from subprocess import DEVNULL, run from typing import Optional -import mlx.core as mx - from .common import ( Host, Hostfile, @@ -112,7 +110,8 @@ def can_auto_setup(hosts, sshinfo, auto_setup=False): has_sudo = all(info.has_sudo for info in sshinfo) if not has_sudo and auto_setup: log_warning( - "Automatic setup requested but the following hosts do not have passwordless sudo" + "Automatic setup requested but the following hosts do not have " + "passwordless sudo" ) for h, i in zip(hosts, sshinfo): if not i.has_sudo: @@ -188,11 +187,11 @@ def setup(self, verbose=False, auto_setup=False): def parse_hardware_ports(ports_string): ports = {} port_name = None - for l in ports_string.decode("utf-8").split("\n"): - if l.startswith("Hardware Port:"): - port_name = l.strip()[15:] - elif l.startswith("Device:"): - ports[port_name] = l.strip()[8:] + for line in ports_string.decode("utf-8").split("\n"): + if line.startswith("Hardware Port:"): + port_name = line.strip()[15:] + elif line.startswith("Device:"): + ports[port_name] = line.strip()[8:] port_name = None return ports @@ -343,7 +342,8 @@ def check_valid_mesh(hosts, connectivity, strict=True): if connectivity[i][j] <= 0: if strict: log_error( - f"Incomplete mesh, {hosts[i].ssh_hostname} is not connected to {hosts[j].ssh_hostname}" + f"Incomplete mesh, {hosts[i].ssh_hostname} is not connected to " + f"{hosts[j].ssh_hostname}" ) log_error() log_error("Try passing --dot to visualize the connectivity") @@ -432,7 +432,7 @@ def _check(hostname, i): def prepare_ethernet_hostfile(args, hosts): - log(args.verbose, f"Preparing an ethernet hostfile") + log(args.verbose, "Preparing an ethernet hostfile") add_ips(hosts, args.verbose) hostfile = Hostfile( @@ -466,14 +466,19 @@ def configure_jaccl(args, hosts, ips, sshinfo): log(args.verbose, "Prepare a jaccl hostfile") add_ips(hosts, args.verbose) + num_nodes = len(hosts) + count = min( + len(ips.ips[i, j]) for i in range(num_nodes) for j in range(num_nodes) if i != j + ) jaccl_hosts = [] for i, h in enumerate(hosts): rdma = [] - for j in range(len(hosts)): + for j in range(num_nodes): if i == j: rdma.append(None) else: - rdma.append(f"rdma_{ips.ips[i, j][0][0]}") + devices = [f"rdma_{ips.ips[i, j][c][0]}" for c in range(count)] + rdma.append(devices[0] if count == 1 else devices) jaccl_hosts.append(Host(i, h.ssh_hostname, h.ips, rdma)) hostfile = Hostfile(jaccl_hosts, "jaccl", args.env) @@ -513,7 +518,7 @@ def configure_jaccl_ring(args, hosts, ips, ring, sshinfo): def prepare_tb_hostfile(args, hosts, sshinfo): - log(args.verbose, f"Preparing for communication over thunderbolt") + log(args.verbose, "Preparing for communication over thunderbolt") tb_hosts, uuid_reverse_index = extract_connectivity(hosts, args.verbose) if args.dot: diff --git a/python/mlx/_distributed_utils/launch.py b/python/mlx/_distributed_utils/launch.py index 0e661e358f..73ff5f1b36 100644 --- a/python/mlx/_distributed_utils/launch.py +++ b/python/mlx/_distributed_utils/launch.py @@ -1,9 +1,9 @@ # Copyright © 2025 Apple Inc. import argparse -import base64 import json import os +import platform import shlex import shutil import sys @@ -193,27 +193,40 @@ def _thread_fn(rank, *args, **kwargs): to_write = [p.stdin.fileno()] stdin_buffer = b"" - while p.poll() is None: + while True: + exited = p.poll() is not None try: stdin_buffer += stdin_queue.get_nowait() except QueueEmpty: pass - rlist, wlist, _ = select(to_read, to_write, [], 1.0) + rlist, wlist, _ = select(to_read, to_write, [], 0 if exited else 1.0) for fd in rlist: is_stdout = fd == p.stdout.fileno() - msg = os.read(fd, 8192).decode(errors="ignore") - msg = command.preprocess_output(msg, is_stdout) + try: + data = os.read(fd, 8192) + except BlockingIOError: + continue + if not data: + to_read.remove(fd) + continue + msg = command.preprocess_output(data.decode(errors="ignore"), is_stdout) if is_stdout: stdout_queue.put(msg.encode()) else: stderr_queue.put(msg.encode()) for fd in wlist: if len(stdin_buffer) > 0: - n = os.write(fd, stdin_buffer) + try: + n = os.write(fd, stdin_buffer) + except BrokenPipeError: + to_write.remove(fd) + continue stdin_buffer = stdin_buffer[n:] - if stop: - command.terminate() + if exited and not rlist: break + if stop and not exited: + command.terminate() + exit_codes[rank] = command.exit_status if exit_codes[rank][1]: @@ -440,7 +453,7 @@ def get_mpi_libname(): filter(lambda line: "libmpi" in line, otool_output.splitlines()) ) return libmpi_line.strip().split()[0].removeprefix("@rpath/") - except: + except BaseException: return None @@ -592,5 +605,6 @@ def main(): launch_jaccl(parser, hostfile.hosts, args, rest) else: parser.error( - "The backend should be one of {'ring', 'mpi', 'nccl', 'jaccl', 'jaccl-ring'}" + "The backend should be one of " + "{'ring', 'mpi', 'nccl', 'jaccl', 'jaccl-ring'}" ) diff --git a/python/mlx/extension.py b/python/mlx/extension.py index d794fbe28f..96dc09013d 100644 --- a/python/mlx/extension.py +++ b/python/mlx/extension.py @@ -1,10 +1,14 @@ # Copyright © 2023 Apple Inc. +import logging import os +import platform import re +import shlex import subprocess import sys from pathlib import Path +from typing import Sequence from setuptools import Extension from setuptools.command.build_ext import build_ext @@ -12,6 +16,572 @@ import mlx _MLX_PATH = str(mlx.__path__[0]) +_MLX_PACKAGE_PATH = str(Path(__file__).resolve().parent) +_HOST_SOURCE_SUFFIXES = {".cc", ".cpp", ".cxx"} +_METAL_SOURCE_SUFFIX = ".metal" +_MIN_MACOS_DEPLOYMENT_TARGET = "14.0" +_LOGGER = logging.getLogger(__name__) + + +def _is_ninja_available() -> bool: + try: + subprocess.check_output(["ninja", "--version"]) + except (OSError, subprocess.SubprocessError): + return False + return True + + +def _cmake_quote(value: os.PathLike[str] | str) -> str: + value = os.fspath(value) + delimiter = "=" + while f"]{delimiter}]" in value: + delimiter += "=" + return f"[{delimiter}[{value}]{delimiter}]" + + +def _cmake_arguments(values: Sequence[os.PathLike[str] | str]) -> list[str]: + return [f" {_cmake_quote(value)}" for value in values] + + +def _extension_paths(command: build_ext, build_py, ext: Extension) -> tuple[Path, Path]: + fullname = command.get_ext_fullname(ext.name) + filename = command.get_ext_filename(fullname) + package = ".".join(fullname.split(".")[:-1]) + package_dir = build_py.get_package_dir(package) + inplace_file = Path(package_dir) / Path(filename).name + regular_file = Path(command.build_lib) / filename + return inplace_file, regular_file + + +def _macos_deployment_target(target: str) -> str: + if not re.fullmatch(r"\d+(?:\.\d+)*", target): + raise ValueError(f"Invalid macOS deployment target: {target!r}.") + if int(target.partition(".")[0]) < 14: + raise ValueError( + "macOS deployment target must be at least " + f"{_MIN_MACOS_DEPLOYMENT_TARGET}, got {target!r}." + ) + return target + + +def _macos_deployment_target_key(target: str) -> tuple[int, ...]: + components = [int(component) for component in target.split(".")] + while len(components) > 1 and components[-1] == 0: + components.pop() + return tuple(components) + + +def _mlx_macos_deployment_target() -> str: + libmlx = Path(_MLX_PACKAGE_PATH) / "lib" / "libmlx.dylib" + try: + output = subprocess.check_output( + ["xcrun", "vtool", "-show-build", str(libmlx)], + stderr=subprocess.STDOUT, + text=True, + ) + except (OSError, subprocess.SubprocessError) as error: + raise RuntimeError( + f"Failed to read the macOS deployment target from {libmlx}." + ) from error + + targets = re.findall(r"^\s*minos\s+(\d+(?:\.\d+)*)\s*$", output, re.MULTILINE) + if not targets: + raise RuntimeError(f"Could not find a macOS deployment target in {libmlx}.") + return max(targets, key=_macos_deployment_target_key) + + +def _cmake_generator( + extra_cmake_args: Sequence[str], use_ninja: bool +) -> tuple[str, bool]: + generator = None + generator_is_configured = False + for index, argument in enumerate(extra_cmake_args): + if argument in ("-G", "--generator"): + generator_is_configured = True + if index + 1 < len(extra_cmake_args): + generator = extra_cmake_args[index + 1] + elif argument.startswith("-G") and argument != "-G": + generator_is_configured = True + generator = argument[2:] + elif argument.startswith("--generator="): + generator_is_configured = True + generator = argument.partition("=")[2] + + if generator_is_configured: + return generator or "explicit", False + if use_ninja: + return "Ninja", True + return os.environ.get("CMAKE_GENERATOR") or "default", False + + +def _cmake_generator_build_directory(generator: str) -> str: + generator = re.sub(r"[^a-z0-9]+", "_", generator.lower()).strip("_") + return f"build-{generator or 'default'}" + + +class MetalLibrary: + """A named Metal library built as part of a :class:`MetalExtension`.""" + + def __init__( + self, + name: str, + sources: Sequence[os.PathLike[str] | str], + *, + extra_compile_args: Sequence[str] = (), + deployment_target: str | None = None, + ) -> None: + if not name or Path(name).name != name: + raise ValueError(f"Invalid Metal library name: {name!r}.") + source_strings = [os.fspath(source) for source in sources] + if not source_strings: + raise ValueError("MetalLibrary requires at least one Metal source file.") + if any( + Path(source).suffix.lower() != _METAL_SOURCE_SUFFIX + for source in source_strings + ): + raise ValueError("MetalLibrary sources must be Metal source files.") + if isinstance(extra_compile_args, (str, bytes)): + raise TypeError("MetalLibrary extra_compile_args must be a sequence.") + + self.name = name + self.sources = source_strings + self.extra_compile_args = list(extra_compile_args) + self.deployment_target = ( + _macos_deployment_target(deployment_target) + if deployment_target is not None + else None + ) + + +class MetalExtension(Extension): + """A setuptools extension built from C++ and Metal sources.""" + + def __init__( + self, + name: str, + sources: Sequence[os.PathLike[str] | str], + *args, + metal_libraries: Sequence[MetalLibrary] | None = None, + **kwargs, + ) -> None: + source_strings = [os.fspath(source) for source in sources] + suffixes = {Path(source).suffix.lower() for source in source_strings} + supported_suffixes = _HOST_SOURCE_SUFFIXES | {_METAL_SOURCE_SUFFIX} + unsupported_sources = [ + source + for source in source_strings + if Path(source).suffix.lower() not in supported_suffixes + ] + if unsupported_sources: + raise ValueError( + "MetalExtension received unsupported source files: " + + ", ".join(unsupported_sources) + ) + if not suffixes.intersection(_HOST_SOURCE_SUFFIXES): + raise ValueError("MetalExtension requires at least one C++ source file.") + if metal_libraries is None and _METAL_SOURCE_SUFFIX not in suffixes: + raise ValueError("MetalExtension requires at least one Metal source file.") + if metal_libraries is not None and _METAL_SOURCE_SUFFIX in suffixes: + raise ValueError( + "Metal sources must be specified in metal_libraries when it is used." + ) + if kwargs.get("py_limited_api", False): + raise ValueError("MetalExtension does not support py_limited_api.") + + compile_args = kwargs.get("extra_compile_args") + if compile_args is None: + compile_args = {"cxx": [], "metal": []} + elif isinstance(compile_args, (list, tuple)): + compile_args = {"cxx": list(compile_args), "metal": []} + elif isinstance(compile_args, dict): + unknown_groups = set(compile_args).difference({"cxx", "metal"}) + if unknown_groups: + raise ValueError( + "extra_compile_args only supports the cxx and metal groups." + ) + if any( + not isinstance(compile_args.get(group, []), (list, tuple)) + for group in ("cxx", "metal") + ): + raise TypeError("cxx and metal compile arguments must be lists.") + compile_args = { + "cxx": list(compile_args.get("cxx", [])), + "metal": list(compile_args.get("metal", [])), + } + else: + raise TypeError("extra_compile_args must be a list or a dictionary.") + + kwargs["extra_compile_args"] = compile_args + kwargs.setdefault("language", "c++") + super().__init__(name, sources, *args, **kwargs) + self.metal_library_name = name.rsplit(".", 1)[-1] + if metal_libraries is None: + self.metal_libraries = [ + MetalLibrary( + self.metal_library_name, + [ + source + for source in source_strings + if Path(source).suffix.lower() == _METAL_SOURCE_SUFFIX + ], + ) + ] + else: + self.metal_libraries = list(metal_libraries) + if not self.metal_libraries: + raise ValueError("metal_libraries must contain at least one library.") + if not all( + isinstance(library, MetalLibrary) for library in self.metal_libraries + ): + raise TypeError("metal_libraries must contain MetalLibrary objects.") + names = [library.name for library in self.metal_libraries] + if len(names) != len(set(names)): + raise ValueError("Metal library names must be unique.") + + +def _metal_extension_cmake( + ext: MetalExtension, output_dir: Path, *, generate_stubs: bool = True +) -> str: + host_sources = [ + str(Path(source).resolve()) + for source in ext.sources + if Path(source).suffix.lower() in _HOST_SOURCE_SUFFIXES + ] + include_dirs = [str(Path(path).resolve()) for path in ext.include_dirs] + depends = [str(Path(path).resolve()) for path in ext.depends] + library_dirs = [str(Path(path).resolve()) for path in ext.library_dirs] + extra_objects = [str(Path(path).resolve()) for path in ext.extra_objects] + languages = ["CXX"] + + lines = [ + "cmake_minimum_required(VERSION 3.25)", + "", + f"project(mlx_extension LANGUAGES {' '.join(languages)})", + "", + "set(CMAKE_CXX_STANDARD 20)", + "set(CMAKE_CXX_STANDARD_REQUIRED ON)", + "set(CMAKE_POSITION_INDEPENDENT_CODE ON)", + "", + "find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)", + "if(NOT nanobind_ROOT)", + " execute_process(", + ' COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir', + " OUTPUT_STRIP_TRAILING_WHITESPACE", + " OUTPUT_VARIABLE nanobind_ROOT", + " COMMAND_ERROR_IS_FATAL ANY)", + "endif()", + "find_package(nanobind CONFIG REQUIRED)", + "if(NOT MLX_ROOT)", + f" set(MLX_ROOT {_cmake_quote(_MLX_PACKAGE_PATH)})", + "endif()", + "find_package(MLX CONFIG REQUIRED)", + "if(NOT MLX_BUILD_METAL)", + ' message(FATAL_ERROR "MetalExtension requires an MLX build ' + 'with Metal support.")', + "endif()", + "", + "nanobind_add_module(", + " mlx_extension", + " NB_STATIC", + " LTO", + " NOMINSIZE", + " NB_DOMAIN", + " mlx", + *_cmake_arguments(host_sources), + ")", + "set_target_properties(mlx_extension PROPERTIES OUTPUT_NAME " + f"{_cmake_quote(ext.metal_library_name)})", + "set_target_properties(", + " mlx_extension", + " PROPERTIES", + f" LIBRARY_OUTPUT_DIRECTORY {_cmake_quote(output_dir)}", + f" LIBRARY_OUTPUT_DIRECTORY_RELEASE {_cmake_quote(output_dir)}", + f" LIBRARY_OUTPUT_DIRECTORY_DEBUG {_cmake_quote(output_dir)}", + f" LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO {_cmake_quote(output_dir)}", + f" LIBRARY_OUTPUT_DIRECTORY_MINSIZEREL {_cmake_quote(output_dir)})", + "target_link_libraries(mlx_extension PRIVATE mlx)", + ] + + if include_dirs: + lines.extend( + [ + "target_include_directories(mlx_extension PRIVATE", + *_cmake_arguments(include_dirs), + ")", + ] + ) + + definitions = [ + f"MLX_EXTENSION_NAME={ext.metal_library_name}", + f'MLX_METAL_LIBRARY_NAME="{ext.metal_library_name}"', + *( + name if value is None else f"{name}={value}" + for name, value in ext.define_macros + ), + ] + if definitions: + lines.extend( + [ + "target_compile_definitions(mlx_extension PRIVATE", + *_cmake_arguments(definitions), + ")", + ] + ) + + cxx_compile_args = list(ext.extra_compile_args["cxx"]) # type: ignore + cxx_compile_args.extend(f"-U{name}" for name in ext.undef_macros) + if cxx_compile_args: + lines.extend( + [ + "target_compile_options(mlx_extension PRIVATE", + *_cmake_arguments(cxx_compile_args), + ")", + ] + ) + + if library_dirs: + lines.extend( + [ + "target_link_directories(mlx_extension PRIVATE", + *_cmake_arguments(library_dirs), + ")", + ] + ) + + link_libraries = [*ext.libraries, *extra_objects] + if link_libraries: + lines.extend( + [ + "target_link_libraries(mlx_extension PRIVATE", + *_cmake_arguments(link_libraries), + ")", + ] + ) + + if ext.extra_link_args: + lines.extend( + [ + "target_link_options(mlx_extension PRIVATE", + *_cmake_arguments(ext.extra_link_args), + ")", + ] + ) + + mlx_rpath = "@loader_path/" + "../" * ext.name.count(".") + "mlx/lib" + rpaths = ["@loader_path", mlx_rpath, *ext.runtime_library_dirs] + lines.extend( + [ + "set_target_properties(", + " mlx_extension", + " PROPERTIES", + " BUILD_WITH_INSTALL_RPATH TRUE", + f" INSTALL_RPATH {_cmake_quote(';'.join(rpaths))})", + "", + ] + ) + metallib_targets = [] + for index, library in enumerate(ext.metal_libraries): + target = ( + "mlx_extension_metallib" + if len(ext.metal_libraries) == 1 + else f"mlx_extension_metallib_{index}" + ) + metallib_targets.append(target) + lines.extend( + [ + "mlx_build_metallib(", + f" TARGET {target}", + f" TITLE {_cmake_quote(library.name)}", + " SOURCES", + *_cmake_arguments( + list(str(Path(source).resolve()) for source in library.sources) + ), + " INCLUDE_DIRS", + *_cmake_arguments(include_dirs), + " ${MLX_INCLUDE_DIRS}", + " DEPS", + *_cmake_arguments(depends), + ] + ) + compile_options = [ + *ext.extra_compile_args["metal"], # type: ignore + *library.extra_compile_args, + ] + if compile_options: + lines.extend( + [ + " COMPILE_OPTIONS", + *_cmake_arguments(compile_options), + ] + ) + if library.deployment_target is not None: + lines.append( + f" DEPLOYMENT_TARGET {_cmake_quote(library.deployment_target)}" + ) + lines.extend( + [ + f" OUTPUT_DIRECTORY {_cmake_quote(output_dir)})", + "", + ] + ) + lines.extend( + [ + f"add_dependencies(mlx_extension {' '.join(metallib_targets)})", + "", + ] + ) + if generate_stubs: + stub_path = output_dir / f"{ext.metal_library_name}.pyi" + stubgen_code = "import mlx.core; from nanobind.stubgen import main; main()" + lines.extend( + [ + "add_custom_command(", + f" OUTPUT {_cmake_quote(stub_path)}", + ' COMMAND "${Python_EXECUTABLE}"', + " -c", + f" {_cmake_quote(stubgen_code)}", + " -q", + " -m", + f" {_cmake_quote(ext.metal_library_name)}", + " -i", + f" {_cmake_quote(output_dir)}", + " -o", + f" {_cmake_quote(stub_path)}", + " DEPENDS mlx_extension", + f' COMMENT "Generating {ext.metal_library_name}.pyi"', + " VERBATIM)", + "add_custom_target(mlx_extension_stub ALL DEPENDS " + f"{_cmake_quote(stub_path)})", + "", + ] + ) + return "\n".join(lines) + + +class BuildExtension(build_ext): + """Build :class:`MetalExtension` modules with CMake and Metal. + + CMake uses the platform default generator. Pass ``use_ninja=True`` with + :meth:`with_options` to use Ninja instead. If Ninja is requested but + unavailable, the build warns and falls back to the platform default generator. + Nanobind stubs are generated by default. Pass ``generate_stubs=False`` to + disable stub generation. + """ + + @classmethod + def with_options(cls, **options): + """Return a command subclass initialized with the given options.""" + + class cls_with_options(cls): # type: ignore + def __init__(self, *args, **kwargs) -> None: + kwargs.update(options) + super().__init__(*args, **kwargs) + + return cls_with_options + + def __init__(self, *args, **kwargs) -> None: + self.use_ninja = kwargs.pop("use_ninja", False) + self.generate_stubs = kwargs.pop("generate_stubs", True) + super().__init__(*args, **kwargs) + if self.use_ninja and not _is_ninja_available(): + _LOGGER.warning( + "Attempted to use Ninja as the BuildExtension CMake generator, " + "but Ninja was not found. Falling back to CMake's platform " + "default generator." + ) + self.use_ninja = False + + def build_extension(self, ext: Extension) -> None: + if not isinstance(ext, MetalExtension): + super().build_extension(ext) + return + if platform.system() != "Darwin": + raise RuntimeError("MetalExtension is only supported on macOS.") + + ext_fullpath = Path.cwd() / self.get_ext_fullpath(ext.name) # type: ignore[no-untyped-call] + output_dir = ext_fullpath.parent.resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + extra_cmake_args = shlex.split(os.environ.get("CMAKE_ARGS", "")) + generator, add_ninja_generator = _cmake_generator( + extra_cmake_args, self.use_ninja + ) + build_root = Path(self.build_temp) / ext.name + source_dir = build_root / "source" + binary_dir = build_root / _cmake_generator_build_directory(generator) + source_dir.mkdir(parents=True, exist_ok=True) + binary_dir.mkdir(parents=True, exist_ok=True) + (source_dir / "CMakeLists.txt").write_text( + _metal_extension_cmake(ext, output_dir, generate_stubs=self.generate_stubs), + encoding="utf-8", + ) + + debug = int(os.environ.get("DEBUG", 0)) if self.debug is None else self.debug + cfg = "Debug" if debug else "Release" + cmake_args = [ + "-S", + str(source_dir), + "-B", + str(binary_dir), + f"-DCMAKE_BUILD_TYPE={cfg}", + f"-DPython_EXECUTABLE={sys.executable}", + "-DBUILD_SHARED_LIBS=ON", + f"-DMLX_METAL_DEBUG={'ON' if debug else 'OFF'}", + ] + + deployment_target = os.environ.get("MACOSX_DEPLOYMENT_TARGET") + if deployment_target is None: + deployment_target = _mlx_macos_deployment_target() + else: + deployment_target = _macos_deployment_target(deployment_target) + cmake_args.append(f"-DCMAKE_OSX_DEPLOYMENT_TARGET={deployment_target}") + + deployment_target_override = None + for argument in extra_cmake_args: + match = re.fullmatch( + r"(?:-D)?CMAKE_OSX_DEPLOYMENT_TARGET(?::[^=]+)?=(.*)", argument + ) + if match: + deployment_target_override = match.group(1) + if deployment_target_override is not None: + _macos_deployment_target(deployment_target_override) + if add_ninja_generator: + cmake_args.extend(["-G", "Ninja"]) + cmake_args.extend(extra_cmake_args) + + archs = re.findall(r"-arch (\S+)", os.environ.get("ARCHFLAGS", "")) + if archs: + cmake_args.append(f"-DCMAKE_OSX_ARCHITECTURES={';'.join(archs)}") + + build_args = ["--build", str(binary_dir), "--config", cfg] + if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ: + jobs = self.parallel + if not isinstance(jobs, int) or isinstance(jobs, bool): + jobs = os.cpu_count() + build_args.append(f"-j{jobs}") + + subprocess.run(["cmake", *cmake_args], check=True) + subprocess.run(["cmake", *build_args], check=True) + + def run(self) -> None: + super().run() + if not self.inplace: + return + + build_py = self.get_finalized_command("build_py") + for ext in self.extensions: + if not isinstance(ext, MetalExtension): + continue + inplace_file, regular_file = _extension_paths(self, build_py, ext) + sidecar_names = [ + f"{library.name}.metallib" for library in ext.metal_libraries + ] + if self.generate_stubs: + sidecar_names.append(f"{ext.metal_library_name}.pyi") + for name in sidecar_names: + regular_sidecar = regular_file.parent / name + inplace_sidecar = inplace_file.parent / regular_sidecar.name + self.copy_file(str(regular_sidecar), str(inplace_sidecar)) # A CMakeExtension needs a sourcedir instead of a file list. @@ -40,6 +610,18 @@ def build_extension(self, ext: CMakeExtension) -> None: f"-DPython_EXECUTABLE={sys.executable}", ] build_args = [] + loader_path = None + if sys.platform.startswith("darwin"): + loader_path = "@loader_path" + elif sys.platform.startswith("linux"): + loader_path = "$ORIGIN" + if loader_path is not None: + mlx_rpath = loader_path + "/" + "../" * ext.name.count(".") + "mlx/lib" + cmake_args += [ + "-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON", + f"-DCMAKE_INSTALL_RPATH={loader_path};{mlx_rpath}", + ] + # Adding CMake arguments set as environment variable # (needed e.g. to build for ARM OSx on conda-forge) if "CMAKE_ARGS" in os.environ: @@ -79,11 +661,9 @@ def run(self) -> None: if isinstance(ext, CMakeExtension): # Resolve inplace package dir build_py = self.get_finalized_command("build_py") - inplace_file, regular_file = self._get_inplace_equivalent( - build_py, ext - ) + inplace_file, regular_file = _extension_paths(self, build_py, ext) - inplace_dir = str(Path(inplace_file).parent.resolve()) - regular_dir = str(Path(regular_file).parent.resolve()) + inplace_dir = str(inplace_file.parent.resolve()) + regular_dir = str(regular_file.parent.resolve()) self.copy_tree(regular_dir, inplace_dir) diff --git a/python/mlx/nn/layers/activations.py b/python/mlx/nn/layers/activations.py index 305b5ec7cc..1511c129e0 100644 --- a/python/mlx/nn/layers/activations.py +++ b/python/mlx/nn/layers/activations.py @@ -180,7 +180,8 @@ def gelu_approx(x): .. math:: - x = 0.5 * x * \left(1 + \text{Tanh}\left(\sqrt{2 / \pi} * \left(x + 0.044715 * x^3\right)\right)\right) + x = 0.5 * x * \left(1 + \text{Tanh}\left(\sqrt{2 / \pi} * \left(x + 0.044715 * + x^3\right)\right)\right) """ return 0.5 * x * (1 + mx.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3))) @@ -557,7 +558,8 @@ class GELU(Module): However, if ``approx`` is set to 'precise' or 'fast' it applies .. math:: - \textrm{GELUApprox}(x) &= 0.5 * x * \left(1 + \text{Tanh}\left(\sqrt{2 / \pi} * \left(x + 0.044715 * x^3\right)\right)\right) \\ + \textrm{GELUApprox}(x) &= 0.5 * x * \left(1 + \text{Tanh}\left(\sqrt{2 / \pi} * + \left(x + 0.044715 * x^3\right)\right)\right) \\ \textrm{GELUFast}(x) &= x * \sigma\left(1.702 * x\right) respectively. diff --git a/python/mlx/nn/layers/base.py b/python/mlx/nn/layers/base.py index e980f8343b..820afb7693 100644 --- a/python/mlx/nn/layers/base.py +++ b/python/mlx/nn/layers/base.py @@ -115,7 +115,7 @@ def __setattr__(self, key: str, val: Any): self.pop(key, None) def __delattr__(self, name): - if (val := self.get(name, None)) is not None: + if self.get(name, None) is not None: del self[name] else: super().__delattr__(name) @@ -208,7 +208,8 @@ def load_weights( def save_weights(self, file: str): """ - Save the model's weights to a file. The saving method is determined by the file extension: + Save the model's weights to a file. The saving method is determined by the file + extension: - ``.npz`` will use :func:`mx.savez` - ``.safetensors`` will use :func:`mx.save_safetensors` """ @@ -306,8 +307,8 @@ def update(self, parameters: dict, strict: bool = True) -> Module: dict of dicts and lists. Commonly used by the optimizer to change the model to the updated - (optimized) parameters. Also used by the :meth:`mlx.nn.value_and_grad` to set the - tracers in the model in order to compute gradients. + (optimized) parameters. Also used by the :meth:`mlx.nn.value_and_grad` to set + the tracers in the model in order to compute gradients. The passed in parameters dictionary need not be a full dictionary similar to :meth:`parameters`. Only the provided locations will be @@ -331,7 +332,8 @@ def apply(dst, parameters): if isinstance(current_value, mx.array): if strict and not isinstance(new_value, mx.array): raise ValueError( - f"Received invalid type: {type(new_value).__name__}." + f"Received invalid type: " + f"{type(new_value).__name__}." ) dst[k] = new_value else: @@ -478,8 +480,8 @@ def freeze( keys: Optional[Union[str, List[str]]] = None, strict: bool = False, ) -> Module: - """Freeze the Module's parameters or some of them. Freezing a parameter means not - computing gradients for it. + """Freeze the Module's parameters or some of them. Freezing a parameter means + not computing gradients for it. This function is idempotent i.e. freezing a frozen model is a no-op. @@ -490,7 +492,9 @@ def freeze( model = nn.Transformer() model.freeze() - model.apply_to_modules(lambda k, v: v.unfreeze() if k.endswith("attention") else None) + model.apply_to_modules( + lambda k, v: v.unfreeze() if k.endswith("attention") else None + ) Args: recurse (bool, optional): If True then freeze the parameters of the @@ -499,8 +503,8 @@ def freeze( parameters will be frozen otherwise all the parameters of a module. For instance freeze all biases by calling ``module.freeze(keys="bias")``. - strict (bool, optional): If set to ``True`` validate that the passed keys exist. - Default: ``False``. + strict (bool, optional): If set to ``True`` validate that the passed keys + exist. Default: ``False``. Returns: The module instance after freezing the parameters. @@ -511,8 +515,10 @@ def _freeze_impl(_, m): if local_keys is None: local_keys = tree_flatten( m.filter_and_map( - lambda m, k, v: (not isinstance(v, Module)) - and m.valid_parameter_filter(m, k, v) + lambda m, k, v: ( + (not isinstance(v, Module)) + and m.valid_parameter_filter(m, k, v) + ) ) ) local_keys = [k for (k, v) in local_keys] @@ -558,8 +564,8 @@ def unfreeze( parameters will be unfrozen otherwise all the parameters of a module. For instance unfreeze all biases by calling ``module.unfreeze(keys="bias")``. - strict (bool, optional): If set to ``True`` validate that the passed keys exist. - Default: ``False``. + strict (bool, optional): If set to ``True`` validate that the passed keys + exist. Default: ``False``. Returns: The module instance after unfreezing the parameters. @@ -627,7 +633,9 @@ def set_dtype( parameters to the new dtype. """ if predicate is None: - predicate = lambda _: True + + def predicate(_): + return True self.apply(lambda x: x.astype(dtype) if predicate(x.dtype) else x) diff --git a/python/mlx/nn/layers/convolution.py b/python/mlx/nn/layers/convolution.py index 40f34ff569..9241e2c148 100644 --- a/python/mlx/nn/layers/convolution.py +++ b/python/mlx/nn/layers/convolution.py @@ -51,7 +51,7 @@ def __init__( f"divisible by the number of groups ({groups})" ) - scale = math.sqrt(1 / (in_channels * kernel_size)) + scale = math.sqrt(1 / (in_channels // groups * kernel_size)) self.weight = mx.random.uniform( low=-scale, high=scale, @@ -132,7 +132,7 @@ def __init__( lambda x: (x, x) if isinstance(x, int) else x, (kernel_size, stride, padding), ) - scale = math.sqrt(1 / (in_channels * kernel_size[0] * kernel_size[1])) + scale = math.sqrt(1 / (in_channels // groups * kernel_size[0] * kernel_size[1])) self.weight = mx.random.uniform( low=-scale, high=scale, diff --git a/python/mlx/nn/layers/convolution_transpose.py b/python/mlx/nn/layers/convolution_transpose.py index 1fe8935fc2..00f3ae0c3f 100644 --- a/python/mlx/nn/layers/convolution_transpose.py +++ b/python/mlx/nn/layers/convolution_transpose.py @@ -8,7 +8,8 @@ class ConvTranspose1d(Module): - """Applies a 1-dimensional transposed convolution over the multi-channel input sequence. + """Applies a 1-dimensional transposed convolution over the multi-channel input + sequence. The channels are expected to be last i.e. the input shape should be ``NLC`` where: @@ -83,7 +84,8 @@ def __call__(self, x): class ConvTranspose2d(Module): - """Applies a 2-dimensional transposed convolution over the multi-channel input image. + """Applies a 2-dimensional transposed convolution over the multi-channel input + image. The channels are expected to be last i.e. the input shape should be ``NHWC`` where: @@ -163,7 +165,8 @@ def __call__(self, x): class ConvTranspose3d(Module): - """Applies a 3-dimensional transposed convolution over the multi-channel input image. + """Applies a 3-dimensional transposed convolution over the multi-channel input + image. The channels are expected to be last i.e. the input shape should be ``NDHWC`` where: diff --git a/python/mlx/nn/layers/distributed.py b/python/mlx/nn/layers/distributed.py index 16979b5097..23f521c975 100644 --- a/python/mlx/nn/layers/distributed.py +++ b/python/mlx/nn/layers/distributed.py @@ -7,7 +7,6 @@ import mlx.core as mx from mlx.nn.layers.base import Module from mlx.nn.layers.linear import Linear -from mlx.nn.layers.quantized import QuantizedLinear from mlx.utils import tree_flatten, tree_map_with_path, tree_unflatten diff --git a/python/mlx/nn/layers/dropout.py b/python/mlx/nn/layers/dropout.py index ef74ba9b60..2c07a5db11 100644 --- a/python/mlx/nn/layers/dropout.py +++ b/python/mlx/nn/layers/dropout.py @@ -24,7 +24,7 @@ def __init__(self, p: float = 0.5): self._p_1 = 1 - p def _extra_repr(self) -> str: - return f"p={1-self._p_1}" + return f"p={1 - self._p_1}" def __call__(self, x: mx.array) -> mx.array: if self._p_1 == 1 or not self.training: @@ -68,7 +68,7 @@ def __init__(self, p: float = 0.5): self._p_1 = 1 - p def _extra_repr(self) -> str: - return f"p={1-self._p_1}" + return f"p={1 - self._p_1}" def __call__(self, x: mx.array) -> mx.array: if x.ndim not in (3, 4): @@ -118,7 +118,7 @@ def __init__(self, p: float = 0.5): self._p_1 = 1 - p def _extra_repr(self) -> str: - return f"p={1-self._p_1}" + return f"p={1 - self._p_1}" def __call__(self, x: mx.array) -> mx.array: if x.ndim not in (4, 5): diff --git a/python/mlx/nn/layers/embedding.py b/python/mlx/nn/layers/embedding.py index e05cfb5f01..f3212f9344 100644 --- a/python/mlx/nn/layers/embedding.py +++ b/python/mlx/nn/layers/embedding.py @@ -47,7 +47,9 @@ def to_quantized( mode: str = "affine", quantize_input: bool = False, ): - """Return a :obj:`QuantizedEmbedding` layer that approximates this embedding layer.""" + """Return a :obj:`QuantizedEmbedding` layer that approximates this embedding + layer. + """ if quantize_input: raise ValueError("Quantized input is not supported.") return QuantizedEmbedding.from_embedding(self, group_size, bits, mode) diff --git a/python/mlx/nn/layers/linear.py b/python/mlx/nn/layers/linear.py index a1da07c465..ae04c921bd 100644 --- a/python/mlx/nn/layers/linear.py +++ b/python/mlx/nn/layers/linear.py @@ -32,9 +32,11 @@ class Linear(Module): y = x W^\top + b - where :math:`W` has shape ``[output_dims, input_dims]`` and :math:`b` has shape ``[output_dims]``. + where :math:`W` has shape ``[output_dims, input_dims]`` and :math:`b` has shape + ``[output_dims]``. - The values are initialized from the uniform distribution :math:`\mathcal{U}(-{k}, {k})`, + The values are initialized from the uniform distribution + :math:`\mathcal{U}(-{k}, {k})`, where :math:`k = \frac{1}{\sqrt{D_i}}` and :math:`D_i` is equal to ``input_dims``. Args: @@ -60,7 +62,10 @@ def __init__(self, input_dims: int, output_dims: int, bias: bool = True) -> None ) def _extra_repr(self) -> str: - return f"input_dims={self.weight.shape[1]}, output_dims={self.weight.shape[0]}, bias={'bias' in self}" + return ( + f"input_dims={self.weight.shape[1]}, " + f"output_dims={self.weight.shape[0]}, bias={'bias' in self}" + ) def __call__(self, x: mx.array) -> mx.array: if "bias" in self: @@ -101,7 +106,8 @@ def to_quantized( if quantize_input: if mode not in ["nvfp4", "mxfp8"]: raise ValueError( - f"Quantized activations are only supported for 'nvfp4' and 'mxfp8' modes, got {mode}." + f"Quantized activations are only supported for 'nvfp4' and 'mxfp8' " + f"modes, got {mode}." ) return QQLinear.from_linear(self, group_size, bits, mode) return QuantizedLinear.from_linear(self, group_size, bits, mode) @@ -117,10 +123,12 @@ class Bilinear(Module): y_i = x_2^\top W_i x_1 + b_i where: - :math:`W` has shape ``[output_dims, input2_dims, input1_dims]``, :math:`b` has shape ``[output_dims]``, + :math:`W` has shape ``[output_dims, input2_dims, input1_dims]``, :math:`b` has + shape ``[output_dims]``, and :math:`i` indexes the output dimension. - The values are initialized from the uniform distribution :math:`\mathcal{U}(-{k}, {k})`, + The values are initialized from the uniform distribution + :math:`\mathcal{U}(-{k}, {k})`, where :math:`k = \frac{1}{\sqrt{D_1}}` and :math:`D_1` is ``input1_dims``. Args: diff --git a/python/mlx/nn/layers/normalization.py b/python/mlx/nn/layers/normalization.py index 97f6942f04..4de2674512 100644 --- a/python/mlx/nn/layers/normalization.py +++ b/python/mlx/nn/layers/normalization.py @@ -13,7 +13,8 @@ class InstanceNorm(Module): .. math:: - y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta, + y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + + \beta, where :math:`\gamma` and :math:`\beta` are learned per feature dimension parameters initialized at 1 and 0 respectively. Both are of size :attr:`dims`, @@ -21,7 +22,8 @@ class InstanceNorm(Module): Args: dims (int): The number of features of the input. - eps (float): A value added to the denominator for numerical stability. Default: ``1e-5``. + eps (float): A value added to the denominator for numerical stability. Default: + ``1e-5``. affine (bool): Default: ``False``. Shape: diff --git a/python/mlx/nn/layers/pooling.py b/python/mlx/nn/layers/pooling.py index eaf50228ee..051c59e258 100644 --- a/python/mlx/nn/layers/pooling.py +++ b/python/mlx/nn/layers/pooling.py @@ -48,7 +48,8 @@ def _sliding_windows(x, window_shape, window_strides): raise ValueError( f"To extract sliding windows the window shapes and strides must have " f"the same number of spatial dimensions as the signal but the signal " - f"has {len(spatial_dims)} dims and the window shape has {len(window_shape)} " + f"has {len(spatial_dims)} dims and the window shape has " + f"{len(window_shape)} " f"and strides have {len(window_strides)}." ) @@ -89,8 +90,7 @@ def __init__(self, pooling_function, kernel_size, stride, padding, padding_value for name, values in (("kernel_size", kernel_size), ("stride", stride)): if any(v <= 0 for v in values): raise ValueError( - f"[{class_name}] '{name}' must be positive but got " - f"{tuple(values)}." + f"[{class_name}] '{name}' must be positive but got {tuple(values)}." ) if any(p[0] < 0 for p in padding): raise ValueError( diff --git a/python/mlx/nn/layers/positional_encoding.py b/python/mlx/nn/layers/positional_encoding.py index 49f300d4b1..cbf877016b 100644 --- a/python/mlx/nn/layers/positional_encoding.py +++ b/python/mlx/nn/layers/positional_encoding.py @@ -24,7 +24,8 @@ class RoPE(Module): implementation which is slightly less efficient. Default: ``False``. base (float, optional): The base used to compute angular frequency for each dimension in the positional encodings. Default: ``10000``. - scale (float, optional): The scale used to scale the positions. Default: ``1.0``. + scale (float, optional): The scale used to scale the positions. + Default: ``1.0``. """ def __init__( @@ -89,7 +90,8 @@ def __init__( # embedding dimension must be positive and even. if dims <= 0 or dims % 2 != 0: raise ValueError( - f"[SinusoidalPositionalEncoding] dims must be positive and even but got {dims}." + f"[SinusoidalPositionalEncoding] dims must be positive and even but " + f"got {dims}." ) # Avoid division by zero when dims == 2 (one frequency pair). @@ -127,14 +129,36 @@ def __call__(self, x): class ALiBi(Module): + """Implements Attention with Linear Biases (ALiBi). + + ALiBi adds a static, non-learnable bias matrix to attention scores proportional + to the distance between query and key tokens. + + For more details see `Train Short, Test Long: Attention with Linear Biases Enables + Input Length Extrapolation `_. + """ + @staticmethod def create_alibi_matrix( q_sequence_length: int, k_sequence_length: int, num_heads: int, - offset: int, - dtype=mx.float32, - ): + offset: int = 0, + dtype: mx.Dtype = mx.float32, + ) -> mx.array: + """Create the ALiBi bias matrix. + + Args: + q_sequence_length (int): The query sequence length. + k_sequence_length (int): The key sequence length. + num_heads (int): The number of attention heads. + offset (int, optional): The position offset. Default: ``0``. + dtype (Dtype, optional): Data type of the output array. Default: + ``mx.float32``. + + Returns: + array: The ALiBi bias matrix. + """ x1 = mx.arange(offset, q_sequence_length) x2 = mx.arange(0, k_sequence_length) distance_matrix = -mx.abs( @@ -145,7 +169,18 @@ def create_alibi_matrix( return alibi_mask @staticmethod - def create_alibi_slope(num_heads, dtype): + def create_alibi_slope(num_heads: int, dtype: mx.Dtype = mx.float32) -> mx.array: + """Create the geometric slopes for ALiBi across attention heads. + + Args: + num_heads (int): The number of attention heads. + dtype (Dtype, optional): Data type of the output array. Default: + ``mx.float32``. + + Returns: + array: The slopes array expanded for head broadcasting. + """ + def get_slopes(n: int): if math.log2(n).is_integer(): start = 2 ** (-(2 ** -(math.log2(n) - 3))) @@ -161,7 +196,22 @@ def get_slopes(n: int): out = mx.array(slopes, dtype=dtype) return mx.expand_dims(out, axis=(-1, -2)) - def __call__(self, attention_scores, offset=0, mask=None): + def __call__( + self, + attention_scores: mx.array, + offset: int = 0, + mask: Optional[mx.array] = None, + ) -> mx.array: + """Apply ALiBi matrix to attention scores. + + Args: + attention_scores (array): The input attention scores. + offset (int, optional): The position offset. Default: ``0``. + mask (array, optional): An optional attention mask. Default: ``None``. + + Returns: + array: The updated attention scores with ALiBi bias added. + """ alibi_mask = ALiBi.create_alibi_matrix( q_sequence_length=attention_scores.shape[-2] + offset, k_sequence_length=attention_scores.shape[-1], diff --git a/python/mlx/nn/layers/quantized.py b/python/mlx/nn/layers/quantized.py index 7cebb5b2da..556057f638 100644 --- a/python/mlx/nn/layers/quantized.py +++ b/python/mlx/nn/layers/quantized.py @@ -67,7 +67,9 @@ def quantize( Weight and input quantization for all linear layers: >>> predicate = lambda p, m: isinstance(m, nn.Linear) - >>> nn.quantize(model, mode="nvfp4", quantize_input=True, class_predicate=predicate) + >>> nn.quantize( + ... model, mode="nvfp4", quantize_input=True, class_predicate=predicate, + ... ) """ class_predicate = class_predicate or (lambda _, m: hasattr(m, "to_quantized")) @@ -318,7 +320,8 @@ class QQLinear(Module): the fly during computation so that gradients with respect to the weights can be computed. - To switch between the two cases, use ``layer.eval()`` and ``layer.train()`` respectively. + To switch between the two cases, use ``layer.eval()`` and ``layer.train()`` + respectively. Compared to the :class:`mlx.nn.QuantizedLinear` layer, this layer quantizes the input as well and includes weights in gradient computations. diff --git a/python/mlx/nn/layers/transformer.py b/python/mlx/nn/layers/transformer.py index 31ec916d19..dfcbd15145 100644 --- a/python/mlx/nn/layers/transformer.py +++ b/python/mlx/nn/layers/transformer.py @@ -173,9 +173,9 @@ def __init__( self.checkpoint = checkpoint def __call__(self, x, mask): - for l in self.layers: - l = checkpoint(l) if self.checkpoint else l - x = l(x, mask) + for layer in self.layers: + layer = checkpoint(layer) if self.checkpoint else layer + x = layer(x, mask) return self.ln(x) @@ -264,9 +264,9 @@ def __init__( self.checkpoint = checkpoint def __call__(self, x, memory, x_mask, memory_mask): - for l in self.layers: - l = checkpoint(l) if self.checkpoint else l - x = l(x, memory, x_mask, memory_mask) + for layer in self.layers: + layer = checkpoint(layer) if self.checkpoint else layer + x = layer(x, memory, x_mask, memory_mask) return self.ln(x) diff --git a/python/mlx/nn/layers/upsample.py b/python/mlx/nn/layers/upsample.py index 0be9f87bfb..208b155712 100644 --- a/python/mlx/nn/layers/upsample.py +++ b/python/mlx/nn/layers/upsample.py @@ -302,6 +302,13 @@ def upsample_linear( indices_fn=_linear_aa_indices, align_corners=align_corners, ) + if not antialias and not align_corners: + return _interpolate_separable( + x=x, + scale_factor=scale_factor, + indices_fn=_linear_indices, + align_corners=align_corners, + ) return _interpolate( x=x, scale_factor=scale_factor, @@ -428,7 +435,8 @@ def __init__( raise ValueError(f"[Upsample] Got unsupported upsampling algorithm: {mode}") if antialias and mode == "nearest": raise ValueError( - "[Upsample] Antialiasing is not supported for nearest neighbor upsampling" + "[Upsample] Antialiasing is not supported for nearest neighbor " + "upsampling" ) if isinstance(scale_factor, (list, tuple)): scale_factor = tuple(map(float, scale_factor)) diff --git a/python/mlx/nn/losses.py b/python/mlx/nn/losses.py index b98d2765d6..f9d5775dcd 100644 --- a/python/mlx/nn/losses.py +++ b/python/mlx/nn/losses.py @@ -64,15 +64,15 @@ def cross_entropy( >>> nn.losses.cross_entropy(logits, targets) array([0.348587, 0.348587], dtype=float32) >>> - >>> # Half precision logits with class indices as targets. On CUDA a + >>> # Half precision logits with class indices as targets. On the GPU a >>> # fused kernel accumulates the reduction in float32: >>> logits = mx.array([[2.0, -1.0], [-1.0, 2.0]], mx.bfloat16) >>> targets = mx.array([0, 1]) >>> nn.losses.cross_entropy(logits, targets) - array([0.0485873, 0.0485873], dtype=float32) + array([0.048584, 0.048584], dtype=bfloat16) >>> - >>> # Metal and the CPU reduce in the dtype of the logits, so upcast - >>> # them to get the same accuracy: + >>> # The CPU reduces in the dtype of the logits, so upcast them to get + >>> # the same accuracy: >>> nn.losses.cross_entropy(logits.astype(mx.float32), targets) array([0.0485873, 0.0485873], dtype=float32) """ @@ -96,8 +96,7 @@ def _drop_dim(shape, axis): ) use_fast = ( - mx.cuda.is_available() - and mx.default_device() == mx.gpu + mx.default_device() == mx.gpu and not targets_as_probs and label_smoothing == 0 and axis in (-1, logits.ndim - 1) @@ -179,7 +178,9 @@ def binary_cross_entropy( >>> probs = mx.array([0.1, 0.1, 0.4, 0.4]) >>> targets = mx.array([0, 0, 1, 1]) - >>> loss = nn.losses.binary_cross_entropy(probs, targets, with_logits=False, reduction="mean") + >>> loss = nn.losses.binary_cross_entropy( + ... probs, targets, with_logits=False, reduction="mean", + ... ) >>> loss array(0.510826, dtype=float32) """ @@ -305,8 +306,8 @@ def gaussian_nll_loss( inputs (array): The predicted expectation of the Gaussian distribution. targets (array): The target values (samples from the Gaussian distribution). vars (array): The predicted variance of the Gaussian distribution. - full (bool, optional): Whether to include the constant term in the loss calculation. - Default: ``False``. + full (bool, optional): Whether to include the constant term in the loss + calculation. Default: ``False``. eps (float, optional): Small positive constant for numerical stability. Default: ``1e-6``. reduction (str, optional): Specifies the reduction to apply to the output: @@ -440,9 +441,9 @@ def triplet_loss( ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``. Returns: - array: Computed triplet loss. If reduction is ``"none"``, returns a tensor with the - same shape as the inputs but with the ``axis`` dimension removed; if reduction - is ``"mean"`` or ``"sum"``, returns a scalar tensor. + array: Computed triplet loss. If reduction is ``"none"``, returns a tensor with + the same shape as the inputs but with the ``axis`` dimension removed; + if reduction is ``"mean"`` or ``"sum"``, returns a scalar tensor. """ pos_dist = mx.power( mx.power(mx.abs(anchors - positives), p).sum(axis) + eps, 1.0 / p @@ -499,8 +500,8 @@ def huber_loss( Args: inputs (array): The predicted values. targets (array): The target values. - delta (float, optional): The threshold at which to change between L1 and L2 loss. - Default: ``1.0``. + delta (float, optional): The threshold at which to change between L1 and L2 + loss. Default: ``1.0``. reduction (str, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``. @@ -591,22 +592,22 @@ def margin_ranking_loss( reduction: Reduction = "none", ) -> mx.array: r""" - Calculate the margin ranking loss that loss given inputs :math:`x_1`, :math:`x_2` and a label - :math:`y` (containing 1 or -1). + Calculate the margin ranking loss that loss given inputs :math:`x_1`, :math:`x_2` + and a label :math:`y` (containing 1 or -1). The loss is given by: .. math:: \text{loss} = \max (0, -y * (x_1 - x_2) + \text{margin}) - Where :math:`y` represents ``targets``, :math:`x_1` represents ``inputs1`` and :math:`x_2` - represents ``inputs2``. + Where :math:`y` represents ``targets``, :math:`x_1` represents ``inputs1`` and + :math:`x_2` represents ``inputs2``. Args: inputs1 (array): Scores for the first input. inputs2 (array): Scores for the second input. - targets (array): Labels indicating whether samples in ``inputs1`` should be ranked higher - than samples in ``inputs2``. Values should be 1 or -1. + targets (array): Labels indicating whether samples in ``inputs1`` should be + ranked higher than samples in ``inputs2``. Values should be 1 or -1. margin (float, optional): The margin by which the scores should be separated. Default: ``0.0``. reduction (str, optional): Specifies the reduction to apply to the output: diff --git a/python/mlx/nn/utils.py b/python/mlx/nn/utils.py index a60468db64..2f057235b9 100644 --- a/python/mlx/nn/utils.py +++ b/python/mlx/nn/utils.py @@ -128,12 +128,14 @@ def average_gradients( if all_reduce_size <= 0: return tree_map( - lambda x: mx.distributed.all_sum( - x, - group=group, - stream=communication_stream, - ) - / N, + lambda x: ( + mx.distributed.all_sum( + x, + group=group, + stream=communication_stream, + ) + / N + ), gradients, ) diff --git a/python/mlx/optimizers/optimizers.py b/python/mlx/optimizers/optimizers.py index 8be344247c..e8362d55a6 100644 --- a/python/mlx/optimizers/optimizers.py +++ b/python/mlx/optimizers/optimizers.py @@ -175,7 +175,7 @@ def __init__(self, optimizers, filters: list = []): if len(filters) != len(optimizers) - 1: raise ValueError( - f"Given {len(filters)} filters but {len(optimizers)-1} needed." + f"Given {len(filters)} filters but {len(optimizers) - 1} needed." ) self.optimizers = optimizers @@ -193,7 +193,8 @@ def _split_dictionary(self, gradients: dict): parts[i].append((k, g)) break - return [tree_unflatten(p) for p in parts] + # tree_unflatten([]) returns a list so use a dict for empty parts + return [tree_unflatten(p) if p else {} for p in parts] def init(self, parameters: dict): for o, p in zip(self.optimizers, self._split_dictionary(parameters)): @@ -274,7 +275,7 @@ def apply_single(self, gradient: mx.array, parameter: mx.array, state: dict): optimizer state.""" if self.weight_decay != 0: - gradient += self.weight_decay * parameter + gradient = gradient + self.weight_decay * parameter if self.momentum <= 0: return parameter - self.learning_rate.astype(gradient.dtype) * gradient @@ -297,7 +298,8 @@ def apply_single(self, gradient: mx.array, parameter: mx.array, state: dict): class RMSprop(Optimizer): r"""The RMSprop optimizer [1]. - [1]: Tieleman, T. and Hinton, G. 2012. Lecture 6.5-rmsprop, coursera: Neural networks for machine learning + [1]: Tieleman, T. and Hinton, G. 2012. Lecture 6.5-rmsprop, coursera: Neural + networks for machine learning .. math:: @@ -338,7 +340,9 @@ def init_single(self, parameter: mx.array, state: dict): state["v"] = mx.zeros_like(parameter) def apply_single(self, gradient: mx.array, parameter: mx.array, state: dict): - """Performs the RMSprop parameter update and stores :math:`v` in the optimizer state.""" + """Performs the RMSprop parameter update and stores :math:`v` in the + optimizer state. + """ lr = self.learning_rate.astype(gradient.dtype) alpha = self.alpha eps = self.eps @@ -405,7 +409,8 @@ class AdaDelta(Optimizer): Our AdaDelta implementation follows the original paper. In detail, - [1]: Zeiler, M.D., 2012. ADADELTA: an adaptive learning rate method. arXiv preprint arXiv:1212.5701. + [1]: Zeiler, M.D., 2012. ADADELTA: an adaptive learning rate method. arXiv preprint + arXiv:1212.5701. .. math:: @@ -418,8 +423,8 @@ class AdaDelta(Optimizer): learning_rate (float or callable): The learning rate :math:`\lambda`. rho (float, optional): The coefficient :math:`\rho` used for computing a running average of squared gradients. Default: ``0.9`` - eps (float, optional): The term :math:`\epsilon` added to the denominator to improve - numerical stability. Default: ``1e-6`` + eps (float, optional): The term :math:`\epsilon` added to the denominator to + improve numerical stability. Default: ``1e-6`` """ def __init__( @@ -502,8 +507,7 @@ def __init__( for i, beta in enumerate(betas): if not 0.0 <= beta < 1.0: raise ValueError( - f"Adam beta{i + 1} should be in [0, 1), {beta} was provided " - "instead" + f"Adam beta{i + 1} should be in [0, 1), {beta} was provided instead" ) if not 0.0 <= eps: @@ -556,7 +560,8 @@ class AdamW(Adam): m_{t+1} &= \beta_1 m_t + (1 - \beta_1) g_t \\ v_{t+1} &= \beta_2 v_t + (1 - \beta_2) g_t^2 \\ - w_{t+1} &= w_t - \alpha (\frac{m_{t+1}}{\sqrt{v_{t+1}} + \epsilon} + \lambda w_t) + w_{t+1} &= w_t - \alpha (\frac{m_{t+1}}{\sqrt{v_{t+1}} + \epsilon} + \lambda + w_t) Args: learning_rate (float or callable): The learning rate :math:`\alpha`. @@ -678,7 +683,8 @@ class Lion(Optimizer): betas (Tuple[float, float], optional): The coefficients :math:`(\beta_1, \beta_2)` used for computing the gradient momentum and update direction. Default: ``(0.9, 0.99)`` - weight_decay (float, optional): The weight decay :math:`\lambda`. Default: ``0.0`` + weight_decay (float, optional): The weight decay :math:`\lambda`. Default: + ``0.0`` """ def __init__( @@ -692,8 +698,7 @@ def __init__( for i, beta in enumerate(betas): if not 0.0 <= beta < 1.0: raise ValueError( - f"Lion beta{i + 1} should be in [0, 1), {beta} was provided " - "instead" + f"Lion beta{i + 1} should be in [0, 1), {beta} was provided instead" ) self._maybe_schedule("learning_rate", learning_rate) @@ -856,7 +861,7 @@ def apply_single(self, gradient: mx.array, parameter: mx.array, state: dict): update = exp_avg if self.weight_decay != 0: - parameter += parameter * (-self.weight_decay * learning_rate) + parameter = parameter + parameter * (-self.weight_decay * learning_rate) return parameter - update @@ -906,9 +911,10 @@ def init_single(self, parameter: mx.array, state: dict): state["v"] = mx.zeros_like(parameter) def _zeropower_via_newtonschulz5(self, X, steps: int): - assert ( - X.ndim == 2 - ), f"Expected a 2D array for Newton-Schulz iteration, got shape {X.shape} instead." + assert X.ndim == 2, ( + f"Expected a 2D array for Newton-Schulz iteration, got shape {X.shape} " + f"instead." + ) a, b, c = (3.4445, -4.7750, 2.0315) transpose_needed = X.shape[-2] > X.shape[-1] @@ -984,8 +990,20 @@ def clip_grad_norm(grads, max_norm): if max_norm < 0: raise ValueError(f"max_norm should be >=0, {max_norm} was provided instead") - norm_squared = tree_reduce(lambda acc, g: acc + g.square().sum(), grads, 0.0) + def squared_norm(g): + # Sum float16 squares in float32 so they do not overflow + if g.dtype == mx.float16: + g = g.astype(mx.float32) + return g.square().sum() + + def scale(g): + # Cast after scaling so small normalizers do not underflow in float16 + if mx.issubdtype(g.dtype, mx.floating): + return (g * normalizer).astype(g.dtype) + return g * normalizer + + norm_squared = tree_reduce(lambda acc, g: acc + squared_norm(g), grads, 0.0) total_norm = mx.sqrt(norm_squared) normalizer = mx.minimum(max_norm / (total_norm + 1e-6), 1.0) - clipped_grads = tree_map(lambda g: g * normalizer, grads) + clipped_grads = tree_map(scale, grads) return clipped_grads, total_norm diff --git a/python/mlx/optimizers/schedulers.py b/python/mlx/optimizers/schedulers.py index 99712097cb..54569f0cfe 100644 --- a/python/mlx/optimizers/schedulers.py +++ b/python/mlx/optimizers/schedulers.py @@ -119,8 +119,7 @@ def join_schedules(schedules: List[Callable], boundaries: List[int]) -> Callable if len(schedules) != len(boundaries) + 1: raise ValueError( - f"Received {len(boundaries)} boundaries but " - f"expected {len(schedules) - 1}." + f"Received {len(boundaries)} boundaries but expected {len(schedules) - 1}." ) def schedule(step): diff --git a/python/mlx/utils.py b/python/mlx/utils.py index f8595ef9a9..ecc15f6c8b 100644 --- a/python/mlx/utils.py +++ b/python/mlx/utils.py @@ -208,8 +208,8 @@ def tree_unflatten(tree: Union[List[Tuple[str, Any]], Dict[str, Any]]) -> Any: # {"hello": {"world": 42}} Args: - tree (list[tuple[str, Any]] or dict[str, Any]): The flat representation of a Python tree. - For instance as returned by :meth:`tree_flatten`. + tree (list[tuple[str, Any]] or dict[str, Any]): The flat representation of a + Python tree. For instance as returned by :meth:`tree_flatten`. Returns: A Python tree. @@ -240,12 +240,12 @@ def tree_unflatten(tree: Union[List[Tuple[str, Any]], Dict[str, Any]]) -> Any: is_list = False if is_list: - l = [] + items = [] for i, k in sorted(keys.items()): - # if i <= len(l), no {} will be appended. - l.extend([{} for _ in range(i - len(l))]) - l.append(tree_unflatten(children[k])) - return l + # if i <= len(items), no {} will be appended. + items.extend([{} for _ in range(i - len(items))]) + items.append(tree_unflatten(children[k])) + return items else: return {k: tree_unflatten(v) for k, v in children.items()} diff --git a/python/src/CMakeLists.txt b/python/src/CMakeLists.txt index 0798add410..d5cda4deef 100644 --- a/python/src/CMakeLists.txt +++ b/python/src/CMakeLists.txt @@ -1,7 +1,6 @@ nanobind_add_module( core NB_STATIC - STABLE_ABI FREE_THREADED LTO NOMINSIZE diff --git a/python/src/array.cpp b/python/src/array.cpp index fbab846182..e634bf31b7 100644 --- a/python/src/array.cpp +++ b/python/src/array.cpp @@ -1,9 +1,4 @@ // Copyright © 2023-2024 Apple Inc. -#include -#include -#include -#include - #include #include #include @@ -13,6 +8,11 @@ #include #include +#include +#include +#include +#include + #include "mlx/backend/metal/metal.h" #include "mlx/utils.h" #include "python/src/buffer.h" @@ -76,6 +76,9 @@ class ArrayAt { class ArrayPythonIterator { public: ArrayPythonIterator(mx::array x) : idx_(0), x_(std::move(x)) { + if (x_.ndim() == 0) { + throw nb::type_error("iter() 0-dimensional array."); + } if (x_.shape(0) > 0 && x_.shape(0) < 10) { splits_ = mx::split(x_, x_.shape(0)); } @@ -126,9 +129,10 @@ void init_array(nb::module_& m) { return nb::isinstance(other) && t == nb::cast(other); }) - .def("__hash__", [](const mx::Dtype& t) { - return static_cast(t.val()); - }); + .def( + "__hash__", + [](const mx::Dtype& t) { return static_cast(t.val()); }) + .freeze(); m.attr("bool_") = nb::cast(mx::bool_); m.attr("uint8") = nb::cast(mx::uint8); @@ -226,13 +230,16 @@ void init_array(nb::module_& m) { &mx::finfo::smallest_normal, R"pbdoc(The smallest positive normal number.)pbdoc") .def_ro("dtype", &mx::finfo::dtype, R"pbdoc(The :obj:`Dtype`.)pbdoc") - .def("__repr__", [](const mx::finfo& f) { - std::ostringstream os; - os << "finfo(" - << "min=" << f.min << ", max=" << f.max << ", dtype=" << f.dtype - << ")"; - return os.str(); - }); + .def( + "__repr__", + [](const mx::finfo& f) { + std::ostringstream os; + os << "finfo(" + << "min=" << f.min << ", max=" << f.max << ", dtype=" << f.dtype + << ")"; + return os.str(); + }) + .freeze(); nb::class_( m, @@ -250,13 +257,16 @@ void init_array(nb::module_& m) { &mx::iinfo::max, R"pbdoc(The largest representable number.)pbdoc") .def_ro("dtype", &mx::iinfo::dtype, R"pbdoc(The :obj:`Dtype`.)pbdoc") - .def("__repr__", [](const mx::iinfo& i) { - std::ostringstream os; - os << "iinfo(" - << "min=" << i.min << ", max=" << i.max << ", dtype=" << i.dtype - << ")"; - return os.str(); - }); + .def( + "__repr__", + [](const mx::iinfo& i) { + std::ostringstream os; + os << "iinfo(" + << "min=" << i.min << ", max=" << i.max << ", dtype=" << i.dtype + << ")"; + return os.str(); + }) + .freeze(); nb::class_( m, @@ -271,7 +281,8 @@ void init_array(nb::module_& m) { .def("multiply", &ArrayAt::multiply, "value"_a) .def("divide", &ArrayAt::divide, "value"_a) .def("maximum", &ArrayAt::maximum, "value"_a) - .def("minimum", &ArrayAt::minimum, "value"_a); + .def("minimum", &ArrayAt::minimum, "value"_a) + .freeze(); nb::class_( m, @@ -280,7 +291,8 @@ void init_array(nb::module_& m) { Any Python object which has an ``__mlx__array__`` method that returns an :obj:`array`. )pbdoc") - .def(nb::init_implicit()); + .def(nb::init_implicit()) + .freeze(); nb::class_( m, @@ -289,7 +301,8 @@ void init_array(nb::module_& m) { A helper object to iterate over the 1st dimension of an array. )pbdoc") .def("__next__", &ArrayPythonIterator::next) - .def("__iter__", [](const ArrayPythonIterator& it) { return it; }); + .def("__iter__", [](const ArrayPythonIterator& it) { return it; }) + .freeze(); // Install buffer protocol functions PyType_Slot array_slots[] = { @@ -503,7 +516,7 @@ void init_array(nb::module_& m) { nd.ndim(), reinterpret_cast(nd.shape_ptr()), owner, - nullptr, + nd.stride_ptr(), nb::dtype()), mx::bfloat16)); } else { @@ -803,6 +816,7 @@ void init_array(nb::module_& m) { }, "other"_a) .def("__neg__", [](const mx::array& a) { return -a; }) + .def("__pos__", [](const mx::array& a) { return mx::copy(a); }) .def("__bool__", [](mx::array& a) { return nb::bool_(to_scalar(a)); }) .def( "__repr__", @@ -1034,6 +1048,23 @@ void init_array(nb::module_& m) { [](mx::array& a) { return nb::cast>(to_scalar(a)); }) + .def( + "__index__", + [](mx::array& a) { + if (!mx::issubdtype(a.dtype(), mx::integer) || a.ndim() != 0) { + throw nb::type_error( + "Only 0-dimensional integer arrays can be converted to an index."); + } + return nb::int_(to_scalar(a)); + }) + .def( + "__bytes__", + [](mx::array& a) { + auto c = mx::contiguous(a); + c.eval(); + return nb::bytes( + reinterpret_cast(c.data()), c.nbytes()); + }) .def( "__format__", [](mx::array& a, nb::object format_spec) { @@ -1248,6 +1279,10 @@ void init_array(nb::module_& m) { "T", [](const mx::array& a) { return mx::transpose(a); }, "Equivalent to calling ``self.transpose()`` with no arguments.") + .def_prop_ro( + "mT", + [](const mx::array& a) { return mx::matrix_transpose(a); }, + "Equivalent to calling ``self.transpose()`` with the last two axes swapped.") .def( "sum", [](const mx::array& a, @@ -1352,7 +1387,9 @@ void init_array(nb::module_& m) { const IntOrVec& axis, bool keepdims, int ddof, + std::optional correction, mx::StreamOrDevice s) { + ddof = correction.value_or(ddof); return mx::std( a, get_reduce_axes(axis, a.ndim()), keepdims, ddof, s); }, @@ -1360,6 +1397,7 @@ void init_array(nb::module_& m) { "keepdims"_a = false, "ddof"_a = 0, nb::kw_only(), + "correction"_a = nb::none(), "stream"_a = nb::none(), "See :func:`std`.") .def( @@ -1368,7 +1406,9 @@ void init_array(nb::module_& m) { const IntOrVec& axis, bool keepdims, int ddof, + std::optional correction, mx::StreamOrDevice s) { + ddof = correction.value_or(ddof); return mx::var( a, get_reduce_axes(axis, a.ndim()), keepdims, ddof, s); }, @@ -1376,6 +1416,7 @@ void init_array(nb::module_& m) { "keepdims"_a = false, "ddof"_a = 0, nb::kw_only(), + "correction"_a = nb::none(), "stream"_a = nb::none(), "See :func:`var`.") .def( @@ -1556,5 +1597,6 @@ void init_array(nb::module_& m) { "dtype"_a, nb::kw_only(), "stream"_a = nb::none(), - "See :func:`view`."); + "See :func:`view`.") + .freeze(); } diff --git a/python/src/buffer.h b/python/src/buffer.h index 4b194b3d25..553bba80cd 100644 --- a/python/src/buffer.h +++ b/python/src/buffer.h @@ -88,9 +88,13 @@ extern "C" inline int getbuffer(PyObject* obj, Py_buffer* view, int flags) { std::memset(view, 0, sizeof(Py_buffer)); auto a = nb::cast(nb::handle(obj)); - { + // Exceptions can not propagate through the buffer protocol. + try { nb::gil_scoped_release nogil; a.eval(); + } catch (const std::exception& e) { + PyErr_SetString(PyExc_RuntimeError, e.what()); + return -1; } std::vector shape(a.shape().begin(), a.shape().end()); diff --git a/python/src/convert.cpp b/python/src/convert.cpp index a3da76ef53..2819884bb0 100644 --- a/python/src/convert.cpp +++ b/python/src/convert.cpp @@ -1,13 +1,13 @@ // Copyright © 2024 Apple Inc. +#include +#include + #include #include #include #include -#include -#include - #include "python/src/convert.h" #include "python/src/utils.h" @@ -180,19 +180,22 @@ mx::array cpu_nd_array_to_mlx( // Try to adopt a CPU host buffer as an mlx array without copying. On unified // memory the host pointer is GPU-addressable, so we wrap it directly via the // allocator instead of copying. The bytes are reinterpreted rather than -// converted, so the source element width must already match the destination -// dtype. The source ndarray is kept alive for the lifetime of the returned -// array. +// converted, so the source dtype must already match the destination dtype. +// The source ndarray is kept alive for the lifetime of the returned array. // // Returns std::nullopt when the buffer cannot be adopted (no Metal backend, -// dtype width mismatch, or a pointer the platform will not wrap), so the caller -// can fall back to a copy or raise. +// dtype mismatch, a pointer not aligned to the item size, or a pointer +// the platform will not wrap), so the caller can fall back to a copy or raise. std::optional cpu_nd_array_to_mlx_no_copy( nb::ndarray nd_array, const mx::Shape& shape, + mx::Dtype src_dtype, mx::Dtype dst_dtype) { - if (!mx::metal::is_available() || - nd_array.itemsize() != mx::size_of(dst_dtype)) { + // GPU kernels need aligned data + auto ptr = reinterpret_cast(nd_array.data()); + if (!mx::metal::is_available() || src_dtype != dst_dtype || + nd_array.itemsize() != mx::size_of(dst_dtype) || + ptr % nd_array.itemsize() != 0) { return std::nullopt; } @@ -206,19 +209,21 @@ std::optional cpu_nd_array_to_mlx_no_copy( return std::nullopt; } + auto byte_offset = nd_array.byte_offset(); mx::array out(shape, dst_dtype, nullptr, {}); out.set_data( - buf, - storage_size, - std::move(strides), - flags, - nd_array.byte_offset(), // The buffer wraps caller-owned memory, so release the wrapper rather // than returning it to the allocator's reuse pool, which must only // recycle buffers it allocated itself. - [owner = std::move(nd_array)](mx::allocator::Buffer b) { - mx::allocator::release(b); - }); + mx::allocator::Data( + buf, + [owner = std::move(nd_array)](mx::allocator::Buffer b) { + mx::allocator::release(b); + }), + storage_size, + std::move(strides), + flags, + byte_offset); out.set_status(mx::array::Status::available); return out; } @@ -238,19 +243,24 @@ mx::array metal_nd_array_to_mlx( } auto [storage_size, strides, flags] = get_strided_layout(nd_array, shape); auto data_handle = nd_array.data_handle(); + auto byte_offset = nd_array.byte_offset(); mx::array out(shape, src_dtype, nullptr, {}); out.set_data( - mx::allocator::Buffer(data_handle), + mx::allocator::Data( + mx::allocator::Buffer(data_handle), + [owner = std::move(nd_array)](mx::allocator::Buffer) {}), storage_size, std::move(strides), flags, - nd_array.byte_offset(), - [owner = std::move(nd_array)](mx::allocator::Buffer) {}); + byte_offset); out.set_status(mx::array::Status::available); if (copy) { auto result = mx::astype(out, dst_dtype, true, mx::Device::gpu); - result.eval(); + { + nb::gil_scoped_release nogil; + result.eval(); + } return result; } return out; @@ -283,8 +293,8 @@ mx::array nd_array_to_mlx( // zero-copy adoption of the host buffer first. A copy is passed by value // so the source is preserved for the fallback below. if (!copy.value_or(false)) { - if (auto out = - cpu_nd_array_to_mlx_no_copy(nd_array, shape, dst_dtype)) { + if (auto out = cpu_nd_array_to_mlx_no_copy( + nd_array, shape, src_mlx_dtype, dst_dtype)) { return *out; } if (no_copy) { @@ -631,6 +641,10 @@ mx::array array_from_list_impl( std::vector vals; fill_vector(pl, vals); return mx::array(vals.begin(), shape, dtype); + } else if (dtype == mx::float64) { + std::vector vals; + fill_vector(pl, vals); + return mx::array(vals.begin(), shape, dtype); } else if (mx::issubdtype(dtype, mx::inexact)) { std::vector vals; fill_vector(pl, vals); @@ -643,7 +657,7 @@ mx::array array_from_list_impl( } case pyfloat: { auto out_type = specified_type.value_or(mx::float32); - if (out_type == mx::float64) { + if (out_type == mx::float64 || !mx::issubdtype(out_type, mx::inexact)) { std::vector vals; fill_vector(pl, vals); return mx::array(vals.begin(), shape, out_type); @@ -738,7 +752,7 @@ mx::array create_array( return mx::array(val, t.value_or(default_type)); } else if (nb::isinstance(v)) { auto out_type = t.value_or(mx::float32); - if (out_type == mx::float64) { + if (out_type == mx::float64 || !mx::issubdtype(out_type, mx::inexact)) { return mx::array(nb::cast(v), out_type); } else { return mx::array(nb::cast(v), out_type); diff --git a/python/src/convert.h b/python/src/convert.h index 133f443ed7..7c767a5944 100644 --- a/python/src/convert.h +++ b/python/src/convert.h @@ -14,24 +14,6 @@ namespace nb = nanobind; namespace nanobind { -template <> -struct ndarray_traits { - static constexpr bool is_complex = false; - static constexpr bool is_float = true; - static constexpr bool is_bool = false; - static constexpr bool is_int = false; - static constexpr bool is_signed = true; -}; - -template <> -struct ndarray_traits { - static constexpr bool is_complex = false; - static constexpr bool is_float = true; - static constexpr bool is_bool = false; - static constexpr bool is_int = false; - static constexpr bool is_signed = true; -}; - namespace detail { template <> diff --git a/python/src/device.cpp b/python/src/device.cpp index 83d32d1cb6..da4f919b1a 100644 --- a/python/src/device.cpp +++ b/python/src/device.cpp @@ -1,14 +1,14 @@ // Copyright © 2023-2025 Apple Inc. -#include -#include - #include #include #include #include #include +#include +#include + #include "mlx/device.h" #include "mlx/utils.h" @@ -43,13 +43,16 @@ void init_device(nb::module_& m) { os << d; return os.str(); }) - .def("__eq__", [](const mx::Device& d, const nb::object& other) { - if (!nb::isinstance(other) && - !nb::isinstance(other)) { - return false; - } - return d == nb::cast(other); - }); + .def( + "__eq__", + [](const mx::Device& d, const nb::object& other) { + if (!nb::isinstance(other) && + !nb::isinstance(other)) { + return false; + } + return d == nb::cast(other); + }) + .freeze(); nb::implicitly_convertible(); diff --git a/python/src/distributed.cpp b/python/src/distributed.cpp index 0ad91c6e48..0d1e341f92 100644 --- a/python/src/distributed.cpp +++ b/python/src/distributed.cpp @@ -51,7 +51,8 @@ void init_distributed(nb::module_& parent_module) { color (int): A value to group processes into subgroups. key (int, optional): A key to optionally change the rank ordering of the processes. - )pbdoc"); + )pbdoc") + .freeze(); m.def( "is_available", diff --git a/python/src/export.cpp b/python/src/export.cpp index 7748f87b14..1becd22bcc 100644 --- a/python/src/export.cpp +++ b/python/src/export.cpp @@ -298,7 +298,8 @@ void init_export(nb::module_& m) { auto [args_, kwargs_] = validate_and_extract_inputs(args, kwargs, "[export_function]"); exporter(args_, kwargs_); - }); + }) + .freeze(); m.def( "exporter", diff --git a/python/src/fast.cpp b/python/src/fast.cpp index 67c3442cff..f9c472ab99 100644 --- a/python/src/fast.cpp +++ b/python/src/fast.cpp @@ -189,8 +189,8 @@ void init_fast(nb::module_& parent_module) { Computes ``logsumexp(logits, axis=-1) - logits[..., target]`` in a fused kernel with accumulation in float32. - Note: Currently is implemented only on CUDA, fallback to unfused version with - manual casting on Metal and CPU. + Note: The fused kernel is available on Metal and CUDA. The CPU falls + back to the unfused version, which reduces in the dtype of the logits. Args: logits (array): The unnormalized logits. The loss is computed over @@ -386,6 +386,32 @@ void init_fast(nb::module_& parent_module) { out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale, mask="causal") )pbdoc"); + m.def( + "gated_delta_update", + &mlx::core::fast::gated_delta_update, + "q"_a, + "k"_a, + "v"_a, + "gamma"_a, + "beta"_a, + "initial_state"_a = nb::none(), // optional, defaults to None + "mask"_a = nb::none(), // optional, defaults to None + "stream"_a = nb::none(), // optional, defaults to None + R"( + Chunked gated delta network forward pass. + + Args: + q: Queries [B, T, Hk, Dk] + k: Keys [B, T, Hk, Dk] + v: Values [B, T, Hv, Dv] + gamma: Decay rate in linear space [B, T, Hv] + beta: Delta update rates [B, T, Hv] + initial_state: Optional initial hidden state [B, T, Hk, Dv] + mask: Optional + Returns: + Tuple of (output [B, T, Hv, Dv], final_state [B, T, Hk, Dv]) + )"); + m.def( "metal_kernel", [](const std::string& name, diff --git a/python/src/fft.cpp b/python/src/fft.cpp index 99f8478bbb..37a176006c 100644 --- a/python/src/fft.cpp +++ b/python/src/fft.cpp @@ -634,4 +634,124 @@ void init_fft(nb::module_& parent_module) { Returns: array: The inverse-shifted array with the same shape as the input. )pbdoc"); + m.def( + "stft", + [](const mx::array& x, + int n_fft, + const std::optional& hop_length, + const std::optional& win_length, + const std::optional& window, + bool center, + const std::string& pad_mode, + const std::string& norm, + const std::optional& onesided, + mx::StreamOrDevice s) { + auto fft_norm = parse_norm(norm, "stft"); + return mx::fft::stft( + x, + n_fft, + hop_length, + win_length, + window, + center, + pad_mode, + fft_norm, + onesided, + s); + }, + "x"_a, + "n_fft"_a = 2048, + "hop_length"_a = nb::none(), + "win_length"_a = nb::none(), + "window"_a = nb::none(), + "center"_a = true, + "pad_mode"_a = "reflect", + "norm"_a = "backward", + "onesided"_a = nb::none(), + "stream"_a = nb::none(), + R"pbdoc( + Short-Time Fourier Transform. + + Splits the last axis of ``x`` into overlapping frames of length + ``n_fft``, applies ``window``, and takes the Fourier Transform of each + frame. The output is always complex with shape ``(..., n_freq, n_frames)``. + + Args: + x (array): The input array. + n_fft (int, optional): Size of the Fourier Transform. Default is ``2048``. + hop_length (int, optional): Samples between frames. Default is ``n_fft // 4``. + win_length (int, optional): Window size. Default is ``n_fft``. + window (array, optional): A one-dimensional window, centered and + zero-padded to ``n_fft``. Default is a rectangular window. + center (bool, optional): Pad both ends so frames are centered. Default is ``True``. + pad_mode (str, optional): One of ``"reflect"``, ``"constant"``, or + ``"edge"``, used when ``center`` is ``True``. Default is ``"reflect"``. + norm (str, optional): One of ``"backward"``, ``"ortho"``, or + ``"forward"``. Default is ``"backward"``. + onesided (bool, optional): Return only non-negative frequencies. + Default is ``True`` for real input and ``False`` for complex input. + + Returns: + array: The STFT of ``x``. + )pbdoc"); + m.def( + "istft", + [](const mx::array& stft_matrix, + const std::optional& n_fft, + const std::optional& hop_length, + const std::optional& win_length, + const std::optional& window, + bool center, + const std::string& norm, + const std::optional& onesided, + const std::optional& length, + mx::StreamOrDevice s) { + auto fft_norm = parse_norm(norm, "istft"); + return mx::fft::istft( + stft_matrix, + n_fft, + hop_length, + win_length, + window, + center, + fft_norm, + onesided, + length, + s); + }, + "stft_matrix"_a, + "n_fft"_a = nb::none(), + "hop_length"_a = nb::none(), + "win_length"_a = nb::none(), + "window"_a = nb::none(), + "center"_a = true, + "norm"_a = "backward", + "onesided"_a = nb::none(), + "length"_a = nb::none(), + "stream"_a = nb::none(), + R"pbdoc( + Inverse Short-Time Fourier Transform. + + Inverts :func:`stft` by overlap-adding the windowed inverse transform + of each frame, normalized by the squared-window envelope. + + Args: + stft_matrix (array): The STFT with shape ``(..., n_freq, n_frames)``. + n_fft (int, optional): Size of the Fourier Transform. Default is + inferred from ``n_freq`` and ``onesided``. The onesided inference + is even; pass ``n_fft`` for an odd transform size. + hop_length (int, optional): Samples between frames. Default is ``n_fft // 4``. + win_length (int, optional): Window size. Default is ``n_fft``. + window (array, optional): A one-dimensional window. Default is a + rectangular window. + center (bool, optional): Whether the STFT was centered. Default is ``True``. + norm (str, optional): One of ``"backward"``, ``"ortho"``, or + ``"forward"``. Default is ``"backward"``. + onesided (bool, optional): Whether the STFT has only non-negative + frequencies. Default is ``True``. + length (int, optional): Trim or zero-pad the output to this length. + + Returns: + array: The reconstructed signal. + )pbdoc"); } diff --git a/python/src/indexing.cpp b/python/src/indexing.cpp index 1dce537880..679291a71b 100644 --- a/python/src/indexing.cpp +++ b/python/src/indexing.cpp @@ -1,10 +1,11 @@ // Copyright © 2023-2024 Apple Inc. +#include + #include #include #include -#include - +#include "mlx/dtype.h" #include "mlx/ops.h" #include "python/src/convert.h" #include "python/src/indexing.h" @@ -20,6 +21,9 @@ bool is_index_scalar(const nb::object& obj) { if (nb::isinstance(obj)) { return false; } + if (nb::isinstance(obj)) { + return false; + } if (!PyIndex_Check(obj.ptr())) { return false; } @@ -71,6 +75,33 @@ void get_slice_params( nb::getattr(in_slice, "stop"), strides < 0 ? -axis_size - 1 : axis_size); } +// Resolve negative bounds and clamp into range, mirroring CPython's +// PySlice_AdjustIndices. Needed wherever a slice is expanded into an explicit +// arange, since out-of-range bounds would otherwise be used verbatim. +void adjust_slice_bounds( + mx::ShapeElem& start, + mx::ShapeElem& end, + mx::ShapeElem stride, + int axis_size) { + if (start < 0) { + start += axis_size; + if (start < 0) { + start = (stride < 0) ? -1 : 0; + } + } else if (start >= axis_size) { + start = (stride < 0) ? axis_size - 1 : axis_size; + } + + if (end < 0) { + end += axis_size; + if (end < 0) { + end = (stride < 0) ? -1 : 0; + } + } else if (end >= axis_size) { + end = (stride < 0) ? axis_size - 1 : axis_size; + } +} + mx::array get_int_index(nb::object idx, int axis_size) { int idx_ = safe_to_int32(idx); idx_ = (idx_ < 0) ? idx_ + axis_size : idx_; @@ -151,9 +182,7 @@ mx::array mlx_gather_nd( get_slice_params( start, end, stride, nb::cast(idx), src.shape(i)); - // Handle negative indices - start = (start < 0) ? start + src.shape(i) : start; - end = (end < 0) ? end + src.shape(i) : end; + adjust_slice_bounds(start, end, stride, src.shape(i)); gather_indices.push_back(arange(start, end, stride, mx::uint32)); num_slices++; @@ -253,8 +282,14 @@ auto mlx_expand_ellipsis(const mx::Shape& shape, const nb::tuple& entries) { // Expand ellipsis if (has_ellipsis) { + int ndim = static_cast(shape.size()); + if (non_none_indices > ndim) { + std::ostringstream msg; + msg << "Too many indices for array with " << ndim << " dimensions."; + throw std::invalid_argument(msg.str()); + } for (int axis = non_none_indices_before; - axis < shape.size() - non_none_indices_after; + axis < ndim - non_none_indices_after; axis++) { indices.push_back( nb::slice(mx::ShapeElem{0}, shape[axis], mx::ShapeElem{1})); @@ -676,9 +711,7 @@ mlx_scatter_args_nd( get_slice_params( start, end, stride, nb::cast(pyidx), axis_size); - // Handle negative indices - start = (start < 0) ? start + axis_size : start; - end = (end < 0) ? end + axis_size : end; + adjust_slice_bounds(start, end, stride, axis_size); mx::Shape idx_shape(idx_ndim, 1); @@ -779,7 +812,8 @@ mlx_compute_scatter_args( } else if (nb::isinstance(obj)) { return mlx_scatter_args_nd(src, nb::cast(obj), vals); } else if (nb::isinstance(obj)) { - return {{}, broadcast_to(vals, src.shape()), {}}; + return { + {}, broadcast_to(squeeze_leading_singletons(vals), src.shape()), {}}; } else if (obj.is_none()) { return {{}, broadcast_to(vals, src.shape()), {}}; } else if (nb::isinstance(obj)) { @@ -907,7 +941,7 @@ mlx_compute_slice_update_args( upd_ax--; } else if (is_index_scalar(pyidx)) { int st = safe_to_int32(pyidx); - st = (st < 0) ? st + src.shape(i) : st; + st = (st < 0) ? st + src.shape(ax) : st; starts[ax] = st; stops[ax] = st + 1; if (upd_ax >= 0) { diff --git a/python/src/linalg.cpp b/python/src/linalg.cpp index a5e82ae853..4a46e77889 100644 --- a/python/src/linalg.cpp +++ b/python/src/linalg.cpp @@ -1,13 +1,13 @@ // Copyright © 2023-2024 Apple Inc. -#include - #include #include #include #include #include +#include + #include "mlx/linalg.h" #include "python/src/small_vector.h" diff --git a/python/src/memory.cpp b/python/src/memory.cpp index 5ce9a765ba..5719449535 100644 --- a/python/src/memory.cpp +++ b/python/src/memory.cpp @@ -1,8 +1,10 @@ -// Copyright © 2025 Apple Inc. +// Copyright © 2025-2026 Apple Inc. -#include "mlx/memory.h" #include +#include "mlx/memory.h" +#include "python/src/trees.h" + namespace mx = mlx::core; namespace nb = nanobind; using namespace nb::literals; @@ -17,6 +19,30 @@ void init_memory(nb::module_& m) { Note, this will not always match memory use reported by the system because it does not include cached memory buffers. )pbdoc"); + m.def( + "get_array_buffer_size", + [](const nb::args& args) { + std::vector arrays = tree_flatten(args, false); + nb::gil_scoped_release nogil; + return mx::get_array_buffer_size(arrays); + }, + nb::arg(), + nb::sig("def get_array_buffer_size(*args) -> int"), + R"pbdoc( + Get the size of the buffers backing arrays in bytes. + + Each unique buffer is counted once. The full allocator size of each + buffer is used, which can exceed the logical size of its arrays. Arrays + must be evaluated before calling this function. The result does not + include graph objects, cached buffers, or other non-buffer memory. + + Args: + *args (arrays or trees of arrays): Each argument can be a single array + or a tree of arrays. Leaves which are not arrays are ignored. + + Returns: + int: The size of the unique buffers in bytes. + )pbdoc"); m.def( "get_peak_memory", &mx::get_peak_memory, @@ -62,6 +88,12 @@ void init_memory(nb::module_& m) { Returns: int: The previous memory limit in bytes. )pbdoc"); + m.def( + "get_memory_limit", + &mx::get_memory_limit, + R"pbdoc( + Get the current memory limit in bytes. + )pbdoc"); m.def( "set_cache_limit", &mx::set_cache_limit, diff --git a/python/src/metal.cpp b/python/src/metal.cpp index fb3c513069..8d0d4242e2 100644 --- a/python/src/metal.cpp +++ b/python/src/metal.cpp @@ -1,6 +1,4 @@ // Copyright © 2023-2024 Apple Inc. -#include - #include #include #include @@ -8,6 +6,8 @@ #include #include +#include + #include "mlx/backend/metal/metal.h" #include "mlx/device.h" #include "mlx/memory.h" diff --git a/python/src/mlx_func.cpp b/python/src/mlx_func.cpp index 9955e134f9..9f84f5c797 100644 --- a/python/src/mlx_func.cpp +++ b/python/src/mlx_func.cpp @@ -2,17 +2,11 @@ #include "python/src/mlx_func.h" -#include - -// A garbage collected function which wraps nb::cpp_function -// See https://github.com/wjakob/nanobind/discussions/919 +// The wrapper owns callbacks because free-threaded nanobind functions are +// immortal struct gc_func { - PyObject_HEAD - // Vector call implementation that forwards calls to nanobind - PyObject* (*vectorcall)(PyObject*, PyObject* const*, size_t, PyObject*); - // The nanobind wrapper func - PyObject* func; + std::unique_ptr func; // The original wrapped func PyObject* orig_func; @@ -22,97 +16,48 @@ struct gc_func { int gc_func_tp_traverse(PyObject* self, visitproc visit, void* arg) { Py_VISIT(Py_TYPE(self)); - gc_func* w = (gc_func*)self; - Py_VISIT(w->func); - for (auto d : w->deps) { - Py_VISIT(d); + if (nb::inst_ready(self)) { + for (auto d : nb::inst_ptr(self)->deps) { + Py_VISIT(d); + } } return 0; -}; +} int gc_func_tp_clear(PyObject* self) { - gc_func* w = (gc_func*)self; - Py_CLEAR(w->func); + auto* w = nb::inst_ptr(self); + w->orig_func = nullptr; + w->deps.clear(); + w->func.reset(); return 0; } -PyObject* gc_func_get_doc(PyObject* self, void*) { - return PyObject_GetAttrString(((gc_func*)self)->func, "__doc__"); -} - -PyObject* gc_func_get_sig(PyObject* self, void*) { - return PyObject_GetAttrString(((gc_func*)self)->func, "__nb_signature__"); -} - -PyObject* gc_func_vectorcall( - PyObject* self, - PyObject* const* args, - size_t nargs, - PyObject* kwnames) { - return PyObject_Vectorcall(((gc_func*)self)->func, args, nargs, kwnames); -} - -void gc_func_dealloc(PyObject* self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(((gc_func*)self)->func); - PyObject_GC_Del(self); -} - -static PyMemberDef gc_func_members[] = { - {"__vectorcalloffset__", - T_PYSSIZET, - (Py_ssize_t)offsetof(gc_func, vectorcall), - READONLY, - nullptr}, - {nullptr, 0, 0, 0, nullptr}}; - -static PyGetSetDef gc_func_getset[] = { - {"__doc__", gc_func_get_doc, nullptr, nullptr, nullptr}, - {"__nb_signature__", gc_func_get_sig, nullptr, nullptr, nullptr}, - {nullptr, nullptr, nullptr, nullptr, nullptr}}; - static PyObject* gc_func_getattro(PyObject* self, PyObject* name_) { - gc_func* w = (gc_func*)self; - return PyObject_GenericGetAttr(w->orig_func, name_); + return PyObject_GenericGetAttr(nb::inst_ptr(self)->orig_func, name_); } // Table of custom type slots we want to install PyType_Slot gc_func_slots[] = { {Py_tp_traverse, (void*)gc_func_tp_traverse}, {Py_tp_clear, (void*)gc_func_tp_clear}, - {Py_tp_getset, (void*)gc_func_getset}, {Py_tp_getattro, (void*)gc_func_getattro}, - {Py_tp_members, (void*)gc_func_members}, - {Py_tp_call, (void*)PyVectorcall_Call}, - {Py_tp_dealloc, (void*)gc_func_dealloc}, {0, 0}}; -static PyType_Spec gc_func_spec = { - /* .name = */ "mlx.gc_func", - /* .basicsize = */ (int)sizeof(gc_func), - /* .itemsize = */ 0, - /* .flags = */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_HAVE_VECTORCALL, - /* .slots = */ gc_func_slots}; - -static PyTypeObject* gc_func_tp = nullptr; - nb::callable mlx_func( - nb::object func, + std::unique_ptr func, const nb::callable& orig_func, std::vector deps) { - gc_func* r = (gc_func*)PyType_GenericAlloc(gc_func_tp, 0); - r->func = func.inc_ref().ptr(); - r->orig_func = orig_func.ptr(); - deps.push_back(r->orig_func); - r->deps = std::move(deps); - r->vectorcall = gc_func_vectorcall; - return nb::steal((PyObject*)r); + deps.push_back(orig_func.ptr()); + return nb::borrow( + nb::cast(gc_func{std::move(func), orig_func.ptr(), std::move(deps)})); } void init_mlx_func(nb::module_& m) { - gc_func_tp = (PyTypeObject*)PyType_FromSpec(&gc_func_spec); - if (!gc_func_tp) { - nb::raise("Could not register MLX function type."); - } + nb::class_(m, "_gc_func", nb::type_slots(gc_func_slots)) + .def( + "__call__", + [](gc_func& self, nb::args args, nb::kwargs kwargs) { + return (*self.func)(args, kwargs); + }) + .freeze(); } diff --git a/python/src/mlx_func.h b/python/src/mlx_func.h index 79c8376dee..3b0c0a10e0 100644 --- a/python/src/mlx_func.h +++ b/python/src/mlx_func.h @@ -2,30 +2,36 @@ #pragma once -#include - #include -#include + +#include +#include +#include namespace nb = nanobind; using namespace nb::literals; +struct PyFunction { + virtual ~PyFunction() = default; + virtual nb::object operator()(nb::args& args, nb::kwargs& kwargs) = 0; +}; + nb::callable mlx_func( - nb::object func, + std::unique_ptr func, const nb::callable& orig_func, std::vector deps); template nb::callable mlx_func(F func, const nb::callable& orig_func, Deps&&... deps) { - return mlx_func( - nb::cpp_function(std::move(func)), - orig_func, - std::vector{deps.ptr()...}); -} + struct Callback : PyFunction { + F func; + + explicit Callback(F func) : func(std::move(func)) {} -template -nb::callable -mlx_func(nb::object func, const nb::callable& orig_func, Deps&&... deps) { + nb::object operator()(nb::args& args, nb::kwargs& kwargs) override { + return nb::cast(func(args, kwargs)); + } + }; return mlx_func( - std::move(func), orig_func, std::vector{deps.ptr()...}); + std::make_unique(std::move(func)), orig_func, {deps.ptr()...}); } diff --git a/python/src/ops.cpp b/python/src/ops.cpp index 677d998af1..dcf0d10863 100644 --- a/python/src/ops.cpp +++ b/python/src/ops.cpp @@ -1,10 +1,5 @@ // Copyright © 2023-2024 Apple Inc. -#include -#include -#include -#include - #include #include #include @@ -13,6 +8,11 @@ #include #include +#include +#include +#include +#include + #include "mlx/einsum.h" #include "mlx/ops.h" #include "mlx/utils.h" @@ -213,14 +213,14 @@ void init_ops(nb::module_& m) { m.def( "unstack", [](const mx::array& a, int axis, mx::StreamOrDevice s) { - return mx::unstack(a, axis, s); + return nb::tuple(nb::cast(mx::unstack(a, axis, s))); }, nb::arg(), nb::kw_only(), "axis"_a = 0, "stream"_a = nb::none(), nb::sig( - "def unstack(x: array, /, *, axis: int = 0, stream: StreamOrDevice = None) -> list[array]"), + "def unstack(x: array, /, *, axis: int = 0, stream: StreamOrDevice = None) -> tuple[array, ...]"), R"pbdoc( Split an array into a sequence of arrays along the given axis. @@ -232,7 +232,7 @@ void init_ops(nb::module_& m) { axis (int, optional): Axis along which to unstack. Default: ``0``. Returns: - list(array): A list of arrays, one for each index along ``axis``. + tuple(array): A tuple of arrays, one for each index along ``axis``. )pbdoc"); m.def( "expand_dims", @@ -746,6 +746,9 @@ void init_ops(nb::module_& m) { - All but the last two dimensions of each input are broadcast with one another using standard numpy-style broadcasting semantics. + Only inexact types are supported. The promoted type of ``a`` and ``b`` + must be floating point or complex. + Args: a (array): Input array or scalar. b (array): Input array or scalar. @@ -1155,19 +1158,24 @@ void init_ops(nb::module_& m) { )pbdoc"); m.def( "arctan2", - &mx::arctan2, + [](const ScalarOrArray& a_, + const ScalarOrArray& b_, + mx::StreamOrDevice s) { + auto [a, b] = to_arrays(a_, b_); + return mx::arctan2(a, b, s); + }, nb::arg(), nb::arg(), nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def arctan2(a: array, b: array, /, *, stream: StreamOrDevice = None) -> array"), + "def arctan2(a: scalar | array, b: scalar | array, /, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Element-wise inverse tangent of the ratio of two arrays. Args: - a (array): Input array. - b (array): Input array. + a (array or scalar): Input array or scalar. + b (array or scalar): Input array or scalar. Returns: array: The inverse tangent of the ratio of ``a`` and ``b``. @@ -1295,12 +1303,12 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def degrees(a: array, /, *, stream: StreamOrDevice = None) -> array"), + "def degrees(a: scalar | array, /, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Convert angles from radians to degrees. Args: - a (array): Input array. + a (array or scalar): Input array. Returns: array: The angles in degrees. @@ -1314,12 +1322,12 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def radians(a: array, /, *, stream: StreamOrDevice = None) -> array"), + "def radians(a: scalar | array, /, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Convert angles from degrees to radians. Args: - a (array): Input array. + a (array or scalar): Input array. Returns: array: The angles in radians. @@ -1768,11 +1776,11 @@ void init_ops(nb::module_& m) { }, nb::arg(), "indices"_a, - "axis"_a = nb::none(), + "axis"_a.none() = -1, nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def take_along_axis(a: array, /, indices: array, axis: int | None = None, *, stream: StreamOrDevice = None) -> array"), + "def take_along_axis(a: array, /, indices: array, axis: int | None = -1, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Take values along an axis at the specified indices. @@ -1782,7 +1790,7 @@ void init_ops(nb::module_& m) { the input array excluding the `axis` dimension. axis (int or None): Axis in the input to take the values from. If ``axis == None`` the array is flattened to 1D prior to the indexing - operation. + operation. Defaults to ``-1``. Returns: array: The output array. @@ -1807,7 +1815,7 @@ void init_ops(nb::module_& m) { nb::arg(), "indices"_a, "values"_a, - "axis"_a.none(), + "axis"_a = nb::none(), nb::kw_only(), "stream"_a = nb::none(), nb::sig( @@ -2106,7 +2114,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def tri(n: int, m: int, k: int, dtype: Dtype | None = None, *, stream: StreamOrDevice = None) -> array"), + "def tri(n: int, m: int | None = None, k: int = 0, dtype: Dtype | None = None, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( An array with ones at and below the given diagonal and zeros elsewhere. @@ -2128,7 +2136,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def tril(x: array, k: int, *, stream: StreamOrDevice = None) -> array"), + "def tril(x: array, k: int = 0, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Zeros the array above the given diagonal. @@ -2148,7 +2156,7 @@ void init_ops(nb::module_& m) { nb::kw_only(), "stream"_a = nb::none(), nb::sig( - "def triu(x: array, k: int, *, stream: StreamOrDevice = None) -> array"), + "def triu(x: array, k: int = 0, *, stream: StreamOrDevice = None) -> array"), R"pbdoc( Zeros the array below the given diagonal. @@ -2549,6 +2557,16 @@ void init_ops(nb::module_& m) { Returns: array: The transposed array. )pbdoc"); + m.def( + "matrix_transpose", + &mx::matrix_transpose, + nb::arg(), + nb::kw_only(), + "stream"_a = nb::none(), + nb::sig( + "def matrix_transpose(a: array, /, *, stream: StreamOrDevice = None) -> array"), + R"pbdoc( + Transpose the last two dimensions of the array.)pbdoc"); m.def( "permute_dims", [](const mx::array& a, @@ -2720,6 +2738,37 @@ void init_ops(nb::module_& m) { Returns: array: The output array with the corresponding axes reduced. )pbdoc"); + m.def( + "minmax", + [](const mx::array& a, + const IntOrVec& axis, + bool keepdims, + mx::StreamOrDevice s) -> std::tuple { + auto axes = get_reduce_axes(axis, a.ndim()); + return mx::minmax(a, axes, keepdims, s); + }, + nb::arg(), + "axis"_a = nb::none(), + "keepdims"_a = false, + nb::kw_only(), + "stream"_a = nb::none(), + nb::sig( + "def minmax(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, *, stream: StreamOrDevice = None) -> tuple[array, array]"), + R"pbdoc( + Return the minimum and maximum over the given axes. + + Equivalent to calling :func:`min` and :func:`max` separately. + + Args: + a (array): Input array. + axis (int or list(int), optional): Axis or axes to reduce over. + If unspecified, reduce over the entire array. + keepdims (bool, optional): Keep reduced axes as singleton + dimensions. Default: ``False``. + + Returns: + tuple(array, array): The minimum and maximum arrays, in that order. + )pbdoc"); m.def( "logcumsumexp", [](const mx::array& a, @@ -2856,7 +2905,9 @@ void init_ops(nb::module_& m) { const IntOrVec& axis, bool keepdims, int ddof, + std::optional correction, mx::StreamOrDevice s) { + ddof = correction.value_or(ddof); return mx::var(a, get_reduce_axes(axis, a.ndim()), keepdims, ddof, s); }, nb::arg(), @@ -2864,6 +2915,7 @@ void init_ops(nb::module_& m) { "keepdims"_a = false, "ddof"_a = 0, nb::kw_only(), + "correction"_a = nb::none(), "stream"_a = nb::none(), nb::sig( "def var(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, stream: StreamOrDevice = None) -> array"), @@ -2889,7 +2941,9 @@ void init_ops(nb::module_& m) { const IntOrVec& axis, bool keepdims, int ddof, + std::optional correction, mx::StreamOrDevice s) { + ddof = correction.value_or(ddof); return mx::std(a, get_reduce_axes(axis, a.ndim()), keepdims, ddof, s); }, nb::arg(), @@ -2897,6 +2951,7 @@ void init_ops(nb::module_& m) { "keepdims"_a = false, "ddof"_a = 0, nb::kw_only(), + "correction"_a = nb::none(), "stream"_a = nb::none(), nb::sig( "def std(a: array, /, axis: None | int | Sequence[int] = None, keepdims: bool = False, ddof: int = 0, *, stream: StreamOrDevice = None) -> array"), @@ -3230,6 +3285,108 @@ void init_ops(nb::module_& m) { Returns: array: The top ``k`` elements from the input. )pbdoc"); + m.def( + "unique", + [](const mx::array& a, + int size, + bool return_index, + bool return_inverse, + bool return_counts, + const std::optional& fill_value, + mx::StreamOrDevice s) -> nb::object { + std::optional fill_value_ = std::nullopt; + if (fill_value) { + fill_value_ = to_array(fill_value.value(), a.dtype()); + } + auto out = mx::unique( + a, + size, + return_index, + return_inverse, + return_counts, + fill_value_, + s); + if (out.size() == 1) { + return nb::cast(out.at(0)); + } + nb::list result; + for (auto& o : out) { + result.append(o); + } + return nb::tuple(result); + }, + nb::arg(), + "size"_a, + "return_index"_a = false, + "return_inverse"_a = false, + "return_counts"_a = false, + "fill_value"_a = nb::none(), + nb::kw_only(), + "stream"_a = nb::none(), + nb::sig( + "def unique(a: array, /, size: int, return_index: bool = False, return_inverse: bool = False, return_counts: bool = False, fill_value: scalar | array | None = None, *, stream: StreamOrDevice = None) -> array | tuple[array, ...]"), + R"pbdoc( + Returns the sorted unique elements of the flattened array. + + The shape of the output does not depend on the values in ``a``, so + ``a`` is not evaluated. Unlike NumPy, the size is never inferred from + the values and must be provided. + + Entries past the last unique element hold ``fill_value`` and their + count is ``0``, so ``mx.sum(counts > 0)`` gives the number of unique + elements as long as the output is not truncated. + + A truncated output keeps the smallest ``size`` unique elements, and + ``index``, ``inverse`` and ``counts`` then stop describing all of ``a``, + and ``inverse`` and ``counts`` stop agreeing with each other: the counts + of the dropped elements are gone, while their indices in ``inverse`` are + clamped to the last entry. + ``inverse`` is meaningless for a ``size`` of ``0``, since there is no + element left for it to point at. + + This op builds on ``mx.sort``, so a ``bool`` input needs the CPU + stream, which is where ``mx.sort`` supports it. + + Args: + a (array): Input array. + size (int): The size of the output. If the size is smaller than + the number of unique elements of ``a``, the output is truncated. + If it is larger, the output is padded with ``fill_value``. + return_index (bool, optional): If ``True``, also return the index + in the flattened ``a`` of the first occurrence of each unique + element. Default: ``False``. + return_inverse (bool, optional): If ``True``, also return the + indices of the unique array that rebuild ``a``. The indices have + the same shape as ``a``. Default: ``False``. + return_counts (bool, optional): If ``True``, also return the number + of times each unique element occurs in ``a``. Default: ``False``. + fill_value (scalar or array, optional): The value of the entries + past the last unique element. If ``None``, this defaults to the + first of the sorted unique elements. Default: ``None``. + + Returns: + array or tuple(array, ...): The sorted unique elements. If any of + ``return_index``, ``return_inverse`` or ``return_counts`` is + ``True``, a tuple with the requested arrays in the order values, + index, inverse, counts. + + Example: + >>> a = mx.array([2, 1, 2, 3, 1]) + >>> mx.unique(a, 3) + array([1, 2, 3], dtype=int32) + >>> mx.unique(a, 5) + array([1, 2, 3, 1, 1], dtype=int32) + >>> values, index, inverse, counts = mx.unique( + ... a, 4, True, True, True, fill_value=0) + >>> values + array([1, 2, 3, 0], dtype=int32) + >>> index + array([1, 0, 3, 1], dtype=uint32) + >>> inverse + array([1, 0, 1, 2, 0], dtype=uint32) + >>> counts + array([2, 2, 1, 0], dtype=int32) + )pbdoc"); m.def( "broadcast_to", [](const ScalarOrArray& a, const mx::Shape& shape, mx::StreamOrDevice s) { @@ -3256,7 +3413,9 @@ void init_ops(nb::module_& m) { m.def( "broadcast_arrays", [](const nb::args& args, mx::StreamOrDevice s) { - return broadcast_arrays(nb::cast>(args), s); + return nb::tuple( + nb::cast( + broadcast_arrays(nb::cast>(args), s))); }, nb::arg(), nb::kw_only(), @@ -4711,14 +4870,14 @@ void init_ops(nb::module_& m) { .. table:: Quantization modes - ====== ====================== ========================== ============= ===== - mode group size bits scale type bias - ====== ====================== ========================== ============= ===== - affine 32, 64\ :sup:`*`, 128 2, 3, 4\ :sup:`*`, 5, 6, 8 same as input yes - mxfp4 32\ :sup:`*` 4\ :sup:`*` e8m0 no - mxfp8 32\ :sup:`*` 8\ :sup:`*` e8m0 no - nvfp4 16\ :sup:`*` 4\ :sup:`*` e4m3 no - ====== ====================== ========================== ============= ===== + ====== ====================== ============================== ============= ===== + mode group size bits scale type bias + ====== ====================== ============================== ============= ===== + affine 32, 64\ :sup:`*`, 128 1, 2, 3, 4\ :sup:`*`, 5, 6, 8 same as input yes + mxfp4 32\ :sup:`*` 4\ :sup:`*` e8m0 no + mxfp8 32\ :sup:`*` 8\ :sup:`*` e8m0 no + nvfp4 16\ :sup:`*` 4\ :sup:`*` e4m3 no + ====== ====================== ============================== ============= ===== :sup:`*` indicates the default value when unspecified. @@ -4823,11 +4982,12 @@ void init_ops(nb::module_& m) { "group_size"_a = nb::none(), "bits"_a = nb::none(), "mode"_a = "affine", + "global_scale"_a = nb::none(), nb::kw_only(), "sorted_indices"_a = false, "stream"_a = nb::none(), nb::sig( - "def gather_qmm(x: array, w: array, /, scales: array, biases: array | None = None, lhs_indices: array | None = None, rhs_indices: array | None = None, transpose: bool = True, group_size: int | None = None, bits: int | None = None, mode: str = 'affine', *, sorted_indices: bool = False, stream: StreamOrDevice = None) -> array"), + "def gather_qmm(x: array, w: array, /, scales: array, biases: array | None = None, lhs_indices: array | None = None, rhs_indices: array | None = None, transpose: bool = True, group_size: int | None = None, bits: int | None = None, mode: str = 'affine', global_scale: array | None = None, *, sorted_indices: bool = False, stream: StreamOrDevice = None) -> array"), R"pbdoc( Perform quantized matrix multiplication with matrix-level gather. @@ -4857,6 +5017,9 @@ void init_ops(nb::module_& m) { ``w`` in the quantized array. See supported values and defaults in the :ref:`table of quantization modes `. Default: ``None``. mode (str, optional): The quantization mode. Default: ``"affine"``. + global_scale (array, optional): The per-input float32 scale used for + ``nvfp4`` quantization of ``w``. Only supported on the GPU. + Default: ``None``. sorted_indices (bool, optional): May allow a faster implementation if the passed indices are sorted. Default: ``False``. @@ -5143,7 +5306,7 @@ void init_ops(nb::module_& m) { "sorted_indices"_a = false, "stream"_a = nb::none(), nb::sig( - "def gather_mm(a: array, b: array, /, lhs_indices: array, rhs_indices: array, *, sorted_indices: bool = False, stream: StreamOrDevice = None) -> array"), + "def gather_mm(a: array, b: array, /, lhs_indices: array | None = None, rhs_indices: array | None = None, *, sorted_indices: bool = False, stream: StreamOrDevice = None) -> array"), R"pbdoc( Matrix multiplication with matrix-level gather. @@ -5805,6 +5968,9 @@ void init_ops(nb::module_& m) { Perform the Einstein summation convention on the operands. + Contractions are implemented with :func:`matmul` and have the same + requirements. + Args: subscripts (str): The Einstein summation convention equation. *operands (array): The input arrays. @@ -6176,6 +6342,5 @@ void init_ops(nb::module_& m) { m.attr("cumulative_sum") = m.attr("cumsum"); m.attr("empty") = m.attr("zeros"); m.attr("empty_like") = m.attr("zeros_like"); - m.attr("matrix_transpose") = m.attr("transpose"); m.attr("pow") = m.attr("power"); } diff --git a/python/src/print.cpp b/python/src/print.cpp index 6c08d88d3f..85404bd8a9 100644 --- a/python/src/print.cpp +++ b/python/src/print.cpp @@ -1,9 +1,9 @@ +#include + #include #include #include -#include - #include "mlx/utils.h" #include "python/src/utils.h" @@ -33,7 +33,8 @@ void init_print(nb::module_& m) { // Expose printing options to Python: allow setting global precision. nb::class_(m, "PrintOptions") .def(nb::init(), "precision"_a = -1) - .def_rw("precision", &mx::PrintOptions::precision); + .def_rw("precision", &mx::PrintOptions::precision) + .freeze(); m.def( "set_printoptions", @@ -64,7 +65,8 @@ void init_print(nb::module_& m) { nb::class_(m, "_PrintOptionsContext") .def(nb::init()) .def("__enter__", &PrintOptionsContext::enter) - .def("__exit__", &PrintOptionsContext::exit); + .def("__exit__", &PrintOptionsContext::exit) + .freeze(); m.def( "printoptions", diff --git a/python/src/random.cpp b/python/src/random.cpp index 10b82b8921..8710a8d701 100644 --- a/python/src/random.cpp +++ b/python/src/random.cpp @@ -74,13 +74,9 @@ void reset_random_state() { class RandomState {}; nb::object random_state_sentinel() { - static nb::object sentinel = []() { - auto sentinel = nb::cast(RandomState{}); - sentinel.inc_ref(); - return sentinel; - }(); + static nb::handle sentinel = nb::cast(RandomState{}).release(); - return sentinel; + return nb::borrow(sentinel); } mx::array random_state_key() { @@ -107,9 +103,10 @@ void init_random(nb::module_& parent_module) { return default_key().state()[0]; }, "index"_a) - .def("__iter__", [](const RandomState&) { - return nb::iter(default_key().state()); - }); + .def( + "__iter__", + [](const RandomState&) { return nb::iter(default_key().state()); }) + .freeze(); m.def("__getattr__", [&](nb::handle key) -> nb::object { // Create random.state lazily to avoid initializing device during import. diff --git a/python/src/small_vector.h b/python/src/small_vector.h index 0b2e6bb2ee..1a07abe1b2 100644 --- a/python/src/small_vector.h +++ b/python/src/small_vector.h @@ -31,7 +31,7 @@ struct type_caster<::mlx::core::SmallVector> { // Not noexcept: on overflow of a narrow integer element we raise // OverflowError so nanobind surfaces a clean error to the user. - bool from_python(handle src, uint8_t flags, cleanup_list* cleanup) { + bool from_python(handle src, uint32_t flags, cleanup_list* cleanup) { size_t size; PyObject* temp; diff --git a/python/src/stream.cpp b/python/src/stream.cpp index 467518e991..5706fc878c 100644 --- a/python/src/stream.cpp +++ b/python/src/stream.cpp @@ -1,12 +1,13 @@ // Copyright © 2023-2024 Apple Inc. -#include - #include #include #include #include +#include +#include + #include "mlx/stream.h" #include "mlx/utils.h" #include "python/src/random.h" @@ -15,10 +16,11 @@ namespace mx = mlx::core; namespace nb = nanobind; using namespace nb::literals; -// Create the StreamContext on enter and delete on exit. +// Create a StreamContext on enter and delete it on exit. The contexts are +// stacked, so the same object can be entered more than once. class PyStreamContext { public: - PyStreamContext(mx::StreamOrDevice s) : _inner(nullptr) { + PyStreamContext(mx::StreamOrDevice s) { if (std::holds_alternative(s)) { throw std::runtime_error( "[StreamContext] Invalid argument, please specify a stream or device."); @@ -27,19 +29,33 @@ class PyStreamContext { } void enter() { - _inner = new mx::StreamContext(_s); + _contexts.push_back(new mx::StreamContext(_s)); } void exit() { - if (_inner != nullptr) { - delete _inner; - _inner = nullptr; + if (_contexts.empty()) { + return; + } + auto* inner = _contexts.back(); + _contexts.pop_back(); + // the destructor can throw, inner is freed regardless. + delete inner; + } + + // ~StreamContext throws when destroyed on a different thread, which Python + // cannot control + ~PyStreamContext() { + while (!_contexts.empty()) { + try { + exit(); + } catch (...) { + } } } private: mx::StreamOrDevice _s; - mx::StreamContext* _inner; + std::vector _contexts; }; void init_stream(nb::module_& m) { @@ -57,10 +73,13 @@ void init_stream(nb::module_& m) { os << s; return os.str(); }) - .def("__eq__", [](const mx::Stream& s, const nb::object& other) { - return nb::isinstance(other) && - s == nb::cast(other); - }); + .def( + "__eq__", + [](const mx::Stream& s, const nb::object& other) { + return nb::isinstance(other) && + s == nb::cast(other); + }) + .freeze(); nb::class_( m, @@ -81,7 +100,8 @@ void init_stream(nb::module_& m) { [](const mx::ThreadLocalStream& s, const nb::object& other) { return nb::isinstance(other) && s == nb::cast(other); - }); + }) + .freeze(); nb::implicitly_convertible(); @@ -140,6 +160,7 @@ void init_stream(nb::module_& m) { "clear_streams", []() { reset_random_state(); + nb::gil_scoped_release nogil; mx::clear_streams(); }, R"pbdoc(Destroy all streams created in current thread.)pbdoc"); @@ -162,7 +183,8 @@ void init_stream(nb::module_& m) { const std::optional& traceback) { scm.exit(); }, "exc_type"_a = nb::none(), "exc_value"_a = nb::none(), - "traceback"_a = nb::none()); + "traceback"_a = nb::none()) + .freeze(); m.def( "stream", [](mx::StreamOrDevice s) { return PyStreamContext(s); }, @@ -190,6 +212,7 @@ void init_stream(nb::module_& m) { m.def( "synchronize", [](mx::StreamOrDevice s) { + nb::gil_scoped_release nogil; if (std::holds_alternative(s)) { mx::synchronize(); } else { diff --git a/python/src/transforms.cpp b/python/src/transforms.cpp index e6a778eca0..223e232e29 100644 --- a/python/src/transforms.cpp +++ b/python/src/transforms.cpp @@ -1,10 +1,5 @@ // Copyright © 2023-2024 Apple Inc. -#include -#include -#include -#include - #include #include #include @@ -13,6 +8,11 @@ #include #include +#include +#include +#include +#include + #include "mlx/array.h" #include "mlx/compile.h" #include "mlx/compile_impl.h" @@ -310,7 +310,11 @@ auto py_vmap( const nb::callable& fun, const nb::object& in_axes, const nb::object& out_axes) { - return [fun, in_axes, out_axes](const nb::args& args) { + return [fun, in_axes, out_axes]( + const nb::args& args, const nb::kwargs& kwargs) { + if (kwargs.size()) { + throw nb::type_error("[vmap] Keyword arguments are not supported."); + } auto axes_to_flat_tree = [](const nb::object& tree, const nb::object& axes, bool output_axes) { @@ -334,7 +338,7 @@ auto py_vmap( msg << "[vmap] Invalid" << (output_axes ? " output " : " ") << "vectorization axis " << axis << " for array with shape " << x.shape(); - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } flat_axes.push_back(axis); } else if (nb::isinstance(inputs[1])) { @@ -351,7 +355,7 @@ auto py_vmap( msg << "[vmap] Invalid" << (output_axes ? " output " : " ") << "vectorization axis " << axis << " for array with shape " << x.shape(); - throw std::invalid_argument(msg.str()); + throw std::out_of_range(msg.str()); } flat_axes.push_back(axis); } else if (l.size() == 1 && l[0].is_none()) { @@ -814,8 +818,8 @@ class PyCustomFunction { } int array_index = 0; int tangent_index = 0; - auto new_tangents = - nb::cast(tree_map(args, [&](nb::handle element) { + auto new_tangents = nb::cast( + tree_map(args, [&](nb::handle element) -> nb::object { if (nb::isinstance(element) && have_tangents[array_index++]) { return nb::cast(tangents[tangent_index++]); @@ -861,8 +865,8 @@ class PyCustomFunction { } int arr_index = 0; - auto new_axes = - nb::cast(tree_map(args, [&](nb::handle element) { + auto new_axes = nb::cast( + tree_map(args, [&](nb::handle element) -> nb::object { int axis = axes[arr_index++]; if (nb::isinstance(element) && axis >= 0) { return nb::cast(axis); @@ -1170,7 +1174,8 @@ void init_transforms(nb::module_& m) { return a pytree with the vectorization axes of each output. If some outputs are no longer vectorized, then their vectorization axis should be ``None``. - )pbdoc"); + )pbdoc") + .freeze(); m.def( "eval", @@ -1471,7 +1476,7 @@ void init_transforms(nb::module_& m) { const nb::object& outputs, bool shapeless) { return mlx_func( - nb::cpp_function(PyCompiledFun{fun, inputs, outputs, shapeless}), + PyCompiledFun{fun, inputs, outputs, shapeless}, fun, inputs, outputs); diff --git a/python/src/trees.cpp b/python/src/trees.cpp index cf05d4e25a..38ba3a8a9a 100644 --- a/python/src/trees.cpp +++ b/python/src/trees.cpp @@ -273,14 +273,9 @@ nb::object tree_unflatten( } nb::object structure_sentinel() { - static nb::object sentinel = []() { - PyObject* raw_obj = PyObject_New(PyObject, &PyBaseObject_Type); - nb::object sentinel = nb::steal(raw_obj); - sentinel.inc_ref(); - return sentinel; - }(); + static nb::handle sentinel = PyObject_New(PyObject, &PyBaseObject_Type); - return sentinel; + return nb::borrow(sentinel); } std::pair, nb::object> tree_flatten_with_structure( diff --git a/python/src/utils.h b/python/src/utils.h index d2fcbd037e..f4d47b3f3d 100644 --- a/python/src/utils.h +++ b/python/src/utils.h @@ -1,15 +1,15 @@ // Copyright © 2023-2024 Apple Inc. #pragma once -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include +#include + #include "mlx/array.h" #include "python/src/convert.h" diff --git a/python/tests/mlx_distributed_tests.py b/python/tests/mlx_distributed_tests.py index cbb9663046..7d6e56aaac 100644 --- a/python/tests/mlx_distributed_tests.py +++ b/python/tests/mlx_distributed_tests.py @@ -325,6 +325,22 @@ def test_all_gather(self): self.assertEqual(y.shape, (world.size() * 2, 2, 4)) self.assertTrue(mx.all(y == 1)) + def test_all_gather_rank_data(self): + # Every rank contributes distinct data so that a missing, stale, or + # misplaced peer region is detected (an all-ones gather cannot tell). + # Sizes include one large enough that backends which slice transfers + # across directions/wires (e.g. the jaccl ring) exercise every slice, + # and odd sizes that exercise the tail clamping. + world = mx.distributed.init() + for size in [7, 1024, 1000003, 4 * 1024 * 1024]: + base = mx.arange(size, dtype=mx.int32) % 100003 + x = base + world.rank() + y = mx.distributed.all_gather(x) + self.assertEqual(y.shape, (world.size() * size,)) + regions = y.reshape(world.size(), size) + for r in range(world.size()): + self.assertTrue(mx.all(regions[r] == base + r).item()) + def test_clip_grad_norm_sharded(self): world = mx.distributed.init() N = world.size() diff --git a/python/tests/mlx_tests.py b/python/tests/mlx_tests.py index 2b60f46154..10a7e5c35f 100644 --- a/python/tests/mlx_tests.py +++ b/python/tests/mlx_tests.py @@ -1,5 +1,6 @@ # Copyright © 2023 Apple Inc. +import contextlib import os import platform import sys @@ -10,6 +11,26 @@ import numpy as np +@contextlib.contextmanager +def scoped_env(**environ): + """ + Temporarily set the process environment variables. + + Passing a value of None removes the variable for the duration of the context. + """ + old_environ = dict(os.environ) + for key, value in environ.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + try: + yield + finally: + os.environ.clear() + os.environ.update(old_environ) + + class MLXTestRunner(unittest.TestProgram): def __init__(self, *args, **kwargs): # Do not exit in runTests @@ -37,7 +58,8 @@ def setUp(self): def tearDown(self): mx.set_default_device(self.default) - # Note if a tuple is passed into args, it will be considered a shape request and convert to a mx.random.normal with the shape matching the tuple + # Note if a tuple is passed into args, it will be considered a shape request and + # convert to a mx.random.normal with the shape matching the tuple def assertCmpNumpy( self, args: List[Union[Tuple[int], Any]], diff --git a/python/tests/nccl_test_distributed.py b/python/tests/nccl_test_distributed.py index db9bbb2e62..be3f38e2eb 100644 --- a/python/tests/nccl_test_distributed.py +++ b/python/tests/nccl_test_distributed.py @@ -143,7 +143,6 @@ def loss_fn(model, x, y): return ((logits - y) ** 2).mean() for dtype, atol, rtol in dtypes: - mx.random.seed(0xF0F0F0F0) kx, ky = mx.random.split(mx.random.key(rank)) diff --git a/python/tests/ring_test_distributed.py b/python/tests/ring_test_distributed.py index 31db2ed5f7..aba897ea1d 100644 --- a/python/tests/ring_test_distributed.py +++ b/python/tests/ring_test_distributed.py @@ -21,7 +21,17 @@ def test_groups(self): self.assertEqual(world.rank(), world2.rank()) with self.assertRaises(RuntimeError): - sub = world.split(world.rank() % 2) + world.split(world.rank() % 2) + + def test_strict_init_after_fallback(self): + with mlx_tests.scoped_env( + JACCL_IBV_DEVICES=None, + MLX_IBV_DEVICES=None, + ): + self.assertEqual(mx.distributed.init(backend="jaccl").size(), 1) + + with self.assertRaises(RuntimeError): + mx.distributed.init(backend="jaccl", strict=True) def test_all_reduce_extra(self): world = mx.distributed.init() diff --git a/python/tests/run.py b/python/tests/run.py index df96d4dd36..b5c1dbd704 100644 --- a/python/tests/run.py +++ b/python/tests/run.py @@ -9,7 +9,7 @@ __unittest = True -import mlx_tests +import mlx_tests # noqa: E402 if __name__ == "__main__": # Run all tests by default. diff --git a/python/tests/test_array.py b/python/tests/test_array.py index 80459fabe5..425a592687 100644 --- a/python/tests/test_array.py +++ b/python/tests/test_array.py @@ -1,7 +1,6 @@ # Copyright © 2023-2024 Apple Inc. import operator -import os import pickle import platform import sys @@ -140,6 +139,30 @@ def test_scalar_conversion(self): self.assertListEqual(list(z.shape), list(x.shape)) self.assertListEqual(list(z.shape), list(y.shape)) + def test_index_conversion(self): + for dtype in [ + mx.uint8, + mx.uint16, + mx.uint32, + mx.uint64, + mx.int8, + mx.int16, + mx.int32, + mx.int64, + ]: + with self.subTest(dtype=dtype): + self.assertEqual(operator.index(mx.array(2, dtype)), 2) + self.assertEqual(list(range(mx.array(3, dtype))), [0, 1, 2]) + + def test_index_conversion_invalid(self): + for dtype in [mx.float16, mx.float32, mx.bfloat16, mx.complex64, mx.bool_]: + with self.subTest(dtype=dtype): + with self.assertRaises(TypeError): + operator.index(mx.array(2, dtype)) + + with self.assertRaises(TypeError): + list(range(mx.array(3, dtype))) + def test_finfo(self): with self.assertRaises(ValueError): mx.finfo(mx.int32) @@ -468,6 +491,27 @@ def test_array_basics(self): self.assertEqual(x.dtype, mx.int32) self.assertEqual(x.tolist(), [1, 2, 3]) + def test_matrix_transpose(self): + x = mx.array([[1, 2], [3, 4]]) + self.assertEqual(x.mT.tolist(), [[1, 3], [2, 4]]) + self.assertEqual(mx.matrix_transpose(x).tolist(), [[1, 3], [2, 4]]) + + x = mx.arange(24).reshape((2, 3, 4)) + self.assertEqual(x.mT.shape, (2, 4, 3)) + self.assertEqualArray(x.mT, x.transpose((0, 2, 1))) + self.assertEqualArray(x.mT.mT, x) + + self.assertEqual(mx.matrix_transpose(x).shape, (2, 4, 3)) + self.assertEqualArray(mx.matrix_transpose(x), x.transpose((0, 2, 1))) + + x = mx.array([1, 2, 3]) + + with self.assertRaises(ValueError): + x.mT + + with self.assertRaises(ValueError): + mx.matrix_transpose(x) + def test_bool_conversion(self): x = mx.array(True) self.assertTrue(x) @@ -554,6 +598,18 @@ def test_double_keeps_precision(self): out = mx.array([x], dtype=mx.float64).item() self.assertEqual(out, x) + # Integer and bool targets + v = 2**24 + 1 + self.assertEqual(mx.array(float(v), dtype=mx.int32).item(), v) + self.assertEqual(mx.array([float(v)], dtype=mx.int64).tolist(), [v]) + # Small non-zero values are still True + self.assertTrue(mx.array(1e-50, dtype=mx.bool_).item()) + self.assertEqual(mx.array([1e-50], dtype=mx.bool_).tolist(), [True]) + + # Python ints to float64 + out = mx.array([v], dtype=mx.float64).tolist() + self.assertEqual(out, [float(v)]) + def test_construction_from_lists_wide_ints(self): # A python int that does not fit in int32 widens to int64, the same # rule the scalar path already uses. It used to raise std::bad_cast. @@ -604,7 +660,8 @@ def test_construction_from_lists_of_mlx_arrays(self): expected = mx.stack([x, y], axis=0) self.assertEqualArray(z, expected) - # check heterogeneous construction with mlx arrays and python primitive types + # check heterogeneous construction with mlx arrays and python primitive + # types x, y = mx.array([True], x_t), mx.array([False], y_t) z = mx.array([[x, [2.0]], [[3.0], y]]) expected = mx.array([[[x.item()], [2.0]], [[3.0], [y.item()]]], z.dtype) @@ -1017,11 +1074,14 @@ def test_array_comparison(self): self.assertEqual((a > 1).tolist(), [False, False, True]) self.assertEqual((a >= 1).tolist(), [False, True, True]) - def test_array_neg(self): + def test_array_unary_ops(self): a = mx.array([-1.0, 4.0, 0.0]) self.assertEqual((-a).tolist(), [1.0, -4.0, 0.0]) + self.assertEqual((+a).tolist(), [-1.0, 4.0, 0.0]) + assert +a is not a + def test_array_type_cast(self): a = mx.array([0.1, 2.3, -1.3]) b = [0, 2, -1] @@ -1044,6 +1104,10 @@ def test_array_iteration(self): self.assertEqual(y.tolist(), [3.0, 4.0]) self.assertEqual(z.tolist(), [5.0, 6.0]) + a = mx.array(3) + with self.assertRaises(TypeError): + list(a) + def test_array_pickle(self): dtypes = [ mx.int8, @@ -1065,6 +1129,10 @@ def test_array_pickle(self): state = pickle.dumps(x) y = pickle.loads(state) self.assertEqualArray(y, x) + # F-contiguous + x = x.T + y = pickle.loads(pickle.dumps(x)) + self.assertEqualArray(y, x) def test_array_copy(self): dtypes = [ @@ -1206,7 +1274,7 @@ def check_slices(arr_np, *idx_np): idx_mlx = [ mx.array(idx) if isinstance(idx, np.ndarray) else idx for idx in idx_np ] - slice_mlx = arr_mlx[tuple(idx_mlx)] + _slice_mlx = arr_mlx[tuple(idx_mlx)] self.assertTrue( np.array_equal(arr_np[tuple(idx_np)], arr_mlx[tuple(idx_mlx)]) ) @@ -1267,6 +1335,13 @@ def check_slices(arr_np, *idx_np): a_mlx = mx.array(a_np) self.assertTrue(np.array_equal(a_np[2:-1, 0], np.array(a_mlx[2:-1, 0]))) + # Ellipsis with more trailing indices than dimensions + a_mlx = mx.array([1, 2, 3]) + with self.assertRaises(ValueError): + a_mlx[..., 0, 0] + with self.assertRaises(ValueError): + a_mlx[..., 0, 0] = 5 + def test_indexing_grad(self): x = mx.array([[1, 2], [3, 4]]).astype(mx.float32) ind = mx.array([0, 1, 0]).astype(mx.float32) @@ -1310,7 +1385,7 @@ def test_setitem(self): a[0:2] = 3 self.assertEqual(a.tolist(), [3, 3, 1]) - # Assigning through a bare Ellipsis, like a[:] and a[None] + # Assigning through a bare Ellipsis, like a[:] and a[(...,)] e = mx.zeros((2, 3), mx.int32) e[...] = 5 self.assertEqual(e.tolist(), [[5, 5, 5], [5, 5, 5]]) @@ -1322,16 +1397,44 @@ def test_setitem(self): e[...] = mx.zeros((2, 3), mx.int32) self.assertEqual(e.tolist(), [[0, 0, 0], [0, 0, 0]]) + # Leading singleton dimensions of the update are squeezed + e[...] = mx.array([[[1, 2, 3], [4, 5, 6]]]) + self.assertEqual(e.tolist(), [[1, 2, 3], [4, 5, 6]]) + + # The target keeps its leading dimension of size 1 + h = mx.zeros((1, 3), mx.int32) + h[...] = mx.array([[[1, 2, 3]]]) + self.assertEqual(h.tolist(), [[1, 2, 3]]) + + # a[...] assigns the same values as a[(...,)] + f = mx.zeros((3,), mx.int32) + g = mx.zeros((3,), mx.int32) + f[...] = mx.array([[1, 2, 3]]) + g[(...,)] = mx.array([[1, 2, 3]]) + self.assertEqual(f.tolist(), [1, 2, 3]) + self.assertEqual(f.tolist(), g.tolist()) + # Scalar array e = mx.array(0) e[...] = 7 self.assertEqual(e.item(), 7) + e[...] = mx.array([[9]]) + self.assertEqual(e.tolist(), 9) + # Shapes that cannot broadcast are still rejected e = mx.zeros((2, 3), mx.int32) with self.assertRaises(ValueError): e[...] = mx.array([1, 2]) + # The squeeze stops at the first dimension that is not 1 + with self.assertRaises(ValueError): + e[...] = mx.zeros((2, 1, 3), mx.int32) + + # A squeezed update that still does not broadcast is rejected + with self.assertRaises(ValueError): + e[...] = mx.zeros((1, 4), mx.int32) + a[0:3] = 4 self.assertEqual(a.tolist(), [4, 4, 4]) @@ -1341,6 +1444,13 @@ def test_setitem(self): a[0:1] = mx.array([1]) self.assertEqual(a.tolist(), [1, 4, 4]) + # Regression test: a negative integer index after a None + # (newaxis) used to be normalized against the wrong axis size, + # silently writing nothing instead of updating the last row. + b = mx.zeros((3, 4)) + b[None, -1] = 9 + self.assertEqual(b.tolist(), [[0, 0, 0, 0], [0, 0, 0, 0], [9, 9, 9, 9]]) + with self.assertRaises(ValueError): a[0:1] = mx.array([2, 3]) @@ -1637,6 +1747,13 @@ def test_array_at(self): a = a.at[1:3, :, 0].minimum(update) self.assertEqualArray(a[1:3, :, 0], mx.minimum(a[1:3, :, 0], update)) + # Indices and updates with negative strides + idx = mx.array([0, 1, 2, 3]) + upd = mx.array([1.0, 2.0, 3.0, 4.0]) + expected = [4.0, 3.0, 2.0, 1.0] + self.assertEqual(mx.zeros(4).at[idx[::-1]].add(upd).tolist(), expected) + self.assertEqual(mx.zeros(4).at[idx].add(upd[::-1]).tolist(), expected) + @unittest.skipIf(not mx.is_available(mx.gpu), "No GPU available") def test_array_at_complex_add_gpu(self): n = 4096 @@ -1840,6 +1957,33 @@ def test_slice_negative_step(self): b_mx = a_mx[::-1, ::-3, ::-2] self.assertTrue(np.array_equal(b_np, b_mx)) + def test_slice_bounds_with_array_index(self): + # Out-of-range slice bounds must be clamped the same way NumPy clamps + # them when the slice is combined with an array index. + a_np = np.arange(20, dtype=np.int32).reshape(4, 5) + a_mx = mx.array(a_np) + idx_np = np.array([0, 1]) + idx_mx = mx.array([0, 1], dtype=mx.uint32) + + bounds = [None, -100, -6, -4, -1, 0, 1, 3, 4, 6, 100] + steps = [None, 1, 2, 3, -1, -2, -3] + + for start in bounds: + for stop in bounds: + for step in steps: + s = slice(start, stop, step) + with self.subTest(start=start, stop=stop, step=step): + self.assertTrue( + np.array_equal(a_np[s, idx_np], a_mx[s, idx_mx]) + ) + + # Same clamping applies when assigning through the slice + u_np = a_np.copy() + u_mx = mx.array(a_np) + u_np[s, idx_np] = 0 + u_mx[s, idx_mx] = 0 + self.assertTrue(np.array_equal(u_np, u_mx)) + def test_api(self): x = mx.array(np.random.rand(10, 10, 10)) ops = [ @@ -1959,7 +2103,8 @@ def test_buffer_protocol(self): self.assertEqual(mv_mx.shape, mv_np.shape, f"{mlx_dtype}{np_dtype}") # correct buffer format for 8 byte (unsigned) 'long long' is Q/q, see # https://docs.python.org/3.10/library/struct.html#format-characters - # numpy returns L/l, as 'long' is equivalent to 'long long' on 64bit machines, so q and l are equivalent + # numpy returns L/l, as 'long' is equivalent to 'long long' on 64bit + # machines, so q and l are equivalent # see https://github.com/pybind/pybind11/issues/1908 if np_dtype == np.uint64: self.assertEqual(mv_mx.format, "Q", f"{mlx_dtype}{np_dtype}") @@ -2004,6 +2149,15 @@ def test_buffer_protocol(self): self.assertEqual(b"aaaaaaaaaa", ab[::2]) self.assertEqual(b"abcdefghij", ab[1::2]) + # Test bytes on non-contiguous arrays + a = mx.arange(10, dtype=mx.uint8) + self.assertEqual(bytes(a[::2]), b"\x00\x02\x04\x06\x08") + self.assertEqual(bytes(a[::-1]), b"\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00") + b = mx.arange(6, dtype=mx.int32).reshape(2, 3).T + self.assertEqual(bytes(b), np.array(b).tobytes()) + c = mx.broadcast_to(mx.array([1, 2], dtype=mx.uint8), (3, 2)) + self.assertEqual(bytes(c), np.array(c).tobytes()) + def test_buffer_protocol_ref_counting(self): a = mx.arange(3) wr = weakref.ref(a) @@ -2011,9 +2165,15 @@ def test_buffer_protocol_ref_counting(self): mv = memoryview(a) a = None self.assertIsNotNone(wr()) - mv = None + del mv self.assertIsNone(wr()) + def test_buffer_protocol_eval_error(self): + # Errors from evaluating the array are raised instead of aborting + a = mx.linalg.inv(mx.zeros((2, 2)), stream=mx.cpu) + with self.assertRaises(RuntimeError): + memoryview(a) + def test_array_view_ref_counting(self): a = mx.arange(3) wr = weakref.ref(a) @@ -2021,7 +2181,7 @@ def test_array_view_ref_counting(self): a_np = np.array(a, copy=False) a = None self.assertIsNotNone(wr()) - a_np = None + del a_np self.assertIsNone(wr()) def test_create_from_buffer(self): @@ -2397,7 +2557,7 @@ def test_torch_mps_asarray_copy_true_copies_dlpack_input(self): self.assertEqual(y.tolist(), [0.0, 1.0, 2.0]) @unittest.skipUnless(has_torch_mps, "PyTorch MPS is required") - def test_torch_mps_dlpack_zero_copy_shares_updates(self): + def test_torch_mps_dlpack_zero_copy_one_way_updates(self): assert torch is not None x = torch.arange(12, device="mps", dtype=torch.float32).reshape(3, 4) torch.mps.synchronize() @@ -2409,7 +2569,8 @@ def test_torch_mps_dlpack_zero_copy_shares_updates(self): y += 10 mx.eval(y) - self.assertEqual(x.cpu().numpy().tolist(), y.tolist()) + self.assertEqual(y.tolist(), [[10.0] * 4] * 3) + self.assertEqual(x.cpu().numpy().tolist(), [[0.0] * 4] * 3) @unittest.skipUnless(has_torch_mps, "PyTorch MPS is required") def test_torch_mps_dlpack_matching_dtype_argument_shares_updates(self): @@ -2574,7 +2735,7 @@ def test_mlx_dlpack_export_torch_update_writes_mlx_buffer(self): self.assertEqual(x.tolist(), [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 6.0, 7.0]) @unittest.skipUnless(has_torch_mps, "PyTorch MPS is required") - def test_from_dlpack_torch_mps_copy_none_shares_updates(self): + def test_from_dlpack_torch_mps_copy_none_one_way_updates(self): assert torch is not None x = torch.arange(3, device="mps", dtype=torch.float32) torch.mps.synchronize() @@ -2586,7 +2747,8 @@ def test_from_dlpack_torch_mps_copy_none_shares_updates(self): y += 10 mx.eval(y) - self.assertEqual(x.cpu().numpy().tolist(), [10.0, 10.0, 10.0]) + self.assertEqual(y.tolist(), [10.0, 10.0, 10.0]) + self.assertEqual(x.cpu().numpy().tolist(), [0.0, 0.0, 0.0]) @unittest.skipUnless(has_torch_mps, "PyTorch MPS is required") def test_from_dlpack_torch_mps_copy_false_shares_updates(self): @@ -2695,6 +2857,13 @@ def test_setitem_with_boolean_mask(self): a[mask] = 5.0 self.assertTrue(mx.array_equal(a, expected)) + # Scalar target and scalar mask + for selected in (False, True): + a = mx.array(False) + a[mx.array(selected)] = True + self.assertEqual(a.shape, ()) + self.assertEqual(a.item(), selected) + mask_np = np.zeros((1, 10, 10), dtype=bool) with self.assertRaises(ValueError): mx.arange(1000).reshape(10, 10, 10)[mask_np] = 0 @@ -2819,7 +2988,7 @@ def test_format(self): self.assertEqual(f"{b:.1f}", "0.4") with self.assertRaises(TypeError): - s = f"{a:.2f}" + f"{a:.2f}" a = mx.array([1, 2, 3]) self.assertEqual(f"{a}", "array([1, 2, 3], dtype=int32)") @@ -2875,6 +3044,41 @@ def test_large_indices(self): with self.assertRaises(ValueError): x[2**32] + @unittest.skipUnless(sys.version_info >= (3, 15), "requires Python 3.15") + def test_frozen_types(self): + types = ( + mx.array, + mx.Dtype, + mx.finfo, + mx.iinfo, + mx.ArrayAt, + mx.ArrayLike, + mx.ArrayIterator, + mx.Device, + mx.Stream, + mx.ThreadLocalStream, + mx.StreamContext, + mx.PrintOptions, + mx.custom_function, + mx.FunctionExporter, + mx.distributed.Group, + ) + for bound_type in types: + with self.subTest(type=bound_type): + with self.assertRaises(TypeError): + bound_type._test_attribute = None + with self.assertRaises(TypeError): + bound_type.__doc__ = "modified" + with self.assertRaises(TypeError): + del bound_type.__doc__ + + def test_array_subclass(self): + class Array(mx.array): + def total(self): + return self.sum().item() + + self.assertEqual(Array([1, 2, 3]).total(), 6) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_autograd.py b/python/tests/test_autograd.py index c85fcf09a6..bd4a4870ef 100644 --- a/python/tests/test_autograd.py +++ b/python/tests/test_autograd.py @@ -4,6 +4,7 @@ import itertools import math import unittest +import weakref import mlx.core as mx import mlx_tests @@ -19,18 +20,24 @@ class TestAutograd(mlx_tests.MLXTestCase): def test_jvp(self): - fun = lambda x: 2 * x + def fun(x): + return 2 * x + out, dout = mx.jvp(fun, [mx.array(1.0)], [mx.array(2.0)]) self.assertEqual(out[0].item(), 2.0) self.assertEqual(dout[0].item(), 4.0) - fun = lambda x, y: x * y + def fun(x, y): + return x * y + _, out = mx.jvp( fun, [mx.array(4.0), mx.array(2.0)], [mx.array(3.0), mx.array(2.0)] ) self.assertEqual(out[0].item(), 4.0 * 2.0 + 2.0 * 3.0) - fun = lambda x, y, z: (x * y, y * z) + def fun(x, y, z): + return (x * y, y * z) + _, out = mx.jvp( fun, [mx.array(2.0), mx.array(4.0), mx.array(6.0)], @@ -40,6 +47,55 @@ def test_jvp(self): self.assertEqual(out[0].item(), 4.0 * 1.0 + 2.0 * 3.0) self.assertEqual(out[1].item(), 4.0 * 1.0 + 6.0 * 3.0) + def test_logcumsumexp_jvp(self): + x = mx.array([0.0, 0.0, 0.0]) + t = mx.array([1.0, 1.0, 1.0]) + + for rev in (False, True): + + def f(z): + return mx.logcumsumexp(z, axis=0, reverse=rev, inclusive=True) + + _, (dout,) = mx.jvp(f, [x], [t]) + self.assertTrue(mx.allclose(dout, mx.array([1.0, 1.0, 1.0]))) + + def f(z): + return mx.logcumsumexp(z, axis=0, reverse=False, inclusive=False) + + _, (dout,) = mx.jvp(f, [x], [t]) + self.assertTrue(mx.allclose(dout, mx.array([0.0, 1.0, 1.0]))) + + def f(z): + return mx.logcumsumexp(z, axis=0, reverse=True, inclusive=False) + + _, (dout,) = mx.jvp(f, [x], [t]) + self.assertTrue(mx.allclose(dout, mx.array([1.0, 1.0, 0.0]))) + + x = mx.array([1000.0, 1000.0, 1000.0]) + + def f(z): + return mx.logcumsumexp(z, axis=0, reverse=False, inclusive=True) + + _, (dout,) = mx.jvp(f, [x], [t]) + self.assertTrue(mx.allclose(dout, mx.array([1.0, 1.0, 1.0]))) + + x = mx.array([1.0, 2.0, 3.0]) + t = mx.array([1.0, -2.0, 0.5]) + eps = 1e-3 + + def f(z): + return mx.logcumsumexp(z, axis=0) + + _, (dout,) = mx.jvp(f, [x], [t]) + + expected = (f(x + eps * t) - f(x - eps * t)) / (2 * eps) + self.assertTrue(mx.allclose(dout, expected, atol=1e-3)) + + x = mx.array([1.0, 2.0], dtype=mx.complex64) + t = mx.array([1 + 1j, 2 - 1j]) + with self.assertRaises(ValueError): + mx.jvp(f, [x], [t]) + def test_jvp_comparison_tangent_dtype(self): # Comparison op JVP tangents should preserve the input tangent's # dtype (e.g. float32), not return bool. Using bool tangents causes @@ -135,17 +191,23 @@ def fun(x): self.assertTrue(mx.array_equal(dout, mx.array([1.0, 0.0, 1.0]))) def test_vjp(self): - fun = lambda x: 2 * x + def fun(x): + return 2 * x + out, dout = mx.vjp(fun, [mx.array(1.0)], [mx.array(2.0)]) self.assertEqual(out[0].item(), 2.0) self.assertEqual(dout[0].item(), 4.0) - fun = lambda x, y: x * y + def fun(x, y): + return x * y + _, dout = mx.vjp(fun, [mx.array(4.0), mx.array(2.0)], [mx.array(3.0)]) self.assertEqual(dout[0].item(), 6.0) self.assertEqual(dout[1].item(), 12.0) - fun = lambda x, y, z: (x * y, y * z) + def fun(x, y, z): + return (x * y, y * z) + _, out = mx.vjp( fun, [mx.array(2.0), mx.array(4.0), mx.array(6.0)], @@ -158,7 +220,9 @@ def test_vjp(self): def test_jvp_with_partly_traced_inputs(self): # power: each traced input must use its own tangent (issue #3634) - fun = lambda a, b: a**b + def fun(a, b): + return a**b + primals = [mx.array(2.0), mx.array(3.0)] dyda = 12.0 # d/da a^b = b * a^(b - 1) dydb = math.log(2.0) * 8.0 # d/db a^b = ln(a) * a^b @@ -168,10 +232,16 @@ def test_jvp_with_partly_traced_inputs(self): self.assertAlmostEqual(j.item(), dydb, places=4) _, (j,) = mx.jvp(fun, primals, [mx.array(1.0), mx.array(1.0)]) self.assertAlmostEqual(j.item(), dyda + dydb, places=4) - fun = lambda a: a ** mx.array(3.0) + + def fun(a): + return a ** mx.array(3.0) + _, (j,) = mx.jvp(fun, [mx.array(2.0)], [mx.array(1.0)]) self.assertAlmostEqual(j.item(), dyda, places=4) - fun = lambda b: mx.array(2.0) ** b + + def fun(b): + return mx.array(2.0) ** b + _, (j,) = mx.jvp(fun, [mx.array(3.0)], [mx.array(1.0)]) self.assertAlmostEqual(j.item(), dydb, places=4) @@ -190,18 +260,28 @@ def fun(x): src = mx.zeros(4) upd = mx.ones(2) start = mx.array([1]) - fun = lambda u: mx.slice_update(src, u, start, axes=[0]) + + def fun(u): + return mx.slice_update(src, u, start, axes=[0]) + _, (j,) = mx.jvp(fun, [upd], [mx.ones(2)]) self.assertEqual(j.tolist(), [0.0, 1.0, 1.0, 0.0]) - fun = lambda s: mx.slice_update(s, upd, start, axes=[0]) + + def fun(s): + return mx.slice_update(s, upd, start, axes=[0]) + _, (j,) = mx.jvp(fun, [src], [mx.ones(4)]) self.assertEqual(j.tolist(), [1.0, 0.0, 0.0, 1.0]) - fun = lambda s, u: mx.slice_update(s, u, start, axes=[0]) + + def fun(s, u): + return mx.slice_update(s, u, start, axes=[0]) + _, (j,) = mx.jvp(fun, [src, upd], [mx.ones(4), mx.full(2, 2.0)]) self.assertEqual(j.tolist(), [1.0, 2.0, 2.0, 1.0]) def test_grad(self): - fun = lambda x: x * x + def fun(x): + return x * x value, dfdx = mx.value_and_grad(fun)(mx.array(0.5)) self.assertEqual(value.item(), 0.25) @@ -215,7 +295,9 @@ def test_grad(self): df3dx3 = mx.grad(mx.grad(mx.grad(fun)))(mx.array(0.5)) self.assertEqual(df3dx3.item(), 0.0) - fun = lambda x, y: x * y + def fun(x, y): + return x * y + x = mx.array(2.0) y = mx.array(3.0) dfdx = mx.grad(fun, argnums=0)(x, y) @@ -224,7 +306,9 @@ def test_grad(self): self.assertEqual(dfdx.item(), 2.0) # Pass non array args to functions works - fun = lambda x, y: x + def fun(x, y): + return x + value, dfdx = mx.value_and_grad(fun)(mx.array(2.0), "hello") self.assertEqual(value.item(), 2.0) self.assertEqual(dfdx.item(), 1.0) @@ -233,12 +317,16 @@ def test_grad(self): self.assertEqual(dfdx.item(), 1.0) # Raises when function does not return array - fun = lambda x: "hello" + def fun(x): + return "hello" + with self.assertRaises(ValueError): mx.grad(fun)(mx.array(2.0)) # Raises for invalid argument number or argument type - fun = lambda x: x + def fun(x): + return x + with self.assertRaises(ValueError): mx.grad(fun, argnums=2)(mx.array(2.0)) with self.assertRaises(ValueError): @@ -247,43 +335,57 @@ def test_grad(self): mx.grad(fun)("hello") # Raises when output is not a scalar array - fun = lambda x: mx.sum(x, keepdims=True) + def fun(x): + return mx.sum(x, keepdims=True) + with self.assertRaises(ValueError): mx.grad(fun)(mx.ones((2, 2))) def test_grad_trees(self): - fun = lambda x, y: x * y + def fun(x, y): + return x * y + value, dfdx = mx.value_and_grad(fun, (0, 1))(mx.array(0.5), mx.array(2.0)) self.assertEqual(value.item(), 1.0) self.assertTrue(isinstance(dfdx, tuple)) self.assertEqual(dfdx[0].item(), 2.0) self.assertEqual(dfdx[1].item(), 0.5) - fun = lambda x, y: x * y + def fun(x, y): + return x * y + value, dfdx = mx.value_and_grad(fun, 1)(mx.array(0.5), mx.array(2.0)) self.assertEqual(value.item(), 1.0) self.assertEqual(dfdx.item(), 0.5) - fun = lambda p: p["x"] * p["y"] + def fun(p): + return p["x"] * p["y"] + value, dfdx = mx.value_and_grad(fun)({"x": mx.array(0.5), "y": mx.array(2.0)}) self.assertEqual(value.item(), 1.0) self.assertEqual(dfdx["x"].item(), 2.0) self.assertEqual(dfdx["y"].item(), 0.5) - fun = lambda p: p["x"] * p["y"] + def fun(p): + return p["x"] * p["y"] + with self.assertRaises(ValueError): mx.value_and_grad(fun)({"x": 0.5, "y": mx.array(2.0)}) with self.assertRaises(ValueError): mx.value_and_grad(fun, (0, 1))({"x": mx.array(0.5), "y": mx.array(2.0)}) - fun = lambda p, b: mx.square(p[0]["foo"][2]) * b + def fun(p, b): + return mx.square(p[0]["foo"][2]) * b + value, dfdx = mx.value_and_grad(fun)( [{"foo": [[], [], mx.array(2.0)]}], mx.array(0.5) ) self.assertEqual(value.item(), 2.0) self.assertEqual(dfdx[0]["foo"][2].item(), 2.0) - fun = lambda x: x + def fun(x): + return x + with self.assertRaises(TypeError): mx.value_and_grad(fun, (None, None)) with self.assertRaises(ValueError): @@ -293,9 +395,13 @@ def test_grad_trees(self): def test_auxiliary_values(self): def fun(x, y): - l = (x * y).sum() - extra = {"loss": l, "foo": y.square() + x.square(), "bar": [1, 2, 3, y, x]} - return l, extra + loss = (x * y).sum() + extra = { + "loss": loss, + "foo": y.square() + x.square(), + "bar": [1, 2, 3, y, x], + } + return loss, extra fun_value_grad = mx.value_and_grad(fun) fun_grad = mx.grad(fun) @@ -312,7 +418,9 @@ def fun(x, y): _ = fun_grad(mx.ones((2, 2)), mx.ones((2, 2))) def test_grad_kwargs(self): - fun = lambda x, y: x * y + def fun(x, y): + return x * y + a, b = mx.array(0.5), mx.array(2.0) dfdx = mx.grad(fun) self.assertEqual(dfdx(a, b).item(), 2.0) @@ -343,7 +451,9 @@ def test_grad_kwargs(self): self.assertTrue(isinstance(grads[1], dict)) self.assertEqual(grads[1]["y"].item(), 0.5) - fun = lambda x, y, z: x * y * z + def fun(x, y, z): + return x * y * z + dfdxyz = mx.grad(fun, argnums=[0, 1], argnames=["z"]) c = mx.array(4.0) grads = dfdxyz(a, b, z=c) @@ -354,7 +464,9 @@ def test_grad_kwargs(self): self.assertTrue(isinstance(grads[1], dict)) self.assertEqual(grads[1]["z"].item(), 1.0) - fun = lambda x, y: x * y + def fun(x, y): + return x * y + dfdy = mx.grad(fun, argnames=["y"]) grads = dfdy(a, y=b) self.assertTrue(isinstance(grads, tuple)) @@ -364,9 +476,15 @@ def test_grad_kwargs(self): def test_captured(self): a = mx.array(5.0) - f = lambda x: a + x - g = lambda x: a + a - h = lambda x: x + x + + def f(x): + return a + x + + def g(x): + return a + a + + def h(x): + return x + x dfdx = mx.grad(f) self.assertEqual(dfdx(a).item(), 1.0) @@ -404,7 +522,9 @@ def h(w, x): self.assertTrue(mx.allclose(vjps[0], 24.0 * mx.ones(shape_in))) self.assertTrue(mx.allclose(vjps[1], mx.zeros(shape_in))) - g = lambda x: h(w_in, x) + def g(x): + return h(w_in, x) + vals, vjps = mx.vjp(g, [x_in], [cotan]) mx.eval(vjps) @@ -731,7 +851,7 @@ def func(x): _, vjps = mx.vjp(func, (arr,), (cotan,)) self.assertEqual(vjps[0].item(), 8.0) - def test_power_grad(self): + def test_power_grad(self): # noqa: F811 def fun(x, y): res = x - y return res**x @@ -1105,7 +1225,7 @@ def outer_f(a, b): out1, dout1 = mx.jvp(outer_f, inputs, tans) @my_double.jvp - def random_grads(primals, tangents): + def random_grads(primals, tangents): # noqa: F811 return { "out": 2 * primals["x"] * tangents["y"] + 2 * primals["y"] * tangents["x"] @@ -1261,6 +1381,51 @@ def fun(a, b): expected[4:-5:-2] = tan_b self.assertTrue(mx.allclose(grad, expected)) + def test_slice_grads_single_element(self): + # A strided slice selecting exactly one element must place each + # cotangent at the position the forward pass read it from, not over + # the whole half-open span (regression: the stride was collapsed to 1 + # without narrowing stop, so the vjp re-derived a wider region). + def grad_of(fun, x): + return mx.grad(fun)(x) + + # positive stride, first element of a length-2 axis + x = mx.zeros((2, 3)) + Wa = mx.ones((1, 3)) + Wb = mx.ones((1, 3)) * 2 + + def fun(z): + return (z[0::2] * Wa).sum() + (z[1::2] * Wb).sum() + + g = grad_of(fun, x) + self.assertTrue(mx.allclose(g, mx.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]))) + + # positive stride, single element in a longer span + x = mx.zeros((8, 2)) + W = mx.ones((1, 2)) + g = grad_of(lambda z: (z[2:5:3] * W).sum(), x) + expected = mx.zeros((8, 2)) + expected[2] = W + self.assertTrue(mx.allclose(g, expected)) + + # negative stride, single element + x = mx.zeros((2, 2)) + W = mx.ones((1, 2)) + g = grad_of(lambda z: (z[::-2] * W).sum(), x) + expected = mx.zeros((2, 2)) + expected[1] = W + self.assertTrue(mx.allclose(g, expected)) + + # negative stride with start == 0 (cannot be expressed as a + # single-element negative-stride span; the unit-stride fallback must + # still land the cotangent at index 0) + x = mx.zeros((3, 2)) + W = mx.ones((1, 2)) + g = grad_of(lambda z: (z[0::-1] * W).sum(), x) + expected = mx.zeros((3, 2)) + expected[0] = W + self.assertTrue(mx.allclose(g, expected)) + def test_leaks(self): for transform in [ mx.grad, @@ -1319,6 +1484,34 @@ def fun(arrs): self.assertNotEqual(id(a_1), id(arrs[1])) self.assertEqual(id(a_2), id(arrs[2])) + def test_pad_value_grad(self): + x = mx.ones((2, 3)) + v = mx.array(5.0) + + def fun(x, v): + return mx.pad(x, pad_width=1, constant_values=v).sum() + + # Padded elements: 4 * 5 - 2 * 3 = 14 + gx, gv = mx.grad(fun, argnums=(0, 1))(x, v) + self.assertTrue(mx.array_equal(gx, mx.ones((2, 3)))) + self.assertEqual(gv.item(), 14.0) + + _, (tangent,) = mx.jvp(fun, [x, v], [mx.zeros((2, 3)), mx.array(1.0)]) + self.assertEqual(tangent.item(), 14.0) + + def test_conv_second_order_grad_with_padding(self): + x = mx.random.normal((1, 4, 4, 1)) + w = mx.random.normal((1, 2, 2, 1)) + + def wgrad_sum(x_): + def fn(w_): + return mx.conv2d(x_, w_, padding=(1, 2)).sum() + + return mx.grad(fn)(w).sum() + + dx = mx.grad(wgrad_sum)(x) + self.assertEqual(dx.shape, x.shape) + def test_grad_with_inplace_update(self): def loss_fn(model): model[1] = mx.array(2.0) @@ -1474,8 +1667,22 @@ def test_complex_unary_vjps(self): mx.tan: lambda x: 1 / mx.cos(x) ** 2, mx.tanh: lambda x: 1 - mx.tanh(x) ** 2, mx.log1p: lambda x: 1 / (1 + x), + mx.cos: lambda x: -mx.sin(x), + mx.sqrt: lambda x: 0.5 / mx.sqrt(x), + mx.rsqrt: lambda x: -0.5 * mx.rsqrt(x) / x, + mx.arcsin: lambda x: 1 / mx.sqrt(1 - mx.square(x)), + mx.arccos: lambda x: -1 / mx.sqrt(1 - mx.square(x)), + mx.arctan: lambda x: 1 / (1 + mx.square(x)), + mx.arcsinh: lambda x: 1 / mx.sqrt(mx.square(x) + 1), + # 1 / sqrt(x**2 - 1) has the wrong sign when Re(x) < 0 + mx.arccosh: lambda x: 1 / (mx.sqrt(x - 1) * mx.sqrt(x + 1)), + mx.arctanh: lambda x: 1 / (1 - mx.square(x)), } for fn, deriv in ops.items(): + _, (jvp,) = mx.jvp(fn, [z], [cotangent]) + expected = cotangent * deriv(z) + self.assertTrue(mx.allclose(jvp, expected, atol=1e-5), msg=str(fn)) + _, (vjp,) = mx.vjp(fn, [z], [cotangent]) expected = cotangent * mx.conj(deriv(z)) self.assertTrue(mx.allclose(vjp, expected, atol=1e-5), msg=str(fn)) @@ -1534,7 +1741,10 @@ def numerical_hvp(f, x, v, eps=1e-3): lambda a: mx.cummax(a, axis=0, inclusive=False), lambda a: mx.cummin(a, axis=0, reverse=True, inclusive=False), ): - f = lambda a: mx.sum(fn(a) ** 2) + + def f(a): + return mx.sum(fn(a) ** 2) + self.assertTrue( mx.allclose(hvp(f, x, v), numerical_hvp(f, x, v), atol=1e-3) ) @@ -1547,11 +1757,39 @@ def numerical_hvp(f, x, v, eps=1e-3): lambda a: mx.partition(a, 1, axis=0), lambda a: mx.cummax(a, axis=0), ): - f = lambda a: mx.sum(fn(a) ** 2) + + def f(a): + return mx.sum(fn(a) ** 2) + self.assertTrue( mx.allclose(hvp(f, y, w), numerical_hvp(f, y, w), atol=1e-3) ) + def test_transform_releases_captures(self): + for transform in ( + mx.compile, + mx.grad, + mx.value_and_grad, + mx.vmap, + mx.checkpoint, + ): + for cycle in (False, True): + with self.subTest(transform=transform, cycle=cycle): + captured = mx.array(2.0) + ref = weakref.ref(captured) + + def fun(x, captured=captured): + return (x * captured).sum() + + fn = transform(fun) + if cycle: + fun.wrapped = fn + result = fn(mx.ones((2, 3))) + mx.eval(result) + del result, fn, fun, captured + gc.collect() + self.assertIsNone(ref()) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_bf16.py b/python/tests/test_bf16.py index d25364c14f..8ef2b97fc8 100644 --- a/python/tests/test_bf16.py +++ b/python/tests/test_bf16.py @@ -1,8 +1,6 @@ # Copyright © 2023 Apple Inc. -import math import unittest -from itertools import permutations import mlx.core as mx import mlx_tests @@ -12,7 +10,7 @@ import torch has_torch = True -except ImportError as e: +except ImportError: has_torch = False try: @@ -71,8 +69,11 @@ def np_fn(*args): ref_op = np_fn mlx_op = mlx_fn - ref_transform = lambda x: simple_transform(np_transform(x)) - mlx_transform = lambda x: simple_transform(mx.array(x).astype(mx.bfloat16)) + def ref_transform(x): + return simple_transform(np_transform(x)) + + def mlx_transform(x): + return simple_transform(mx.array(x).astype(mx.bfloat16)) self.__test_ops( ref_op, @@ -92,9 +93,10 @@ def torch_fn(*args): return out_bf16.to(torch.float32).numpy() ref_op = torch_fn - ref_transform = lambda x: simple_transform( - torch.from_numpy(x).to(torch.bfloat16) - ) + + def ref_transform(x): + return simple_transform(torch.from_numpy(x).to(torch.bfloat16)) + self.__test_ops( ref_op, mlx_op, @@ -141,6 +143,21 @@ def test_reduction_ops(self): torch_op="a" + op, ) + def test_arithmetic_reduction_ops(self): + cases = { + "sum": np.ones((4096, 4), dtype=np.float32), + "prod": np.full((128, 4), 1.0078125, dtype=np.float32), + } + for op, values in cases.items(): + with self.subTest(op=op): + x = mx.array(values, dtype=mx.bfloat16) + expected = mx.array( + getattr(np, op)(values, axis=0, dtype=np.float32), + dtype=mx.bfloat16, + ) + actual = getattr(mx, op)(x, axis=0, stream=mx.cpu) + self.assertEqual(actual.tolist(), expected.tolist()) + def test_arg_reduction_ops(self): data = np.random.rand(10, 12, 13).astype(np.float32) x = mx.array(data).astype(mx.bfloat16) diff --git a/python/tests/test_blas.py b/python/tests/test_blas.py index 7dbbaea049..eaed51dae7 100644 --- a/python/tests/test_blas.py +++ b/python/tests/test_blas.py @@ -1,8 +1,6 @@ # Copyright © 2023-2024 Apple Inc. import math -import unittest -from itertools import permutations import mlx.core as mx import mlx_tests @@ -449,14 +447,26 @@ def test_matrix_vector_attn(self): shape_values = (B, ksl, Dk) # Prepare numpy arrays - q_np = np.random.uniform(-scale, scale, size=shape_queries).astype(np_dtype) - k_np = np.random.uniform(-scale, scale, size=shape_keys).astype(np_dtype) - v_np = np.random.uniform(-scale, scale, size=shape_values).astype(np_dtype) + q_np = np.random.uniform(-scale, scale, size=shape_queries).astype( + np_dtype + ) + k_np = np.random.uniform(-scale, scale, size=shape_keys).astype( + np_dtype + ) + v_np = np.random.uniform(-scale, scale, size=shape_values).astype( + np_dtype + ) # Rearrange to move heads up - q_np_reshape = q_np.reshape(B, qsl, n_kv_heads, factor, -1).transpose(0, 2, 3, 1, 4) - k_np_reshape = k_np.reshape(B, ksl, n_kv_heads, 1, -1).transpose(0, 2, 3, 4, 1) - v_np_reshape = v_np.reshape(B, ksl, n_kv_heads, 1, -1).transpose(0, 2, 3, 1, 4) + q_np_reshape = q_np.reshape( + B, qsl, n_kv_heads, factor, -1 + ).transpose(0, 2, 3, 1, 4) + k_np_reshape = k_np.reshape(B, ksl, n_kv_heads, 1, -1).transpose( + 0, 2, 3, 4, 1 + ) + v_np_reshape = v_np.reshape(B, ksl, n_kv_heads, 1, -1).transpose( + 0, 2, 3, 1, 4 + ) # Do attn style matmul s_np = q_np_reshape @ k_np_reshape @@ -469,9 +479,15 @@ def test_matrix_vector_attn(self): v_mx = mx.array(v_np) # Rearrange to move heads up - q_mx_reshape = q_mx.reshape(B, qsl, n_kv_heads, factor, -1).transpose(0, 2, 3, 1, 4) - k_mx_reshape = k_mx.reshape(B, ksl, n_kv_heads, 1, -1).transpose(0, 2, 3, 4, 1) - v_mx_reshape = v_mx.reshape(B, ksl, n_kv_heads, 1, -1).transpose(0, 2, 3, 1, 4) + q_mx_reshape = q_mx.reshape( + B, qsl, n_kv_heads, factor, -1 + ).transpose(0, 2, 3, 1, 4) + k_mx_reshape = k_mx.reshape(B, ksl, n_kv_heads, 1, -1).transpose( + 0, 2, 3, 4, 1 + ) + v_mx_reshape = v_mx.reshape(B, ksl, n_kv_heads, 1, -1).transpose( + 0, 2, 3, 1, 4 + ) # Do attn style matmul s_mx = q_mx_reshape @ k_mx_reshape @@ -598,8 +614,11 @@ def run_test(dtype, shape_a, shape_b, f_np_b, f_mx_b): self.assertListEqual(list(out_np.shape), list(out_mx.shape)) self.assertTrue(np.allclose(out_mx, out_np, atol=0.05 * scale)) - nt_np = lambda b: b.swapaxes(-1, -2) - nt_mx = lambda b: mx.swapaxes(b, -1, -2) + def nt_np(b): + return b.swapaxes(-1, -2) + + def nt_mx(b): + return mx.swapaxes(b, -1, -2) for dtype in (mx.float32, mx.float16, mx.bfloat16): for M in (1, 2, 3, 5, 8, 11, 16): @@ -907,6 +926,32 @@ def run_test(dtype, B, M, K, N, c_shape, alpha, beta): out = mx.addmm(c, a, mx.swapaxes(b, -1, -2), 0.125, 0.0) self.assertTrue(np.allclose(out.astype(mx.float32), 12800.0)) + def test_thin_matmul(self): + if mx.default_device() == mx.cpu: + self.skipTest("requires GPU") + + # few output columns or few rows with a transposed b takes the thin NAX + # kernel on Metal. + np.random.seed(0) + shapes = [(2048, 64, 2048), (2049, 48, 300), (4100, 16, 1), (1025, 24, 63)] + shapes += [(20, 300, 1), (33, 1000, 999), (64, 2560, 128)] + for M, N, K in shapes: + scale = K**-0.5 + a_np = np.random.normal(0.0, scale, (M, K)).astype(np.float32) + b_np = np.random.normal(0.0, scale, (N, K)).astype(np.float32) + c_np = np.random.normal(0.0, scale, (N,)).astype(np.float32) + for dtype in (mx.float16, mx.bfloat16): + a, b, c = (mx.array(x).astype(dtype) for x in (a_np, b_np, c_np)) + a_r, b_r, c_r = (np.array(x.astype(mx.float32)) for x in (a, b, c)) + ref = a_r @ b_r.T + for layout, b_mx in (("nt", b.T), ("nn", mx.contiguous(b.T))): + with self.subTest(shape=(M, N, K), dtype=str(dtype), layout=layout): + out = (a @ b_mx).astype(mx.float32) + self.assertTrue(np.allclose(out, ref, 1e-2, 0.05 * scale)) + out = mx.addmm(c, a, b_mx, 0.5, 2.0).astype(mx.float32) + ref_c = 0.5 * ref + 2.0 * c_r + self.assertTrue(np.allclose(out, ref_c, 1e-2, 0.125 * scale)) + def test_addmm_grad(self): def make_ref_addmm(alpha, beta): return lambda c, a, b: alpha * (a @ b) + beta * c @@ -1222,6 +1267,15 @@ def test_shape( self.assertTrue(np.allclose(c_mx, c_np, atol=1e-5)) self.assertTrue(np.allclose(e_mx, e_np, atol=1e-5)) + # Strided output mask with a vector lhs + a = mx.random.normal((1, 64)) + b = mx.random.normal((64, 128)) + mask = mx.array([[True, False, False, True, True, False, False, True]]) + out_mask = mask[:, ::2] + out = mx.block_masked_mm(a, b, 32, out_mask) + expected = ref_block_masked_mm(a, b, 32, out_mask) + self.assertTrue(mx.allclose(out, expected, atol=1e-5)) + def test_gather_matmul(self): def np_gather_mm(a, b, lhs_indices=None, rhs_indices=None): a = a.reshape((-1, a.shape[-2], a.shape[-1])) @@ -1593,6 +1647,14 @@ def segmented_mm_ref(a, b, s): c2 = mx.segmented_mm(a.T, b.T, segments) self.assertTrue(mx.allclose(c1, c2, atol=1e-4)) + # Negative leading dimension + a = mx.random.normal((8, 64)) + b = mx.random.normal((64, 16))[::-1] + segments = mx.array([[0, 20], [20, 64]], dtype=mx.uint32) + c1 = segmented_mm_ref(a, b, segments) + c2 = mx.segmented_mm(a, b, segments) + self.assertTrue(mx.allclose(c1, c2, atol=1e-4)) + with self.assertRaises(ValueError): a = mx.ones((2, 10, 10)) s = mx.array([[0, 5], [5, 10]]).astype(mx.uint32) diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 663ec295b0..7436e58cd2 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -7,6 +7,7 @@ import threading from functools import partial, wraps from io import StringIO +from itertools import product import mlx.core as mx import mlx_tests @@ -45,6 +46,22 @@ def fun(x, y): self.assertEqual(out.dtype, mx.int32) self.assertTrue(mx.array_equal(out, mx.array([2, 4]))) + def test_compile_sigmoid_matches_eager(self): + # Regression test: `Sigmoid` spelled an unqualified `metal::exp`, which + # the prebuilt metallib (-fno-fast-math) resolves to the precise + # implementation but a runtime-compiled kernel resolves to the fast + # approximation -- so a fused compiled chain returned a different, less + # accurate sigmoid than the eager primitive. `Exp` in the same header + # already spells `metal::precise::exp`. + x = mx.linspace(-12, 12, 4001) + + for dtype in (mx.float32, mx.bfloat16): + xd = x.astype(dtype) + expected = mx.sigmoid(xd) + fused = mx.compile(lambda a: mx.sigmoid(a) * 1.0)(xd) + mx.eval(expected, fused) + self.assertTrue(mx.array_equal(fused, expected)) + def test_compile_nonfinite_constants(self): # Regression test: a non-finite scalar constant (NaN / infinity) baked # into a fused compiled kernel used to stream a bare token (e.g. `nan`) @@ -71,6 +88,15 @@ def test_compile_nonfinite_constants(self): self.assertEqual(out[0].item(), 1.0) self.assertEqual(out[1].item(), float("-inf")) + def test_compile_float_constant_precision(self): + x = mx.ones((4,), dtype=mx.float32) + for constant in (1 / 3, 128**-0.5, 0.7071067811865476): + + def fun(x, constant=constant): + return (x * x) * constant + + self.assertTrue(mx.array_equal(mx.compile(fun)(x), fun(x))) + def test_compile_tuple_output_in_thread(self): @mx.compile def fun(x): @@ -278,7 +304,7 @@ def count_prims(outputs): buf = io.StringIO() mx.export_to_dot(buf, outputs) buf.seek(0) - return len([l for l in buf.read().split() if "label" in l]) + return len([line for line in buf.read().split() if "label" in line]) x = mx.array(1.0) cfun = mx.compile(fun) @@ -635,6 +661,33 @@ def fun(x): cfun = mx.compile(fun, shapeless=True) self.assertTrue(mx.array_equal(fun(x2), cfun(x2))) + def test_shapeless_compile_scan(self): + ops = (mx.cumsum, mx.cumprod, mx.cummin, mx.cummax, mx.logcumsumexp) + for op, axis, reverse, inclusive in product( + ops, (0, 1, -1), (False, True), (False, True) + ): + with self.subTest( + op=op.__name__, axis=axis, reverse=reverse, inclusive=inclusive + ): + scan = partial(op, axis=axis, reverse=reverse, inclusive=inclusive) + trace_count = 0 + + def fun(x): + nonlocal trace_count + trace_count += 1 + return scan(x) + + cfun = mx.compile(fun, shapeless=True) + for shape in ((3, 4), (5, 7), (1, 2), (2, 1)): + with self.subTest(shape=shape): + x = mx.arange(math.prod(shape), dtype=mx.float32) + x = ((x % 7 - 3) / 4).reshape(shape) + expected = scan(x) + actual = cfun(x) + self.assertEqual(actual.shape, x.shape) + self.assertEqualArray(actual, expected, atol=1e-6, rtol=1e-6) + self.assertEqual(trace_count, 1) + def test_shapeless_compile_unflatten(self): x = mx.zeros((1, 1, 4 * 32)) @@ -712,6 +765,24 @@ def fn(x): self.assertEqual(cfn(x4).shape, fn(x4).shape) self.assertEqual(cfn(x8).shape, fn(x8).shape) + def test_compile_scalar_constant_output(self): + for shapeless in [False, True]: + fun = mx.compile(lambda x: (x + 1.0, mx.array(1.0)), shapeless=shapeless) + out, c = fun(mx.array(3.0)) + self.assertEqual(out.item(), 4.0) + self.assertEqual(c.item(), 1.0) + + s = mx.array(7.0) + out, c = mx.compile(lambda x: (x + 7.0, s))(mx.array([1.0, 2.0])) + self.assertEqual(out.tolist(), [8.0, 9.0]) + self.assertEqual(c.item(), 7.0) + + # The gradient is the seed constant of the backward pass + fun = mx.compile(mx.value_and_grad(lambda x: x + 1.0)) + value, grad = fun(mx.array(2.0)) + self.assertEqual(value.item(), 3.0) + self.assertEqual(grad.item(), 1.0) + def test_compile_with_constant(self): # Test float @partial(mx.compile) @@ -852,10 +923,10 @@ def fun(x, y): return x + y.value with self.assertRaises(ValueError): - out = fun(mx.array(0.0), MyClass()) + fun(mx.array(0.0), MyClass()) with self.assertRaises(ValueError): - out = fun(mx.array(0.0), y=MyClass()) + fun(mx.array(0.0), y=MyClass()) def test_compile_create_list(self): @mx.compile @@ -883,7 +954,7 @@ def step(w): self.assertTrue(mx.allclose(expected[0], out[0])) self.assertTrue(mx.allclose(expected[1], out[1])) - def fun(w1, w2, x): + def fun(w1, w2, x): # noqa: F811 x = x @ w1 y = x @ w2 x = x + y * y @@ -1293,14 +1364,13 @@ def f(x): def test_double_constant(self): with mx.stream(mx.cpu): - x = mx.array(1.0, dtype=mx.float64) + x = mx.array([1.0], dtype=mx.float64) + constant = math.nextafter(1.0, 2.0) def fun(x): - return (x + math.pi) * 2.0 + return (x * x) * constant - y = fun(x).item() - y_compiled = mx.compile(fun)(x).item() - self.assertEqual(y, y_compiled) + self.assertTrue(mx.array_equal(fun(x), mx.compile(fun)(x))) def test_shared_broadcast(self): def fun(x, y, z): @@ -1495,7 +1565,7 @@ def transform_tuple(t): def transform_vector(t): return Vector([t[0] + 10, t[1] * 10]) - x = State(mx.array(1), mx.array(2)) + _x = State(mx.array(1), mx.array(2)) compiled_transform = mx.compile(transform) compiled_transform_tuple = mx.compile(transform_tuple) @@ -1618,7 +1688,9 @@ def p(x): def test_compile_abs_unsigned(self): # abs has to compile for the wider unsigned types too - fun = lambda x: mx.abs(x) + 1 + def fun(x): + return mx.abs(x) + 1 + for dtype in [mx.uint8, mx.uint16, mx.uint32, mx.uint64]: x = mx.array([1, 2, 3], dtype) self.assertTrue(mx.array_equal(mx.compile(fun)(x), fun(x))) diff --git a/python/tests/test_constants.py b/python/tests/test_constants.py index cfd971fbe0..dfd856002a 100644 --- a/python/tests/test_constants.py +++ b/python/tests/test_constants.py @@ -1,6 +1,5 @@ # Copyright © 2023 Apple Inc. -import unittest import mlx.core as mx import mlx_tests diff --git a/python/tests/test_conv.py b/python/tests/test_conv.py index 4e0fd3457f..8ec1b054a3 100644 --- a/python/tests/test_conv.py +++ b/python/tests/test_conv.py @@ -3,7 +3,6 @@ import math import os import unittest -from itertools import permutations import mlx.core as mx import mlx_tests @@ -60,7 +59,7 @@ def test_torch_conv_1D(self): def run_conv1D( N, C, - O, + OC, iH, kH, stride, @@ -74,7 +73,7 @@ def run_conv1D( dtype=dtype, N=N, C=C, - O=O, + O=OC, iH=iH, kH=kH, stride=stride, @@ -85,7 +84,7 @@ def run_conv1D( np_dtype = getattr(np, dtype) np.random.seed(0) in_np = np.random.normal(0, 1.0 / C, (N, iH, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, int(C / groups))).astype( + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, int(C / groups))).astype( np_dtype ) @@ -116,7 +115,7 @@ def run_conv1D( self.assertTrue(np.allclose(out_pt.numpy(), out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -127,17 +126,17 @@ def run_conv1D( (3, 3, 1, 0), (31, 5, 5, 2), ): - run_conv1D(N, C, O, iH, kH, stride, padding, dtype=dtype) + run_conv1D(N, C, OC, iH, kH, stride, padding, dtype=dtype) # Groups tests - N, C, O = (4, 32, 64) + N, C, OC = (4, 32, 64) for iH, kH, stride, padding in ( (1, 1, 1, 0), (3, 3, 1, 0), (31, 5, 5, 2), ): for group in (1, 2, 4, 8, 16, 32): - run_conv1D(N, C, O, iH, kH, stride, padding, groups=group, dtype=dtype) + run_conv1D(N, C, OC, iH, kH, stride, padding, groups=group, dtype=dtype) # Strided inputs tests for tpose_in, tpose_wt in ( @@ -169,7 +168,7 @@ def test_torch_conv_1D_grad(self): def run_conv1D_grad( N, C, - O, + OC, iH, kH, stride, @@ -183,7 +182,7 @@ def run_conv1D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, iH=iH, kH=kH, stride=stride, @@ -196,8 +195,8 @@ def run_conv1D_grad( oH = 1 + ((iH + 2 * padding - dilation * (kH - 1) - 1) // stride) in_np = np.random.normal(0, 1.0 / C, (N, iH, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, C)).astype(np_dtype) - ct_np = np.random.normal(0, 1.0 / C, (N, oH, O)).astype(np_dtype) + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, C)).astype(np_dtype) + ct_np = np.random.normal(0, 1.0 / C, (N, oH, OC)).astype(np_dtype) in_mx, wt_mx, ct_mx = map(mx.array, (in_np, wt_np, ct_np)) in_pt, wt_pt, ct_pt = map( @@ -257,7 +256,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -268,14 +267,14 @@ def f(a, b): (3, 3, 1, 0), (31, 5, 5, 2), ): - run_conv1D_grad(N, C, O, iH, kH, stride, padding, dtype=dtype) + run_conv1D_grad(N, C, OC, iH, kH, stride, padding, dtype=dtype) @unittest.skipIf(not has_torch, "requires Torch") def test_torch_conv_2D(self): def run_conv2D( N, C, - O, + OC, idim, kdim, stride, @@ -288,7 +287,7 @@ def run_conv2D( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -301,7 +300,7 @@ def run_conv2D( kH, kW = kdim scale = 1.0 / math.sqrt(kH * kW * C) in_np = np.random.normal(0.0, scale, (N, iH, iW, C)) - wt_np = np.random.normal(0.0, 1.0, (O, kH, kW, int(C / groups))) + wt_np = np.random.normal(0.0, 1.0, (OC, kH, kW, int(C / groups))) mx_dtype = getattr(mx, dtype) torch_dtype = getattr(torch, dtype) @@ -341,27 +340,31 @@ def run_conv2D( self.assertEqual(out_pt.shape, out_mx.shape) if dtype == "bfloat16": - atol, rtol = 1e-1, 1e-3 + atol = 1e-1 else: - atol, rtol = 1e-5, 1e-6 + atol = 1e-5 self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32", "bfloat16"): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 32, 64), + (1, 128, 48), + (1, 128, 96), ): for idim, kdim, stride, padding in ( ((1, 1), (1, 1), (1, 1), (0, 0)), ((3, 3), (3, 1), (1, 1), (0, 0)), ((31, 31), (5, 5), (5, 5), (2, 2)), ): - run_conv2D(N, C, O, idim, kdim, stride, padding, dtype=dtype) + run_conv2D(N, C, OC, idim, kdim, stride, padding, dtype=dtype) + + run_conv2D(1, 128, 32, (1, 9601), (1, 7), (1, 1), (0, 3), dtype=dtype) # Groups tests - N, C, O = (4, 32, 64) + N, C, OC = (4, 32, 64) for idim, kdim, stride, padding in ( ((1, 1), (1, 1), (1, 1), (0, 0)), ((3, 3), (3, 1), (1, 1), (0, 0)), @@ -369,7 +372,7 @@ def run_conv2D( ): for group in (1, 2, 4, 8, 16, 32): run_conv2D( - N, C, O, idim, kdim, stride, padding, groups=group, dtype=dtype + N, C, OC, idim, kdim, stride, padding, groups=group, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -377,7 +380,7 @@ def test_torch_conv_2D_grad(self): def run_conv2D_grad( N, C, - O, + OC, idim, kdim, stride, @@ -391,7 +394,7 @@ def run_conv2D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -413,10 +416,10 @@ def run_conv2D_grad( ) in_np = np.random.normal(0.0, scale, (N, iH, iW, C)).astype(np_dtype) - wt_np = np.random.normal(0.0, scale, (O, kH, kW, C // groups)).astype( + wt_np = np.random.normal(0.0, scale, (OC, kH, kW, C // groups)).astype( np_dtype ) - ct_np = np.random.normal(0.0, scale, (N, oH, oW, O)).astype(np_dtype) + ct_np = np.random.normal(0.0, scale, (N, oH, oW, OC)).astype(np_dtype) in_mx, wt_mx, ct_mx = map(mx.array, (in_np, wt_np, ct_np)) in_pt, wt_pt, ct_pt = map( @@ -471,7 +474,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 32, 64), (4, 16, 32)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 32, 64), (4, 16, 32)): for idim, kdim, stride, padding, dilation in ( ((1, 1), (1, 1), (1, 1), (0, 0), (1, 1)), ((3, 3), (3, 1), (1, 1), (0, 0), (1, 1)), @@ -481,7 +484,7 @@ def f(a, b): ((32, 32), (3, 3), (2, 2), (1, 1), (3, 2)), ): run_conv2D_grad( - N, C, O, idim, kdim, stride, padding, dilation, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dilation, dtype=dtype ) for groups in (2, 4, 32): @@ -497,12 +500,27 @@ def f(a, b): dtype=dtype, ) + # Depthwise with C % 16 != 0 and grouped with C_per_group = 8 + for N, C, OC, groups in ((2, 24, 24, 24), (2, 40, 40, 40), (2, 64, 128, 8)): + for stride in ((1, 1), (2, 2)): + run_conv2D_grad( + N, + C, + OC, + (16, 16), + (3, 3), + stride, + (1, 1), + groups=groups, + dtype=dtype, + ) + @unittest.skipIf(not has_torch, "requires Torch") def test_torch_conv_3D(self): def run_conv3D( N, C, - O, + OC, idim, kdim, stride, @@ -516,7 +534,7 @@ def run_conv3D( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -532,7 +550,7 @@ def run_conv3D( in_np = np.random.normal(0.0, scale, (N, iD, iH, iW, C)).astype( np_dtype ) - wt_np = np.random.normal(0.0, 1.0, (O, kD, kH, kW, C)).astype(np_dtype) + wt_np = np.random.normal(0.0, 1.0, (OC, kD, kH, kW, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt, wt_pt = map( @@ -562,7 +580,7 @@ def run_conv3D( self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -573,12 +591,12 @@ def run_conv3D( ((3, 3, 3), (3, 1, 1), (1, 1, 1), (0, 0, 0)), ((31, 31, 31), (5, 5, 5), (5, 5, 5), (2, 2, 2)), ): - run_conv3D(N, C, O, idim, kdim, stride, padding, dtype=dtype) + run_conv3D(N, C, OC, idim, kdim, stride, padding, dtype=dtype) - N, C, O = (2, 4, 4) + N, C, OC = (2, 4, 4) idim, kdim, stride, padding = (6, 6, 6), (3, 1, 1), (1, 1, 1), (0, 0, 0) run_conv3D( - N, C, O, idim, kdim, stride, padding, dilation=(2, 2, 2), dtype=dtype + N, C, OC, idim, kdim, stride, padding, dilation=(2, 2, 2), dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -586,7 +604,7 @@ def test_torch_conv_3D_grad(self): def run_conv3D_grad( N, C, - O, + OC, idim, kdim, stride, @@ -600,7 +618,7 @@ def run_conv3D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -627,10 +645,10 @@ def run_conv3D_grad( in_np = np.random.normal(0.0, scale, (N, iD, iH, iW, C)).astype( np_dtype ) - wt_np = np.random.normal(0.0, scale, (O, kD, kH, kW, C)).astype( + wt_np = np.random.normal(0.0, scale, (OC, kD, kH, kW, C)).astype( np_dtype ) - ct_np = np.random.normal(0.0, scale, (N, oD, oH, oW, O)).astype( + ct_np = np.random.normal(0.0, scale, (N, oD, oH, oW, OC)).astype( np_dtype ) @@ -687,7 +705,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 16, 32), (4, 8, 16)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 16, 32), (4, 8, 16)): for idim, kdim, stride, padding, dilation in ( ((1, 1, 1), (1, 1, 1), (1, 1, 1), (0, 0, 0), (1, 1, 1)), ((3, 3, 3), (3, 1, 1), (1, 1, 1), (0, 0, 0), (1, 1, 1)), @@ -697,7 +715,7 @@ def f(a, b): ((16, 16, 16), (3, 3, 3), (2, 2, 2), (1, 1, 1), (3, 2, 2)), ): run_conv3D_grad( - N, C, O, idim, kdim, stride, padding, dilation, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dilation, dtype=dtype ) def __conv_general_test( @@ -753,7 +771,9 @@ def conv_general_pt( ): C = inp.size()[1] ndim = inp.ndim - 2 - map_ints = lambda x: [x] * ndim if isinstance(x, int) else x + + def map_ints(x): + return [x] * ndim if isinstance(x, int) else x stride, padding, kernel_dilation, input_dilation = map( map_ints, (stride, padding, kernel_dilation, input_dilation) @@ -975,7 +995,6 @@ def fn(x, w): def fn_gt(x, w): num_groups = x.shape[-1] // w.shape[-1] - group_size = w.shape[-1] ws = w.reshape(num_groups, -1, *w.shape[1:]).split(num_groups) xs = x.reshape(*x.shape[:-1], num_groups, -1).split(num_groups, axis=-2) return mx.concatenate( @@ -1025,7 +1044,6 @@ def fn(x, w): def fn_gt(x, w): num_groups = x.shape[-1] // w.shape[-1] - group_size = w.shape[-1] ws = w.reshape(num_groups, -1, *w.shape[1:]).split(num_groups) xs = x.reshape(*x.shape[:-1], num_groups, -1).split(num_groups, axis=-2) return mx.concatenate( @@ -1079,6 +1097,9 @@ def test_torch_conv_depthwise(self): ( 1, 32, 32, 32, 7, 7, 32, (1, 1), (3, 3), 32), ( 3, 32, 32, 32, 5, 5, 32, (1, 2), (0, 0), 32), ( 1, 32, 32, 32, 7, 7, 32, (2, 1), (1, 3), 32), + ( 2, 16, 16, 24, 3, 3, 24, (1, 1), (1, 1), 24), + ( 1, 14, 14, 40, 5, 5, 40, (2, 2), (2, 2), 40), + ( 2, 9, 9, 8, 3, 3, 8, (1, 1), (1, 1), 8), ) # fmt: on @@ -1086,14 +1107,14 @@ def test_torch_conv_depthwise(self): if mx.default_device() == mx.gpu: dtypes += [np.float16] - for N, H, W, C, kH, kW, O, strides, padding, groups in shapes: + for N, H, W, C, kH, kW, OC, strides, padding, groups in shapes: for dtype in dtypes: for flip in [False, True]: Cw = C // groups self.__conv_general_test( (N, H, W, C), - (O, kH, kW, Cw), + (OC, kH, kW, Cw), strides, padding, kernel_dilation=1, @@ -1168,6 +1189,35 @@ def loss_fn(kernel, inputs, strides, groups): ) self.assertEqual(grads.shape, k_shape) + def test_padding_input_grad(self): + def conv_loss(x, w, stride, padding): + out = mx.conv_general(x, w, stride=stride, padding=padding) + return mx.sum(out * out) + + def padded_loss(x, w, stride, padding): + lo, hi = padding + pad_width = [(0, 0)] + list(zip(lo, hi)) + [(0, 0)] + out = mx.conv_general(mx.pad(x, pad_width), w, stride=stride) + return mx.sum(out * out) + + for in_shape, w_shape, stride, padding in [ + ((1, 4, 1), (1, 3, 1), (1,), ([0], [1])), + ((1, 4, 1), (1, 3, 1), (2,), ([0], [1])), + ((1, 4, 1), (1, 3, 1), (1,), ([1], [0])), + ((2, 6, 6, 3), (4, 3, 3, 3), (2, 2), ([0, 1], [1, 2])), + ((2, 5, 5, 5, 2), (3, 2, 2, 2, 2), (2, 1, 2), ([0, 0, 1], [1, 1, 0])), + ((1, 4, 1), (1, 2, 1), (1,), ([3], [3])), + ((1, 4, 1), (1, 2, 1), (1,), ([0], [3])), + ((1, 4, 1), (1, 2, 1), (2,), ([3], [0])), + ((2, 5, 6, 3), (4, 2, 3, 3), (1, 2), ([4, 0], [1, 5])), + ]: + x = mx.random.normal(in_shape) + w = mx.random.normal(w_shape) + expected = mx.grad(padded_loss)(x, w, stride, padding) + grad = mx.grad(conv_loss)(x, w, stride, padding) + self.assertEqual(grad.shape, x.shape) + self.assertTrue(mx.allclose(grad, expected, atol=1e-4, rtol=1e-4)) + @unittest.skipIf(mx.cuda.is_available() and "CI" in os.environ, "flaky in CI") def test_conv_1d_with_2d(self): x = mx.random.uniform(shape=(2, 10, 16)) @@ -1215,6 +1265,177 @@ def test_conv2d_unaligned_channels(self): y_hat = mx.conv_transpose2d(x, w) self.assertTrue(mx.allclose(y, y_hat)) + def __assert_gpu_matches_cpu(self, f, *args, **kwargs): + out_gpu = f(*args, **kwargs, stream=mx.gpu) + out_cpu = f(*args, **kwargs, stream=mx.cpu) + self.assertEqual(out_gpu.shape, out_cpu.shape) + atol = 1e-4 if args[0].dtype == mx.float32 else 5e-3 + self.assertTrue( + mx.allclose( + out_gpu.astype(mx.float32), out_cpu.astype(mx.float32), atol=atol + ) + ) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_conv_grouped_c_per_group_8(self): + # fmt: off + shapes_2d = ( + # N, H, W, groups, O_per_group, k, stride, padding, dilation + ( 2, 14, 14, 2, 8, 3, 1, 1, 1), + ( 2, 13, 9, 16, 16, 3, 2, 1, 1), + ( 1, 7, 7, 32, 8, 3, 1, 1, 1), + ( 2, 14, 14, 32, 16, 3, 2, 1, 1), + ( 2, 14, 14, 16, 8, 5, 1, 2, 1), + ( 2, 14, 14, 16, 8, 3, 1, 2, 2), + ( 2, 14, 14, 8, 32, 3, 1, 1, 1), + ( 2, 14, 14, 8, 64, 3, 1, 1, 1), + ( 1, 33, 31, 4, 8, 3, 2, 0, 1), + ( 1, 9, 9, 1, 8, 3, 1, 1, 1), + ) + shapes_1d = ( + # N, L, groups, O_per_group, k, stride, padding + ( 2, 64, 2, 8, 3, 1, 1), + ( 2, 63, 16, 16, 3, 2, 1), + ( 1, 100, 32, 8, 5, 1, 2), + ( 2, 64, 32, 16, 3, 2, 0), + ) + # fmt: on + + for dtype in (mx.float32, mx.float16): + for N, H, W, groups, opg, k, stride, padding, dilation in shapes_2d: + C, OC = 8 * groups, opg * groups + for flip in (False, True): + x = mx.random.normal((N, H, W, C)).astype(dtype) + w = (0.2 * mx.random.normal((OC, k, k, 8))).astype(dtype) + with self.subTest( + dtype=dtype, + in_shape=x.shape, + wt_shape=w.shape, + groups=groups, + stride=stride, + padding=padding, + dilation=dilation, + flip=flip, + ): + self.__assert_gpu_matches_cpu( + mx.conv_general, + x, + w, + stride=stride, + padding=padding, + kernel_dilation=dilation, + groups=groups, + flip=flip, + ) + + for N, L, groups, opg, k, stride, padding in shapes_1d: + C, OC = 8 * groups, opg * groups + x = mx.random.normal((N, L, C)).astype(dtype) + w = (0.2 * mx.random.normal((OC, k, 8))).astype(dtype) + with self.subTest(dtype=dtype, in_shape=x.shape, wt_shape=w.shape): + self.__assert_gpu_matches_cpu( + mx.conv1d, + x, + w, + stride=stride, + padding=padding, + groups=groups, + ) + + # Non-contiguous input and weight go through a contiguous copy + x = mx.random.normal((2, 128, 14, 14)).transpose(0, 2, 3, 1) + w = 0.2 * mx.random.normal((3, 3, 8, 256)).transpose(3, 0, 1, 2) + self.__assert_gpu_matches_cpu(mx.conv2d, x, w, padding=1, groups=16) + + # Gradients with respect to the input and the weight + def vjp(f, x, w, stream): + out, grads = mx.vjp( + lambda a, b: f(a, b, stream=stream), + [x, w], + [mx.ones(f(x, w, stream=mx.cpu).shape)], + ) + return grads + + x = mx.random.normal((2, 14, 14, 128)) + w = 0.2 * mx.random.normal((256, 3, 3, 8)) + + def f(a, b, stream): + return mx.conv2d(a, b, stride=2, padding=1, groups=16, stream=stream) + + for g_gpu, g_cpu in zip(vjp(f, x, w, mx.gpu), vjp(f, x, w, mx.cpu)): + self.assertTrue(mx.allclose(g_gpu, g_cpu, atol=1e-4)) + + x = mx.random.normal((2, 64, 128)) + w = 0.2 * mx.random.normal((128, 3, 8)) + + def f(a, b, stream): + return mx.conv1d(a, b, padding=1, groups=16, stream=stream) + + for g_gpu, g_cpu in zip(vjp(f, x, w, mx.gpu), vjp(f, x, w, mx.cpu)): + self.assertTrue(mx.allclose(g_gpu, g_cpu, atol=1e-4)) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_conv_depthwise_c_multiple_of_8(self): + # fmt: off + shapes = ( + # N, H, W, C, k, stride, padding + ( 2, 16, 16, 24, 3, 1, 1), + ( 2, 17, 15, 24, 3, 2, 1), + ( 1, 14, 14, 40, 5, 1, 2), + ( 1, 14, 14, 40, 5, 2, 2), + ( 2, 9, 9, 8, 3, 1, 1), + ( 1, 12, 12, 56, 7, 1, 3), + ) + # fmt: on + + for dtype in (mx.float32, mx.float16): + for N, H, W, C, k, stride, padding in shapes: + for flip in (False, True): + x = mx.random.normal((N, H, W, C)).astype(dtype) + w = (0.2 * mx.random.normal((C, k, k, 1))).astype(dtype) + with self.subTest( + dtype=dtype, + in_shape=x.shape, + wt_shape=w.shape, + stride=stride, + padding=padding, + flip=flip, + ): + self.__assert_gpu_matches_cpu( + mx.conv_general, + x, + w, + stride=stride, + padding=padding, + groups=C, + flip=flip, + ) + + # conv1d depthwise with padding also uses the 2D depthwise kernel + for C, k, stride in ((24, 3, 1), (40, 5, 2)): + x = mx.random.normal((2, 64, C)).astype(dtype) + w = (0.2 * mx.random.normal((C, k, 1))).astype(dtype) + with self.subTest(dtype=dtype, in_shape=x.shape, wt_shape=w.shape): + self.__assert_gpu_matches_cpu( + mx.conv1d, x, w, stride=stride, padding=k // 2, groups=C + ) + + # Gradients with respect to the input and the weight + for C, k, stride in ((24, 3, 1), (40, 5, 2)): + x = mx.random.normal((2, 16, 16, C)) + w = 0.2 * mx.random.normal((C, k, k, 1)) + + def f(a, b, stream): + return mx.conv2d( + a, b, stride=stride, padding=k // 2, groups=C, stream=stream + ) + + cotan = mx.ones(f(x, w, mx.cpu).shape) + _, grads_gpu = mx.vjp(lambda a, b: f(a, b, mx.gpu), [x, w], [cotan]) + _, grads_cpu = mx.vjp(lambda a, b: f(a, b, mx.cpu), [x, w], [cotan]) + for g_gpu, g_cpu in zip(grads_gpu, grads_cpu): + self.assertTrue(mx.allclose(g_gpu, g_cpu, atol=1e-4)) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") def test_conv2d_winograd_batch_tiling(self): # Winograd and its batch tiling exist only in the Metal backend. On @@ -1225,7 +1446,6 @@ def test_conv2d_winograd_batch_tiling(self): # Use envs to test tiling without allocating large buffers. tile_key = "MLX_CONV_WINOGRAD_TILE_BATCH" ws_key = "MLX_CONV_WINOGRAD_WORKING_SET" - prev = {k: os.environ.get(k) for k in (tile_key, ws_key)} # Winograd needs 3x3 stride-1, channels in multiples of 32, # C + O >= 256 and N * iH * iW >= 4096. @@ -1236,81 +1456,91 @@ def test_conv2d_winograd_batch_tiling(self): ) def run(x, w, env={}): - for k in (tile_key, ws_key): - os.environ.pop(k, None) - os.environ.update(env) - y = mx.conv2d(x, w, padding=1) - mx.eval(y) - return np.array(y) - - try: - for in_shape, wt_shape in cases: - np.random.seed(0) - x = mx.array(np.random.normal(size=in_shape).astype(np.float32)) - # Small weights keep the output near unit scale. - w = mx.array( - (np.random.normal(size=wt_shape) * 0.05).astype(np.float32) - ) - b = mx.zeros((wt_shape[0],)) - mx.eval(x, w, b) - cpu_ref = np.array(mx.conv2d(x, w, padding=1, stream=mx.cpu)) - - untiled = run(x, w) - self.assertGreater(np.abs(untiled).max(), 0) - self.assertTrue(np.allclose(untiled, cpu_ref, atol=1e-3)) - - # Tiled winograd keeps the same per-element reduction order, - # so it is bit-identical to untiled; the implicit gemm - # fallback never is. Exact equality pins each run to its path. - # 3 divides none of the batches, so it also covers a short - # final tile. - for tile in (1, 3): - with self.subTest(in_shape=in_shape, tile=tile): - tiled = run(x, w, {tile_key: str(tile)}) - self.assertTrue(np.array_equal(untiled, tiled)) - - # A consumer op checks the output is fenced across - # command encoders. - os.environ[tile_key] = str(tile) + with mlx_tests.scoped_env(**env): + y = mx.conv2d(x, w, padding=1) + mx.eval(y) + return np.array(y) + + for in_shape, wt_shape in cases: + np.random.seed(0) + x = mx.array(np.random.normal(size=in_shape).astype(np.float32)) + # Small weights keep the output near unit scale. + w = mx.array((np.random.normal(size=wt_shape) * 0.05).astype(np.float32)) + b = mx.zeros((wt_shape[0],)) + mx.eval(x, w, b) + cpu_ref = np.array(mx.conv2d(x, w, padding=1, stream=mx.cpu)) + + untiled = run(x, w) + self.assertGreater(np.abs(untiled).max(), 0) + self.assertTrue(np.allclose(untiled, cpu_ref, atol=1e-3)) + + # Tiled winograd keeps the same per-element reduction order, + # so it is bit-identical to untiled; the implicit gemm + # fallback never is. Exact equality pins each run to its path. + # 3 divides none of the batches, so it also covers a short + # final tile. + for tile in (1, 3): + with self.subTest(in_shape=in_shape, tile=tile): + tiled = run(x, w, {tile_key: str(tile)}) + self.assertTrue(np.array_equal(untiled, tiled)) + + # A consumer op checks the output is fenced across + # command encoders. + with mlx_tests.scoped_env(MLX_CONV_WINOGRAD_TILE_BATCH=str(tile)): fused = mx.conv2d(x, w, padding=1) + b mx.eval(fused) - self.assertTrue(np.allclose(untiled, fused, atol=1e-4)) - os.environ.pop(tile_key, None) - - # Budget for ~2 batch elements so the selector itself must - # tile; mirrors the winograd_batch_step arithmetic. - n, iH, iW, C = in_shape - O = wt_shape[0] - pH = 6 * ((iH + 2 - 2 + 5) // 6) + 2 - pW = 6 * ((iW + 2 - 2 + 5) // 6) + 2 - per_n = ( - pH * pW * C * 4 - + 64 * ((iH + 5) // 6) * ((iW + 5) // 6) * (C + O) * 4 - ) - used = (n * iH * iW * (C + O) + 64 * C * O) * 4 - with self.subTest(in_shape=in_shape, budget="tiled"): - budget = str(int((used + 5 * per_n // 2) / 0.75)) - tiled = run(x, w, {ws_key: budget}) - self.assertTrue(np.array_equal(untiled, tiled)) + self.assertTrue(np.allclose(untiled, fused, atol=1e-4)) + + # Budget for ~2 batch elements so the selector itself must + # tile; mirrors the winograd_batch_step arithmetic. + n, iH, iW, C = in_shape + OC = wt_shape[0] + pH = 6 * ((iH + 2 - 2 + 5) // 6) + 2 + pW = 6 * ((iW + 2 - 2 + 5) // 6) + 2 + per_n = ( + pH * pW * C * 4 + 64 * ((iH + 5) // 6) * ((iW + 5) // 6) * (C + OC) * 4 + ) + used = (n * iH * iW * (C + OC) + 64 * C * OC) * 4 + with self.subTest(in_shape=in_shape, budget="tiled"): + budget = str(int((used + 5 * per_n // 2) / 0.75)) + tiled = run(x, w, {ws_key: budget}) + self.assertTrue(np.array_equal(untiled, tiled)) + + # Too small for even one batch element: must fall back. + with self.subTest(in_shape=in_shape, budget="infeasible"): + fallback = run(x, w, {ws_key: "1"}) + self.assertFalse(np.array_equal(untiled, fallback)) + self.assertTrue(np.allclose(fallback, cpu_ref, atol=1e-3)) + + # A forced tile is capped by the budget, so this must still + # fall back. + with self.subTest(in_shape=in_shape, budget="forced+infeasible"): + capped = run(x, w, {ws_key: "1", tile_key: "1"}) + self.assertFalse(np.array_equal(untiled, capped)) + self.assertTrue(np.allclose(capped, cpu_ref, atol=1e-3)) - # Too small for even one batch element: must fall back. - with self.subTest(in_shape=in_shape, budget="infeasible"): - fallback = run(x, w, {ws_key: "1"}) - self.assertFalse(np.array_equal(untiled, fallback)) - self.assertTrue(np.allclose(fallback, cpu_ref, atol=1e-3)) - - # A forced tile is capped by the budget, so this must still - # fall back. - with self.subTest(in_shape=in_shape, budget="forced+infeasible"): - capped = run(x, w, {ws_key: "1", tile_key: "1"}) - self.assertFalse(np.array_equal(untiled, capped)) - self.assertTrue(np.allclose(capped, cpu_ref, atol=1e-3)) - finally: - for k, v in prev.items(): - if v is None: - os.environ.pop(k, None) - else: - os.environ[k] = v + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_conv2d_winograd_disable(self): + # Winograd exists only in the Metal backend. On the CPU every run + # takes the same path, so the check cannot tell the paths apart. + if mx.default_device() != mx.gpu: + self.skipTest("Winograd is specific to the GPU device") + # N * iH * iW >= 4096 selects Winograd only from a batch of 3. + np.random.seed(0) + x = mx.array(np.random.normal(size=(1, 40, 40, 128)).astype(np.float32)) + w = mx.array( + (np.random.normal(size=(128, 3, 3, 128)) * 0.05).astype(np.float32) + ) + xb = mx.repeat(x, 3, axis=0) + + single = np.array(mx.conv2d(x, w, padding=1)) + winograd = np.array(mx.conv2d(xb, w, padding=1)) + self.assertFalse(np.array_equal(winograd[0], single[0])) + + with mlx_tests.scoped_env(MLX_CONV_WINOGRAD="0"): + gemm = np.array(mx.conv2d(xb, w, padding=1)) + for i in range(3): + self.assertTrue(np.array_equal(gemm[i], single[0])) def test_conv2d_large_filter_small_channels(self): x = mx.random.normal(shape=(1, 181, 181, 1)) @@ -1345,6 +1575,78 @@ def test_conv_3D_small_kd_decomposition(self): f"C{Cin}->{Cout} k{kd}{kh}{kw} flip={flip}", ) + def test_grouped_conv_padding_stays_in_output(self): + # groups takes the direct CPU kernel. Padding taller than the output + # used to run the border loop past the buffer. + mx.random.seed(0) + x = mx.random.normal((1, 1, 8, 2)) + w = mx.random.normal((2, 5, 1, 1)) + y = mx.conv2d(x, w, stride=(1, 1), padding=(2, 0), groups=2, stream=mx.cpu) + parts = [ + mx.conv2d( + x[..., g : g + 1], + w[g : g + 1], + stride=(1, 1), + padding=(2, 0), + stream=mx.cpu, + ) + for g in range(2) + ] + expected = mx.concatenate(parts, axis=-1) + self.assertEqual(tuple(y.shape), (1, 1, 8, 2)) + self.assertTrue(mx.allclose(y, expected, atol=1e-4)) + + # A 1-wide kernel makes weight dilation a no-op, but any dilation + # other than 1 sends 3D conv to the direct kernel. Depth padding is + # the same overhang as the 2D case. + x3 = mx.random.normal((1, 1, 4, 2, 1)) + w3 = mx.random.normal((1, 5, 1, 1, 1)) + y3 = mx.conv3d( + x3, + w3, + padding=(2, 0, 0), + dilation=(1, 2, 1), + stream=mx.cpu, + ) + expected3 = mx.conv3d( + x3, + w3, + padding=(2, 0, 0), + stream=mx.cpu, + ) + self.assertEqual(tuple(y3.shape), tuple(expected3.shape)) + self.assertTrue(mx.allclose(y3, expected3, atol=1e-4)) + + wide = mx.random.normal((1, 1, 500000, 2)) + wide_w = mx.random.normal((2, 5, 1, 1)) + wide_y = mx.conv2d( + wide, + wide_w, + stride=(1, 1), + padding=(2, 0), + groups=2, + stream=mx.cpu, + ) + mx.eval(wide_y) + self.assertEqual(tuple(wide_y.shape), (1, 1, 500000, 2)) + + @unittest.skipIf(not mx.is_available(mx.gpu), "requires GPU") + def test_grouped_depthwise_conv_padding_bounds(self): + x = mx.random.normal((1, 16, 64)) + w = mx.random.normal((64, 3, 1)) + y = mx.conv1d(x, w, padding=1, groups=64) + mx.eval(y) + self.assertEqual(tuple(y.shape), (1, 16, 64)) + + @unittest.skipIf(not mx.is_available(mx.gpu), "requires GPU") + def test_conv2d_large_output_channels(self): + x = mx.random.normal((1, 33, 33, 5)) + w = mx.random.normal((32800, 1, 1, 5)) + yg = mx.conv2d(x, w, stride=(2, 2), stream=mx.gpu) + yc = mx.conv2d(x, w, stride=(2, 2), stream=mx.cpu) + mx.eval(yg, yc) + self.assertTrue(mx.allclose(yg, yc, atol=1e-3)) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_conv_transpose.py b/python/tests/test_conv_transpose.py index 7d12cb16f4..07ce6e74be 100644 --- a/python/tests/test_conv_transpose.py +++ b/python/tests/test_conv_transpose.py @@ -1,9 +1,7 @@ # Copyright © 2023-2024 Apple Inc. import math -import os import unittest -from itertools import permutations import mlx.core as mx import mlx_tests @@ -14,7 +12,7 @@ import torch.nn.functional as F has_torch = True -except ImportError as e: +except ImportError: has_torch = False @@ -24,7 +22,7 @@ def test_torch_conv_transpose_1D(self): def run_conv_transpose_1D( N, C, - O, + OC, iH, kH, stride, @@ -39,7 +37,7 @@ def run_conv_transpose_1D( dtype=dtype, N=N, C=C, - O=O, + O=OC, iH=iH, kH=kH, stride=stride, @@ -50,7 +48,7 @@ def run_conv_transpose_1D( np_dtype = getattr(np, dtype) np.random.seed(0) in_np = np.random.normal(0, 1.0 / C, (N, iH, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, int(C / groups))).astype( + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, int(C / groups))).astype( np_dtype ) @@ -80,7 +78,7 @@ def run_conv_transpose_1D( self.assertTrue(np.allclose(out_pt.numpy(), out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -91,10 +89,12 @@ def run_conv_transpose_1D( (3, 3, 1, 0), (31, 5, 5, 2), ): - run_conv_transpose_1D(N, C, O, iH, kH, stride, padding, dtype=dtype) + run_conv_transpose_1D( + N, C, OC, iH, kH, stride, padding, dtype=dtype + ) # Groups tests - N, C, O = (4, 32, 64) + N, C, OC = (4, 32, 64) for iH, kH, stride, padding in ( (1, 1, 1, 0), (3, 3, 1, 0), @@ -102,7 +102,7 @@ def run_conv_transpose_1D( ): for group in (1,): run_conv_transpose_1D( - N, C, O, iH, kH, stride, padding, groups=group, dtype=dtype + N, C, OC, iH, kH, stride, padding, groups=group, dtype=dtype ) # Strided inputs tests @@ -133,7 +133,7 @@ def test_torch_conv_transpose_1D_grad(self): def run_conv_transpose1D_grad( N, C, - O, + OC, iH, kH, stride, @@ -147,7 +147,7 @@ def run_conv_transpose1D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, iH=iH, kH=kH, stride=stride, @@ -160,7 +160,7 @@ def run_conv_transpose1D_grad( # oH = 1 + ((iH + 2 * padding - dilation * (kH - 1) - 1) // stride) in_np = np.random.normal(0, 1.0 / C, (N, iH, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, C)).astype(np_dtype) + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 2, 1)).requires_grad_(True) @@ -211,7 +211,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -223,7 +223,7 @@ def f(a, b): (31, 5, 5, 2), ): run_conv_transpose1D_grad( - N, C, O, iH, kH, stride, padding, dtype=dtype + N, C, OC, iH, kH, stride, padding, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -231,7 +231,7 @@ def test_torch_conv_transpose_2D(self): def run_conv_transpose2D( N, C, - O, + OC, idim, kdim, stride, @@ -245,7 +245,7 @@ def run_conv_transpose2D( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -259,9 +259,9 @@ def run_conv_transpose2D( kH, kW = kdim scale = 1.0 / math.sqrt(kH * kW * C) in_np = np.random.normal(0.0, scale, (N, iH, iW, C)).astype(np_dtype) - wt_np = np.random.normal(0.0, 1.0, (O, kH, kW, int(C / groups))).astype( - np_dtype - ) + wt_np = np.random.normal( + 0.0, 1.0, (OC, kH, kW, int(C / groups)) + ).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 3, 1, 2)).to("cpu") @@ -289,7 +289,7 @@ def run_conv_transpose2D( self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -301,11 +301,11 @@ def run_conv_transpose2D( ((31, 31), (5, 5), (5, 5), (2, 2)), ): run_conv_transpose2D( - N, C, O, idim, kdim, stride, padding, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dtype=dtype ) # Groups tests - N, C, O = (4, 32, 64) + N, C, OC = (4, 32, 64) for idim, kdim, stride, padding in ( ((1, 1), (1, 1), (1, 1), (0, 0)), ((3, 3), (3, 1), (1, 1), (0, 0)), @@ -313,7 +313,7 @@ def run_conv_transpose2D( ): for group in (1,): run_conv_transpose2D( - N, C, O, idim, kdim, stride, padding, groups=group, dtype=dtype + N, C, OC, idim, kdim, stride, padding, groups=group, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -321,7 +321,7 @@ def test_torch_conv_transpose_2D_grad(self): def run_conv_transpose2D_grad( N, C, - O, + OC, idim, kdim, stride, @@ -335,7 +335,7 @@ def run_conv_transpose2D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -347,10 +347,10 @@ def run_conv_transpose2D_grad( np.random.seed(0) iH, iW = idim kH, kW = kdim - scale = 1.0 / math.sqrt(kH * kW * C * O) + scale = 1.0 / math.sqrt(kH * kW * C * OC) in_np = np.random.normal(0.0, scale, (N, iH, iW, C)).astype(np_dtype) - wt_np = np.random.normal(0.0, scale, (O, kH, kW, C)).astype(np_dtype) + wt_np = np.random.normal(0.0, scale, (OC, kH, kW, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 3, 1, 2)).requires_grad_( @@ -400,7 +400,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 32, 64), (4, 16, 32)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (4, 32, 64), (4, 16, 32)): for idim, kdim, stride, padding, dilation in ( ((1, 1), (1, 1), (1, 1), (0, 0), (1, 1)), ((3, 3), (3, 1), (1, 1), (0, 0), (1, 1)), @@ -410,7 +410,7 @@ def f(a, b): ((32, 32), (3, 3), (2, 2), (1, 1), (3, 2)), ): run_conv_transpose2D_grad( - N, C, O, idim, kdim, stride, padding, dilation, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dilation, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -418,7 +418,7 @@ def test_torch_conv_transpose_3D(self): def run_conv_transpose3D( N, C, - O, + OC, idim, kdim, stride, @@ -432,7 +432,7 @@ def run_conv_transpose3D( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -444,11 +444,11 @@ def run_conv_transpose3D( np.random.seed(0) iD, iH, iW = idim kD, kH, kW = kdim - scale = 1.0 / math.sqrt(kD * kH * kW * C * O) + scale = 1.0 / math.sqrt(kD * kH * kW * C * OC) in_np = np.random.normal(0.0, scale, (N, iD, iH, iW, C)).astype( np_dtype ) - wt_np = np.random.normal(0.0, 1.0, (O, kD, kH, kW, C)).astype(np_dtype) + wt_np = np.random.normal(0.0, 1.0, (OC, kD, kH, kW, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 4, 1, 2, 3)) @@ -476,7 +476,7 @@ def run_conv_transpose3D( self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ( + for N, C, OC in ( (1, 1, 1), (1, 6, 1), (1, 1, 6), @@ -490,7 +490,7 @@ def run_conv_transpose3D( ((3, 4, 5), (2, 2, 2), (2, 2, 2), (0, 0, 0)), ): run_conv_transpose3D( - N, C, O, idim, kdim, stride, padding, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -498,7 +498,7 @@ def test_torch_conv_transpose_3D_grad(self): def run_conv_transpose3D_grad( N, C, - O, + OC, idim, kdim, stride, @@ -512,7 +512,7 @@ def run_conv_transpose3D_grad( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -524,12 +524,12 @@ def run_conv_transpose3D_grad( np.random.seed(0) iD, iH, iW = idim kD, kH, kW = kdim - scale = 1.0 / math.sqrt(kD * kH * kW * C * O) + scale = 1.0 / math.sqrt(kD * kH * kW * C * OC) in_np = np.random.normal(0.0, scale, (N, iD, iH, iW, C)).astype( np_dtype ) - wt_np = np.random.normal(0.0, scale, (O, kD, kH, kW, C)).astype( + wt_np = np.random.normal(0.0, scale, (OC, kD, kH, kW, C)).astype( np_dtype ) @@ -586,7 +586,7 @@ def f(a, b): self.assertTrue(np.allclose(pt_grad_wt, mx_grad_wt, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (2, 4, 8), (2, 8, 16)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (1, 1, 6), (2, 4, 8), (2, 8, 16)): for idim, kdim, stride, padding, dilation in ( ((1, 1, 1), (1, 1, 1), (1, 1, 1), (0, 0, 0), (1, 1, 1)), ((3, 3, 3), (3, 1, 1), (1, 1, 1), (0, 0, 0), (1, 1, 1)), @@ -596,19 +596,28 @@ def f(a, b): ((8, 8, 8), (3, 3, 3), (2, 2, 2), (1, 1, 1), (3, 2, 2)), ): run_conv_transpose3D_grad( - N, C, O, idim, kdim, stride, padding, dilation, dtype=dtype + N, C, OC, idim, kdim, stride, padding, dilation, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") def test_torch_conv_tranpose_1d_output_padding(self): def run_conv_transpose_1d_output_padding( - N, C, O, iH, kH, stride, padding, output_padding, dtype="float32", atol=1e-5 + N, + C, + OC, + iH, + kH, + stride, + padding, + output_padding, + dtype="float32", + atol=1e-5, ): with self.subTest( dtype=dtype, N=N, C=C, - O=O, + O=OC, iH=iH, kH=kH, stride=stride, @@ -618,7 +627,7 @@ def run_conv_transpose_1d_output_padding( np_dtype = getattr(np, dtype) np.random.seed(0) in_np = np.random.normal(0, 1.0 / C, (N, iH, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, C)).astype(np_dtype) + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 2, 1)) @@ -645,14 +654,14 @@ def run_conv_transpose_1d_output_padding( self.assertTrue(np.allclose(out_pt.numpy(), out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): for iH, kH, stride, padding, output_padding in ( (3, 2, 2, 0, 1), (5, 3, 2, 1, 0), (7, 4, 3, 1, 2), ): run_conv_transpose_1d_output_padding( - N, C, O, iH, kH, stride, padding, output_padding, dtype=dtype + N, C, OC, iH, kH, stride, padding, output_padding, dtype=dtype ) @unittest.skipIf(not has_torch, "requires Torch") @@ -660,7 +669,7 @@ def test_torch_conv_transpose_2d_output_padding(self): def run_conv_transpose_2d_output_padding( N, C, - O, + OC, idim, kdim, stride, @@ -673,7 +682,7 @@ def run_conv_transpose_2d_output_padding( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -685,7 +694,7 @@ def run_conv_transpose_2d_output_padding( iH, iW = idim kH, kW = kdim in_np = np.random.normal(0, 1.0 / C, (N, iH, iW, C)).astype(np_dtype) - wt_np = np.random.normal(0, 1.0 / C, (O, kH, kW, C)).astype(np_dtype) + wt_np = np.random.normal(0, 1.0 / C, (OC, kH, kW, C)).astype(np_dtype) in_mx, wt_mx = map(mx.array, (in_np, wt_np)) in_pt = torch.from_numpy(in_np.transpose(0, 3, 1, 2)) @@ -712,7 +721,7 @@ def run_conv_transpose_2d_output_padding( self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): for idim, kdim, stride, padding, output_padding in ( ((3, 3), (2, 2), (2, 2), (0, 0), (1, 1)), ((5, 5), (3, 3), (2, 2), (1, 1), (0, 0)), @@ -721,7 +730,7 @@ def run_conv_transpose_2d_output_padding( run_conv_transpose_2d_output_padding( N, C, - O, + OC, idim, kdim, stride, @@ -735,7 +744,7 @@ def test_torch_conv_transpose_3d_output_padding(self): def run_conv_transpose_3d_output_padding( N, C, - O, + OC, idim, kdim, stride, @@ -748,7 +757,7 @@ def run_conv_transpose_3d_output_padding( dtype=dtype, N=N, C=C, - O=O, + O=OC, idim=idim, kdim=kdim, stride=stride, @@ -762,7 +771,7 @@ def run_conv_transpose_3d_output_padding( in_np = np.random.normal(0, 1.0 / C, (N, iD, iH, iW, C)).astype( np_dtype ) - wt_np = np.random.normal(0, 1.0 / C, (O, kD, kH, kW, C)).astype( + wt_np = np.random.normal(0, 1.0 / C, (OC, kD, kH, kW, C)).astype( np_dtype ) @@ -790,7 +799,7 @@ def run_conv_transpose_3d_output_padding( self.assertTrue(np.allclose(out_pt, out_mx, atol=atol)) for dtype in ("float32",): - for N, C, O in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): + for N, C, OC in ((1, 1, 1), (1, 6, 1), (4, 32, 64)): for idim, kdim, stride, padding, output_padding in ( ((3, 3, 3), (2, 2, 2), (2, 2, 2), (0, 0, 0), (1, 1, 1)), ((5, 5, 5), (3, 3, 3), (2, 2, 2), (1, 1, 1), (0, 0, 0)), @@ -799,7 +808,7 @@ def run_conv_transpose_3d_output_padding( run_conv_transpose_3d_output_padding( N, C, - O, + OC, idim, kdim, stride, @@ -813,37 +822,27 @@ def test_conv_transpose_unfold_tiling(self): # The explicit-GEMM conv path unfolds into one buffer that can exceed # maxBufferLength for large outputs; it unfolds and runs the gemm in row # tiles instead (issue #3082). - key = "MLX_CONV_UNFOLD_TILE_ROWS" - prev = os.environ.get(key) cases = ( (mx.conv_transpose1d, (2, 9, 4), (5, 3, 4), {"stride": 2}), (mx.conv_transpose2d, (2, 5, 5, 4), (5, 3, 3, 4), {"stride": 2}), (mx.conv_transpose3d, (1, 4, 4, 4, 2), (3, 2, 2, 2, 2), {"stride": 2}), (mx.conv_transpose1d, (2, 9, 4), (6, 3, 2), {"stride": 2, "groups": 2}), ) - try: - # tile_rows=1 forces uniform tiles; 7 does not divide any output, so - # it exercises a partial final tile too. - for conv, in_shape, wt_shape, kwargs in cases: - for tile_rows in (1, 7): - with self.subTest( - conv=conv.__name__, tile_rows=tile_rows, **kwargs - ): - np.random.seed(0) - x = mx.array(np.random.normal(size=in_shape).astype(np.float32)) - w = mx.array(np.random.normal(size=wt_shape).astype(np.float32)) - os.environ.pop(key, None) + # tile_rows=1 forces uniform tiles; 7 does not divide any output, so + # it exercises a partial final tile too. + for conv, in_shape, wt_shape, kwargs in cases: + for tile_rows in (1, 7): + with self.subTest(conv=conv.__name__, tile_rows=tile_rows, **kwargs): + np.random.seed(0) + x = mx.array(np.random.normal(size=in_shape).astype(np.float32)) + w = mx.array(np.random.normal(size=wt_shape).astype(np.float32)) + with mlx_tests.scoped_env(MLX_CONV_UNFOLD_TILE_ROWS=None): untiled = conv(x, w, **kwargs) mx.eval(untiled) - os.environ[key] = str(tile_rows) + with mlx_tests.scoped_env(MLX_CONV_UNFOLD_TILE_ROWS=str(tile_rows)): tiled = conv(x, w, **kwargs) mx.eval(tiled) - self.assertTrue(np.allclose(untiled, tiled, atol=1e-4)) - finally: - if prev is None: - os.environ.pop(key, None) - else: - os.environ[key] = prev + self.assertTrue(np.allclose(untiled, tiled, atol=1e-4)) if __name__ == "__main__": diff --git a/python/tests/test_device.py b/python/tests/test_device.py index 6cd6df81fa..c0ed9ca900 100644 --- a/python/tests/test_device.py +++ b/python/tests/test_device.py @@ -1,5 +1,7 @@ # Copyright © 2023 Apple Inc. +import concurrent.futures +import gc import unittest import mlx.core as mx @@ -112,6 +114,44 @@ def test_op_on_stream(self): b = mx.add(x, y, stream=s_cpu) self.assertEqual(a.item(), b.item()) + def test_reentrant_stream_context(self): + default = mx.default_stream(mx.default_device()) + s = mx.new_stream(mx.default_device()) + context = mx.stream(s) + + with context: + with context: + self.assertEqual(mx.default_stream(mx.default_device()), s) + self.assertEqual(mx.default_stream(mx.default_device()), s) + self.assertEqual(mx.default_stream(mx.default_device()), default) + + def test_stream_context_exited_on_another_thread(self): + # A generator suspended inside `mx.stream(...)` and abandoned is + # finalized by the GC on whatever thread drops the last reference. + # Restoring there would install a foreign, thread-affine stream as + # that thread's default and break every later op on it. + abandoned = {} + + def on_worker(): + def gen(): + with mx.stream(mx.new_stream(mx.default_device())): + yield 1 + yield 2 + + g = gen() + next(g) + abandoned["gen"] = g + + before = mx.default_stream(mx.default_device()) + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(on_worker).result() + + del abandoned["gen"] + gc.collect() + + self.assertEqual(mx.default_stream(mx.default_device()), before) + mx.eval(mx.add(mx.array(1.0), mx.array(1.0))) + class TestDeviceInfo(mlx_tests.MLXTestCase): def test_device_count(self): diff --git a/python/tests/test_double.py b/python/tests/test_double.py index 3186e7e573..7cae2e19e9 100644 --- a/python/tests/test_double.py +++ b/python/tests/test_double.py @@ -1,8 +1,6 @@ # Copyright © 2024 Apple Inc. import math -import os -import unittest import mlx.core as mx import mlx_tests diff --git a/python/tests/test_einsum.py b/python/tests/test_einsum.py index 08884ae981..d9baa3a776 100644 --- a/python/tests/test_einsum.py +++ b/python/tests/test_einsum.py @@ -1,6 +1,5 @@ # Copyright © 2024 Apple Inc. -import unittest import mlx.core as mx import mlx_tests @@ -8,7 +7,6 @@ class TestEinsum(mlx_tests.MLXTestCase): - def test_simple_path(self): a = mx.zeros((5, 5)) path = mx.einsum_path("ii", a) diff --git a/python/tests/test_eval.py b/python/tests/test_eval.py index 265a090aa2..9801f82c7a 100644 --- a/python/tests/test_eval.py +++ b/python/tests/test_eval.py @@ -1,7 +1,6 @@ # Copyright © 2023 Apple Inc. import unittest -from functools import partial import mlx.core as mx import mlx_tests @@ -115,10 +114,10 @@ def fn(x): mx.eval(a) return a - out = mx.vjp(fn, (x,), (y,)) - out = mx.vjp(fn, (x,), (y,)) + _out = mx.vjp(fn, (x,), (y,)) + _out = mx.vjp(fn, (x,), (y,)) peak_mem = mx.get_peak_memory() - out = mx.vjp(fn, (x,), (y,)) + _out = mx.vjp(fn, (x,), (y,)) self.assertEqual(peak_mem, mx.get_peak_memory()) def test_async_eval_with_multiple_streams(self): @@ -128,7 +127,7 @@ def test_async_eval_with_multiple_streams(self): b = mx.array([1.0]) d = mx.default_device() - s2 = mx.new_stream(d) + _s2 = mx.new_stream(d) for _ in range(50): for _ in range(20): @@ -138,7 +137,6 @@ def test_async_eval_with_multiple_streams(self): def test_donation_for_noops(self): def fun(x): - s = x.shape for _ in range(10): x = mx.abs(x) x = mx.reshape(x, (-1,)) @@ -236,6 +234,27 @@ def test_async_eval_error_in_synchronize(self): with self.assertRaises(RuntimeError): mx.synchronize(mx.cpu) + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_eval_exception_after_cross_stream_wait(self): + # gather_qqmm has no CPU kernel. It fails in eval after the CPU + # stream waits for x from the GPU. + x = mx.multiply( + mx.full((2, 64), 3.0, stream=mx.gpu), + 2.0, + stream=mx.gpu, + ) + wq, scales = mx.quantize( + mx.ones((32, 64), stream=mx.gpu), + mode="nvfp4", + stream=mx.gpu, + )[:2] + y = mx.gather_qqmm(x, wq, scales, mode="nvfp4", stream=mx.cpu) + with self.assertRaises(RuntimeError): + mx.eval(y) + + self.assertTrue(mx.all(x == 6.0).item()) + self.assertEqual((mx.ones((4,), stream=mx.cpu) + 1).sum().item(), 8.0) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_export_import.py b/python/tests/test_export_import.py index 23f0645b3a..b8de6ce487 100644 --- a/python/tests/test_export_import.py +++ b/python/tests/test_export_import.py @@ -12,7 +12,6 @@ class TestExportImport(mlx_tests.MLXTestCase): - @classmethod def setUpClass(cls): cls.test_dir_fid = tempfile.TemporaryDirectory() @@ -160,7 +159,7 @@ def fun(x, z=None): return out x = mx.array([1, 2, 3]) - y = mx.array([1, 1, 0]) + _y = mx.array([1, 1, 0]) z = mx.array([2, 2, 2]) mx.export_function(path, fun, (x,), {"z": z}) @@ -332,6 +331,33 @@ def fun(a, v): out = imported_fun(x, y)[0] self.assertTrue(mx.array_equal(expected, out)) + def test_export_unique(self): + path = os.path.join(self.test_dir, "fn.mlxfn") + + # the fixed output size is what makes this exportable. The input is + # fixed so that the padded, exact and truncated cases are all covered + # rather than left to chance. + x = mx.array([3, 1, 2, 1, 3, 2, 1, 0, 2, 1]) # four unique values + for size, fill_value in ((10, None), (6, -1), (4, None), (2, None)): + + def fun(a): + return mx.unique( + a, + size, + return_index=True, + return_inverse=True, + return_counts=True, + fill_value=fill_value, + ) + + mx.export_function(path, fun, x) + imported_fun = mx.import_function(path) + expected = fun(x) + out = imported_fun(x) + self.assertEqual(len(out), len(expected)) + for e, o in zip(expected, out): + self.assertTrue(mx.array_equal(e, o)) + def test_export_conv(self): path = os.path.join(self.test_dir, "fn.mlxfn") diff --git a/python/tests/test_extension.py b/python/tests/test_extension.py new file mode 100644 index 0000000000..6900bbf29f --- /dev/null +++ b/python/tests/test_extension.py @@ -0,0 +1,393 @@ +# Copyright © 2026 Apple Inc. + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +import mlx.core as mx +from mlx.extension import ( + BuildExtension, + MetalExtension, + MetalLibrary, + _extension_paths, + _metal_extension_cmake, + _mlx_macos_deployment_target, +) +from setuptools import Distribution + + +@unittest.skipUnless(mx.metal.is_available(), "MetalExtension requires Metal") +class TestMetalExtension(unittest.TestCase): + def test_extension_paths_use_public_build_metadata(self): + extension = MetalExtension("sample._ext", ["bindings.cpp", "kernel.metal"]) + command = Mock() + command.build_lib = "/tmp/build" + command.get_ext_fullname.return_value = extension.name + command.get_ext_filename.return_value = "sample/_ext.so" + build_py = Mock() + build_py.get_package_dir.return_value = "/tmp/source/sample" + + inplace_file, regular_file = _extension_paths(command, build_py, extension) + + self.assertEqual(inplace_file, Path("/tmp/source/sample/_ext.so")) + self.assertEqual(regular_file, Path("/tmp/build/sample/_ext.so")) + command.get_ext_fullname.assert_called_once_with(extension.name) + command.get_ext_filename.assert_called_once_with(extension.name) + build_py.get_package_dir.assert_called_once_with("sample") + + def _cmake_configure_command( + self, command_type, cmake_args="", debug=False, mlx_target="14.0" + ): + extension = MetalExtension("sample._ext", ["bindings.cpp", "kernel.metal"]) + distribution = Distribution({"ext_modules": [extension]}) + with tempfile.TemporaryDirectory() as directory: + command = command_type(distribution) + command.build_lib = str(Path(directory) / "lib") + command.build_temp = str(Path(directory) / "temp") + command.debug = debug + command.parallel = 1 + with patch( + "mlx.extension._mlx_macos_deployment_target", + return_value=mlx_target, + ): + with patch("mlx.extension.subprocess.run") as run: + with patch.dict(os.environ, {"CMAKE_ARGS": cmake_args}): + command.build_extension(extension) + return run.call_args_list[0].args[0] + + def test_reads_mlx_macos_deployment_target(self): + vtool_output = """ +Load command 10 + cmd LC_BUILD_VERSION + platform MACOS + minos 14.0 +Load command 10 + cmd LC_BUILD_VERSION + platform MACOS + minos 15.2 +""" + with ( + patch("mlx.extension._MLX_PACKAGE_PATH", "/tmp/mlx"), + patch( + "mlx.extension.subprocess.check_output", return_value=vtool_output + ) as check_output, + ): + deployment_target = _mlx_macos_deployment_target() + + self.assertEqual(deployment_target, "15.2") + check_output.assert_called_once_with( + [ + "xcrun", + "vtool", + "-show-build", + "/tmp/mlx/lib/libmlx.dylib", + ], + stderr=subprocess.STDOUT, + text=True, + ) + + def test_build_extension_can_enable_ninja(self): + command_type = BuildExtension.with_options(use_ninja=True) + with patch("mlx.extension._is_ninja_available", return_value=True): + command = command_type(Distribution()) + configure_command = self._cmake_configure_command(command_type) + + self.assertTrue(command.use_ninja) + self.assertTrue(command.generate_stubs) + self.assertIn("-DMLX_METAL_DEBUG=OFF", configure_command) + generator_index = configure_command.index("-G") + self.assertEqual( + configure_command[generator_index : generator_index + 2], ["-G", "Ninja"] + ) + binary_dir = Path(configure_command[configure_command.index("-B") + 1]) + self.assertEqual(binary_dir.name, "build-ninja") + + def test_debug_build_enables_metal_debug(self): + command_type = BuildExtension.with_options(use_ninja=False) + configure_command = self._cmake_configure_command(command_type, debug=True) + + self.assertIn("-DCMAKE_BUILD_TYPE=Debug", configure_command) + self.assertIn("-DMLX_METAL_DEBUG=ON", configure_command) + + def test_build_extension_uses_mlx_macos_deployment_target(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {}, clear=True): + configure_command = self._cmake_configure_command( + command_type, mlx_target="15.2" + ) + + self.assertIn("-DCMAKE_OSX_DEPLOYMENT_TARGET=15.2", configure_command) + + def test_environment_overrides_macos_deployment_target(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {"MACOSX_DEPLOYMENT_TARGET": "15.0"}): + configure_command = self._cmake_configure_command( + command_type, mlx_target="16.0" + ) + + self.assertIn("-DCMAKE_OSX_DEPLOYMENT_TARGET=15.0", configure_command) + + def test_environment_rejects_macos_deployment_target_below_minimum(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {"MACOSX_DEPLOYMENT_TARGET": "13.0"}): + with self.assertRaisesRegex(ValueError, "must be at least 14.0"): + self._cmake_configure_command(command_type) + + def test_cmake_args_overrides_macos_deployment_target(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {}, clear=True): + configure_command = self._cmake_configure_command( + command_type, + cmake_args="-DCMAKE_OSX_DEPLOYMENT_TARGET=15.0", + mlx_target="16.0", + ) + + default_index = configure_command.index("-DCMAKE_OSX_DEPLOYMENT_TARGET=16.0") + override_index = configure_command.index("-DCMAKE_OSX_DEPLOYMENT_TARGET=15.0") + self.assertLess(default_index, override_index) + + def test_cmake_args_rejects_macos_deployment_target_below_minimum(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {}, clear=True): + with self.assertRaisesRegex(ValueError, "must be at least 14.0"): + self._cmake_configure_command( + command_type, + cmake_args="-DCMAKE_OSX_DEPLOYMENT_TARGET=13.0", + ) + + def test_build_extension_uses_default_generator(self): + with patch("mlx.extension._is_ninja_available") as is_ninja_available: + command = BuildExtension(Distribution()) + configure_command = self._cmake_configure_command(BuildExtension) + + self.assertFalse(command.use_ninja) + self.assertNotIn("-G", configure_command) + binary_dir = Path(configure_command[configure_command.index("-B") + 1]) + self.assertEqual(binary_dir.name, "build-default") + is_ninja_available.assert_not_called() + + def test_build_extension_falls_back_without_ninja(self): + command_type = BuildExtension.with_options(use_ninja=True) + with patch("mlx.extension._is_ninja_available", return_value=False): + with self.assertLogs("mlx.extension", level="WARNING") as logs: + command = command_type(Distribution()) + configure_command = self._cmake_configure_command(command_type) + + self.assertFalse(command.use_ninja) + self.assertNotIn("-G", configure_command) + binary_dir = Path(configure_command[configure_command.index("-B") + 1]) + self.assertEqual(binary_dir.name, "build-default") + self.assertIn("Falling back", "\n".join(logs.output)) + + def test_explicit_cmake_generator_overrides_ninja(self): + command_type = BuildExtension.with_options(use_ninja=True) + with patch("mlx.extension._is_ninja_available", return_value=True): + configure_command = self._cmake_configure_command( + command_type, cmake_args="-G Xcode" + ) + + self.assertEqual(configure_command.count("-G"), 1) + generator_index = configure_command.index("-G") + self.assertEqual( + configure_command[generator_index : generator_index + 2], ["-G", "Xcode"] + ) + binary_dir = Path(configure_command[configure_command.index("-B") + 1]) + self.assertEqual(binary_dir.name, "build-xcode") + + def test_cmake_generator_environment_uses_distinct_build_directory(self): + command_type = BuildExtension.with_options(use_ninja=False) + with patch.dict(os.environ, {"CMAKE_GENERATOR": "Unix Makefiles"}): + configure_command = self._cmake_configure_command(command_type) + + self.assertNotIn("-G", configure_command) + binary_dir = Path(configure_command[configure_command.index("-B") + 1]) + self.assertEqual(binary_dir.name, "build-unix_makefiles") + + def test_build_extension_can_disable_stub_generation(self): + command_type = BuildExtension.with_options(generate_stubs=False) + command = command_type(Distribution()) + extension = MetalExtension("sample._ext", ["bindings.cpp", "kernel.metal"]) + + self.assertFalse(command.generate_stubs) + with patch( + "mlx.extension._metal_extension_cmake", wraps=_metal_extension_cmake + ) as generate_cmake: + self._cmake_configure_command(command_type) + self.assertFalse(generate_cmake.call_args.kwargs["generate_stubs"]) + + cmake = _metal_extension_cmake( + extension, Path("/tmp/output"), generate_stubs=False + ) + self.assertNotIn("nanobind.stubgen", cmake) + self.assertNotIn("_ext.pyi", cmake) + self.assertIn("mlx_extension_metallib", cmake) + + def test_extension_metadata(self): + extension = MetalExtension( + "sample._ext", + ["bindings.cpp", "silu.metal", "gelu.metal"], + extra_compile_args={"cxx": ["-O2"], "metal": ["-O3"]}, + ) + + self.assertEqual( + extension.sources, + ["bindings.cpp", "silu.metal", "gelu.metal"], + ) + self.assertEqual(extension.language, "c++") + self.assertFalse(extension.py_limited_api) + self.assertEqual(extension.metal_library_name, "_ext") + self.assertEqual(len(extension.metal_libraries), 1) + self.assertEqual(extension.metal_libraries[0].name, "_ext") + self.assertEqual( + extension.metal_libraries[0].sources, + ["silu.metal", "gelu.metal"], + ) + self.assertEqual( + extension.extra_compile_args, + {"cxx": ["-O2"], "metal": ["-O3"]}, + ) + + def test_requires_host_source(self): + with self.assertRaisesRegex(ValueError, "C\\+\\+ source"): + MetalExtension("sample._ext", ["kernel.metal"]) + + def test_compile_argument_list_applies_to_cxx(self): + extension = MetalExtension( + "sample._ext", + ["bindings.cpp", "silu.metal", "gelu.metal"], + extra_compile_args=["-O2"], + ) + + self.assertEqual( + extension.extra_compile_args, + {"cxx": ["-O2"], "metal": []}, + ) + + def test_requires_metal_source(self): + with self.assertRaisesRegex(ValueError, "Metal source"): + MetalExtension("sample._ext", ["bindings.cpp"]) + + def test_explicit_metal_libraries(self): + extension = MetalExtension( + "sample._ext", + ["bindings.cpp"], + metal_libraries=[ + MetalLibrary("first", ["first.metal"]), + MetalLibrary( + "second", + ["second.metal"], + extra_compile_args=["-O3"], + deployment_target="26.2", + ), + ], + extra_compile_args={"metal": ["-Wno-unused"]}, + ) + + self.assertEqual( + [library.name for library in extension.metal_libraries], + ["first", "second"], + ) + cmake = _metal_extension_cmake(extension, Path("/tmp/output")) + self.assertIn("TITLE [=[first]=]", cmake) + self.assertIn("TITLE [=[second]=]", cmake) + self.assertIn("TARGET mlx_extension_metallib_0", cmake) + self.assertIn("TARGET mlx_extension_metallib_1", cmake) + self.assertIn("DEPLOYMENT_TARGET [=[26.2]=]", cmake) + self.assertIn("[=[-Wno-unused]=]\n [=[-O3]=]", cmake) + self.assertIn( + "add_dependencies(mlx_extension mlx_extension_metallib_0 " + "mlx_extension_metallib_1)", + cmake, + ) + + def test_rejects_mixed_metal_source_forms(self): + with self.assertRaisesRegex(ValueError, "specified in metal_libraries"): + MetalExtension( + "sample._ext", + ["bindings.cpp", "kernel.metal"], + metal_libraries=[MetalLibrary("kernels", ["other.metal"])], + ) + + def test_rejects_duplicate_metal_library_names(self): + with self.assertRaisesRegex(ValueError, "must be unique"): + MetalExtension( + "sample._ext", + ["bindings.cpp"], + metal_libraries=[ + MetalLibrary("kernels", ["first.metal"]), + MetalLibrary("kernels", ["second.metal"]), + ], + ) + + def test_rejects_unknown_compile_argument_group(self): + with self.assertRaisesRegex(ValueError, "cxx.*metal"): + MetalExtension( + "sample._ext", + ["bindings.cpp", "kernel.metal"], + extra_compile_args={"nvcc": ["-O3"]}, + ) + + def test_rejects_non_list_compile_arguments(self): + with self.assertRaisesRegex(TypeError, "must be lists"): + MetalExtension( + "sample._ext", + ["bindings.cpp", "kernel.metal"], + extra_compile_args={"metal": "-O3"}, + ) + + def test_generated_cmake_builds_module_and_metallib(self): + extension = MetalExtension( + "sample._ext", + ["bindings.cpp", "silu.metal", "gelu.metal"], + include_dirs=["include"], + extra_compile_args={"cxx": ["-Wall"], "metal": ["-O3"]}, + ) + + cmake = _metal_extension_cmake(extension, Path("/tmp/output")) + + self.assertIn("nanobind_add_module(", cmake) + self.assertIn("cmake_minimum_required(VERSION 3.25)", cmake) + self.assertIn( + "find_package(Python 3.10 COMPONENTS " + "Interpreter Development.Module REQUIRED)", + cmake, + ) + self.assertNotIn("Development.SABIModule", cmake) + self.assertNotIn(" STABLE_ABI", cmake) + self.assertIn("TITLE [=[_ext]=]", cmake) + self.assertIn("COMPILE_OPTIONS\n [=[-O3]=]", cmake) + self.assertIn(str(Path("silu.metal").resolve()), cmake) + self.assertIn(str(Path("gelu.metal").resolve()), cmake) + self.assertIn("[=[MLX_EXTENSION_NAME=_ext]=]", cmake) + self.assertIn('[=[MLX_METAL_LIBRARY_NAME="_ext"]=]', cmake) + self.assertIn("target_compile_options(mlx_extension PRIVATE", cmake) + self.assertIn("[=[-Wall]=]", cmake) + self.assertIn("BUILD_WITH_INSTALL_RPATH TRUE", cmake) + self.assertIn("INSTALL_RPATH [=[@loader_path;@loader_path/../mlx/lib]=]", cmake) + self.assertNotIn("BUILD_RPATH", cmake) + self.assertIn("from nanobind.stubgen import main", cmake) + self.assertIn("import mlx.core", cmake) + self.assertIn("OUTPUT [=[/tmp/output/_ext.pyi]=]", cmake) + self.assertIn("DEPENDS mlx_extension", cmake) + + def test_generated_cmake_uses_nested_package_mlx_rpath(self): + extension = MetalExtension("sample.ops._ext", ["bindings.cpp", "kernel.metal"]) + + cmake = _metal_extension_cmake(extension, Path("/tmp/output")) + + self.assertIn("@loader_path/../../mlx/lib", cmake) + + def test_rejects_python_stable_abi(self): + with self.assertRaisesRegex(ValueError, "does not support py_limited_api"): + MetalExtension( + "sample._ext", + ["bindings.cpp", "kernel.metal"], + py_limited_api=True, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/python/tests/test_fast.py b/python/tests/test_fast.py index 200781d372..dfdcc18242 100644 --- a/python/tests/test_fast.py +++ b/python/tests/test_fast.py @@ -166,7 +166,7 @@ def test_rope(self): dims, _, base, scale, offset, traditional = defaults x = (mx.random.uniform(shape=(2, T, dims)) * 10).astype(mx.int32) with self.assertRaises(ValueError): - y = mx.fast.rope( + mx.fast.rope( x, dims, traditional=traditional, base=base, scale=scale, offset=offset ) @@ -284,19 +284,22 @@ def test_rope_with_freqs(self): self.assertLess(mx.abs(rx - rx_fast).max(), 1e-5) # Test grad with freqs - f1 = lambda x, y: (rope_orig(x, dims, False, None, 1.0, 0, freqs) * y).sum() - f2 = lambda x, y: ( - mx.fast.rope( - x, - dims, - traditional=False, - base=None, - scale=1.0, - offset=0, - freqs=freqs, - ) - * y - ).sum() + def f1(x, y): + return (rope_orig(x, dims, False, None, 1.0, 0, freqs) * y).sum() + + def f2(x, y): + return ( + mx.fast.rope( + x, + dims, + traditional=False, + base=None, + scale=1.0, + offset=0, + freqs=freqs, + ) + * y + ).sum() x = mx.random.uniform(shape=(2, 4, dims)) y = mx.random.uniform(shape=(2, 4, dims)) @@ -310,20 +313,24 @@ def test_rope_grad(self): for dims in (D, D // 2): for traditional in (True, False): _, base, scale, offset, _ = defaults - f1 = lambda x, y: ( - rope_orig(x, dims, traditional, base, scale, offset) * y - ).sum() - f2 = lambda x, y: ( - mx.fast.rope( - x, - dims, - traditional=traditional, - base=base, - scale=scale, - offset=offset, - ) - * y - ).sum() + + def f1(x, y): + return ( + rope_orig(x, dims, traditional, base, scale, offset) * y + ).sum() + + def f2(x, y): + return ( + mx.fast.rope( + x, + dims, + traditional=traditional, + base=base, + scale=scale, + offset=offset, + ) + * y + ).sum() x = mx.random.uniform(shape=(2, 100, D)) y = mx.random.uniform(shape=(2, 100, D)) @@ -373,7 +380,7 @@ def test_rope_batch(self): rx_fast = mx.fast.rope( x, dims, traditional=traditional, scale=scale, base=base, offset=offset ) - rx_fast_single = mx.fast.rope( + _rx_fast_single = mx.fast.rope( x[0:1], dims, traditional=traditional, scale=scale, base=base, offset=offset ) @@ -484,10 +491,18 @@ def test_rms_norm(self): def test_rms_norm_grad(self): eps = 1e-5 - f1 = lambda x, w, y: (rms_norm(x, w, eps) * y).sum() - f2 = lambda x, w, y: (mx.fast.rms_norm(x, w, eps) * y).sum() - f3 = lambda x, y: (rms_norm(x, mx.ones((x.shape[-1],)), eps) * y).sum() - f4 = lambda x, y: (mx.fast.rms_norm(x, None, eps) * y).sum() + + def f1(x, w, y): + return (rms_norm(x, w, eps) * y).sum() + + def f2(x, w, y): + return (mx.fast.rms_norm(x, w, eps) * y).sum() + + def f3(x, y): + return (rms_norm(x, mx.ones((x.shape[-1],)), eps) * y).sum() + + def f4(x, y): + return (mx.fast.rms_norm(x, None, eps) * y).sum() for D in [32, 256]: x = mx.random.uniform(shape=(8, 100, D)) @@ -535,6 +550,9 @@ def cross_entropy_ref(logits, targets): ) tolerances = {mx.float32: 1e-5, mx.float16: 3e-2, mx.bfloat16: 3e-1} + # The fused GPU kernels accumulate in float32 for every input dtype. + if mx.default_device() == mx.gpu: + tolerances = {mx.float32: 1e-5, mx.float16: 1e-3, mx.bfloat16: 1e-3} for V in [7, 32, 128, 255, 256, 1000, 4096, 8192]: for dtype in [mx.float32, mx.float16, mx.bfloat16]: @@ -565,8 +583,11 @@ def ref(logits, targets): ) return mx.logsumexp(logits, axis=-1) - score - f1 = lambda x, y: ref(x, y).mean() - f2 = lambda x, y: mx.fast.cross_entropy(x, y).mean() + def f1(x, y): + return ref(x, y).mean() + + def f2(x, y): + return mx.fast.cross_entropy(x, y).mean() for V in [7, 128, 1000, 4096]: logits = mx.random.normal(shape=(4, 7, V), scale=2.0) @@ -577,8 +598,13 @@ def ref(logits, targets): self.assertLess(mx.abs(g1 - g2).max().item(), 1e-6) w = mx.random.uniform(shape=(4, 7)) - f3 = lambda x, y: (ref(x, y) * w).sum() - f4 = lambda x, y: (mx.fast.cross_entropy(x, y) * w).sum() + + def f3(x, y): + return (ref(x, y) * w).sum() + + def f4(x, y): + return (mx.fast.cross_entropy(x, y) * w).sum() + logits = mx.random.normal(shape=(4, 7, 512), scale=2.0) targets = mx.random.randint(0, 512, shape=(4, 7)) g1 = mx.grad(f3, argnums=0)(logits, targets) @@ -684,7 +710,6 @@ def test_layer_norm(self): self.assertLess(mx.abs(rx - rx_fast).max(), tolerances[dtype]) def test_slice_into_layer_norm(self): - dim = 128 eps = 1e-5 x = mx.random.uniform(shape=(8, 100, 128))[:, 99:] rx_fast = mx.fast.layer_norm(x, weight=None, bias=None, eps=eps) @@ -694,8 +719,12 @@ def test_slice_into_layer_norm(self): def test_layer_norm_grad(self): D = 32 eps = 1e-5 - f1 = lambda x, w, b, y: (layer_norm(x, w, b, eps) * y).sum() - f2 = lambda x, w, b, y: (mx.fast.layer_norm(x, w, b, eps) * y).sum() + + def f1(x, w, b, y): + return (layer_norm(x, w, b, eps) * y).sum() + + def f2(x, w, b, y): + return (mx.fast.layer_norm(x, w, b, eps) * y).sum() x = mx.random.uniform(shape=(8, 100, D)) w = mx.random.uniform(shape=(D,)) @@ -746,8 +775,11 @@ def test_layer_norm_grad_no_bias(self): y = mx.random.uniform(shape=(2, 4, D)) mx.eval(x, w, y) - f_ref = lambda x, w, y: (layer_norm(x, w, None, eps) * y).sum() - f_fast = lambda x, w, y: (mx.fast.layer_norm(x, w, None, eps) * y).sum() + def f_ref(x, w, y): + return (layer_norm(x, w, None, eps) * y).sum() + + def f_fast(x, w, y): + return (mx.fast.layer_norm(x, w, None, eps) * y).sum() # First order should match reference gx1, gw1 = mx.grad(f_ref, argnums=(0, 1))(x, w, y) @@ -772,8 +804,13 @@ def inner(x, w, y): def test_layer_norm_grad_no_params(self): eps = 1e-5 - f1 = lambda x: layer_norm(x, None, None, eps).sum() - f2 = lambda x: mx.fast.layer_norm(x, None, None, eps).sum() + + def f1(x): + return layer_norm(x, None, None, eps).sum() + + def f2(x): + return mx.fast.layer_norm(x, None, None, eps).sum() + x = mx.random.normal(shape=(2, 2, 8)) mx.eval(x) @@ -783,8 +820,12 @@ def test_layer_norm_grad_no_params(self): def test_layer_norm_grad_params(self): eps = 1e-5 - f1 = lambda params, x: (layer_norm(x, params[0], params[1], eps)).sum() - f2 = lambda params, x: (mx.fast.layer_norm(x, params[0], params[1], eps)).sum() + + def f1(params, x): + return (layer_norm(x, params[0], params[1], eps)).sum() + + def f2(params, x): + return (mx.fast.layer_norm(x, params[0], params[1], eps)).sum() w = mx.ones((8,)) b = mx.zeros((8,)) @@ -944,7 +985,8 @@ def test_custom_kernel_strides(self): elif mx.cuda.is_available(): source = """ auto elem = cooperative_groups::this_grid().thread_rank(); - auto loc = elem_to_loc(elem, inp_shape.data(), inp_strides.data(), inp_ndim); + auto loc = elem_to_loc( + elem, inp_shape.data(), inp_strides.data(), inp_ndim); T tmp = inp[loc]; out[elem] = exp(tmp) * WARP_SIZE; """ @@ -1239,6 +1281,28 @@ def call_kernel(a: mx.array): out = call_kernel(a).astype(mx.float32) + call_kernel(b) self.assertTrue(mx.allclose(out, mx.full((32,), 8.0))) + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_custom_metal_kernel_negative_template_int(self): + # Negative int template values used to produce a '-' in the generated + # kernel name (via make_template_hash), which fails Metal compilation + # (#4579). + kernel = mx.fast.metal_kernel( + name="negtmpl", + input_names=["inp"], + output_names=["out"], + source="out[thread_position_in_grid.x] = T(V);", + ) + (out,) = kernel( + inputs=[mx.zeros((4,), dtype=mx.int32)], + template=[("T", mx.int32), ("V", -1)], + grid=(4, 1, 1), + threadgroup=(4, 1, 1), + output_shapes=[(4,)], + output_dtypes=[mx.int32], + ) + mx.eval(out) + self.assertEqual(out.tolist(), [-1, -1, -1, -1]) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_fast_gated_delta.py b/python/tests/test_fast_gated_delta.py new file mode 100644 index 0000000000..f0a5255ff6 --- /dev/null +++ b/python/tests/test_fast_gated_delta.py @@ -0,0 +1,341 @@ +import os +import unittest + +import mlx.core as mx +import mlx_tests +import numpy as np + +try: + import torch + + has_torch = True +except ImportError: + has_torch = False + + +def gated_delta_oracle( + q, + k, + v, + beta, + g, + scale=None, + initial_state=None, + output_final_state=False, +): + """ + Reference PyTorch implementation of recurrent gated delta rule. + Taken from: https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/naive.py + + Args: + q: [B, T, H, K] + k: [B, T, H, K] + v: [B, T, H, V] + beta: [B, T, H] + g: [B, T, H] <--- Difference: with out kernel: + this is expected as a log. + scale: float, optional <--- Difference: This is done by the + qwen3_5 model. + initial_state: [B, H, K, V], optional <- Difference: last two dimensions + are transposed. + output_final_state: bool + + Returns: + o: [B, T, H, V] + final_state: [B, H, K, V] if output_final_state else None + """ + q, k, v, beta, g = map( + lambda x: x.transpose(1, 2).contiguous().to(torch.float32), [q, k, v, beta, g] + ) + B, H, T, K, V = *k.shape, v.shape[-1] + o = torch.zeros(B, H, T, V).to(v) + h = torch.zeros(B, H, K, V).to(v) + if initial_state is not None: + h = initial_state.to(torch.float32) + if scale is None: + scale = 1 / (q.shape[-1] ** 0.5) + q = q * scale + + for i in range(T): + b_q = q[:, :, i] + b_k = k[:, :, i] + b_v = v[:, :, i].clone() + h = h.clone() * g[:, :, i].exp()[..., None, None] + b_beta = beta[:, :, i] + b_v = b_v - (h.clone() * b_k[..., None]).sum(-2) + b_v = b_v * b_beta[..., None] + h = h.clone() + b_k.unsqueeze(-1) * b_v.unsqueeze(-2) + o[:, :, i] = torch.einsum("bhd,bhdm->bhm", b_q, h) + + if not output_final_state: + h = None + o = o.transpose(1, 2).contiguous() + return o, h + + +def runner(dims, stream=mx.gpu, reference=True): + B, Hk, Hv, T, Dk, Dv = dims + + assert Hv % Hk == 0 + repeat_factor = Hv // Hk + + q = mx.random.normal(shape=(B, T, Hk, Dk)) + k = mx.random.normal(shape=(B, T, Hk, Dk)) + k = k / (mx.linalg.norm(k, axis=-1, keepdims=True) + 1e-6) + v = mx.random.normal(shape=(B, T, Hv, Dv)) + g = mx.random.uniform(shape=(B, T, Hv)) + b = mx.sigmoid(mx.random.normal(shape=(B, T, Hv))) + h0 = mx.random.normal((B, Hv, Dv, Dk), dtype=mx.float32) + + if reference: + # Prepare reference inputs + qpt = torch.from_numpy(np.array(q)) + kpt = torch.from_numpy(np.array(k)) + vpt = torch.from_numpy(np.array(v)) + bpt = torch.from_numpy(np.array(b)) + gpt = torch.from_numpy(np.array(g)) + h0pt = torch.from_numpy(np.array(h0)).transpose(-1, -2).contiguous() + + if repeat_factor > 1: + qpt = qpt.repeat_interleave(repeat_factor, dim=2) + kpt = kpt.repeat_interleave(repeat_factor, dim=2) + + out_on_py, hf_on_py = gated_delta_oracle( + qpt, + kpt, + vpt, + bpt, + torch.log(gpt), + scale=1.0, + initial_state=h0pt, + output_final_state=True, + ) + + out_on = mx.array(out_on_py.detach().cpu().numpy()) # [B, T, Hv, Dv] + hf_on = mx.swapaxes( + mx.array(hf_on_py.detach().cpu().numpy()), -1, -2 + ) # -> [B, Hv, Dv, Dk] + out_ref = mx.array(out_on) + hf_ref = mx.array(hf_on) + else: + # use fallback for tests once fallback is validated by setting a mask instead of + # using the cpu + mask = mx.ones((B, T)) + + out_ref, hf_ref = mx.fast.gated_delta_update( + q, + k, + v, + g, + b, + initial_state=h0, + mask=mask, + ) + + mx.eval(out_ref, hf_ref) + + out, hf = mx.fast.gated_delta_update(q, k, v, g, b, initial_state=h0, stream=stream) + + mx.eval(out, hf) + return (out, hf), (out_ref, hf_ref) + + +class TestGatedDelta(mlx_tests.MLXTestCase): + base_dims = (1, 32, 32, 1, 128, 128) + unaligned_dims = (1, 32, 32, 33, 128, 128) + big_batch_dims = (128, 32, 32, 16, 128, 128) + large_t_dims = (2, 32, 32, 1111, 128, 128) + diff_heads = (1, 16, 32, 33, 128, 128) + diff_heads2 = (1, 16, 48, 33, 128, 128) + unsupported_heads1 = (1, 8, 32, 33, 128, 128) + unsupported_heads2 = (1, 24, 48, 33, 128, 128) + + fallback_dims = [unsupported_heads1, unsupported_heads2] + gpu_dims = [ + base_dims, + unaligned_dims, + big_batch_dims, + diff_heads, + diff_heads2, + large_t_dims, + ] + vjp_dims = [base_dims, unaligned_dims, diff_heads, diff_heads2] + + @unittest.skipIf(not has_torch, "requires Torch") + def test_gated_delta_fallback(self): + for dims in self.fallback_dims: + (out, hf), (out_ref, hf_ref) = runner(dims, mx.cpu) + msg = f"Failed on Dimensions: {dims}" + self.assertTrue( + mx.allclose(out_ref, out, atol=1e-4, rtol=1e-4), msg="Out " + msg + ) + self.assertTrue( + mx.allclose(hf_ref, hf, atol=1e-4, rtol=1e-4), msg="State " + msg + ) + + def test_gated_delta_fallback_masked(self): + for dims in self.fallback_dims: + B, Hk, Hv, T, Dk, Dv = dims + + q = mx.random.normal(shape=(B, T, Hk, Dk)) + k = mx.random.normal(shape=(B, T, Hk, Dk)) + k = k / (mx.linalg.norm(k, axis=-1, keepdims=True) + 1e-6) + v = mx.random.normal(shape=(B, T, Hv, Dv)) + g = mx.random.uniform(shape=(B, T, Hv)) + b = mx.sigmoid(mx.random.normal(shape=(B, T, Hv))) + h0 = mx.random.normal((B, Hv, Dv, Dk), dtype=mx.float32) + + # make a mask + lengths = mx.random.randint(1, T + 1, shape=(B,)) + mask = mx.arange(T)[None, :] < lengths[:, None] + # mask one input in python + mask_float = mask.astype(q.dtype) + km = k * mask_float[..., None, None] + vm = v * mask_float[..., None, None] + qm = q * mask_float[..., None, None] + bm = b * mask_float[..., None] + gm = mx.where(mask[..., None], g, 1.0) + + out_ref, hf_ref = mx.fast.gated_delta_update( + qm, + km, + vm, + gm, + bm, + initial_state=h0, + ) + + mx.eval(out_ref, hf_ref) + out, hf = mx.fast.gated_delta_update( + q, + k, + v, + g, + b, + initial_state=h0, + mask=mask, + ) + mx.eval(out, hf) + + msg = f"Failed on Dimensions: {dims}" + self.assertTrue( + mx.allclose(out_ref, out, atol=1e-4, rtol=1e-4), msg="Out " + msg + ) + self.assertTrue( + mx.allclose(hf_ref, hf, atol=1e-4, rtol=1e-4), msg="State " + msg + ) + + def test_gated_delta_dtypes(self): + dtypes = [mx.bfloat16, mx.float32] + for dtype in dtypes: + for dims in [self.base_dims]: + B, Hk, Hv, T, Dk, Dv = dims + + q = mx.random.normal(shape=(B, T, Hk, Dk), dtype=dtype) + k = mx.random.normal(shape=(B, T, Hk, Dk), dtype=dtype) + k = k / (mx.linalg.norm(k, axis=-1, keepdims=True) + 1e-6) + v = mx.random.normal(shape=(B, T, Hv, Dv), dtype=dtype) + g = mx.random.uniform(shape=(B, T, Hv), dtype=dtype) + b = mx.sigmoid(mx.random.normal(shape=(B, T, Hv), dtype=dtype)) + h0 = mx.random.normal((B, Hv, Dv, Dk), dtype=mx.float32) + + out, hf = mx.fast.gated_delta_update(q, k, v, g, b, initial_state=h0) + + msg = f"Output dtype mismatch on Dimensions: {dims}" + self.assertTrue(dtype == out.dtype, msg="Out " + msg) + self.assertTrue(hf.dtype == mx.float32, msg="State " + msg) + + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_gated_delta_sequential(self): + os.environ["GATED_DELTA_CHUNK"] = "0" + for dims in self.gpu_dims: + (out, hf), (out_ref, hf_ref) = runner(dims, reference=False) + msg = f"Failed on Dimensions: {dims}" + self.assertTrue( + mx.allclose(out_ref, out, atol=1e-4, rtol=1e-4), msg="Out " + msg + ) + self.assertTrue( + mx.allclose(hf_ref, hf, atol=1e-4, rtol=1e-4), msg="State " + msg + ) + + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_gated_delta_simdgroup(self): + os.environ["GATED_DELTA_CHUNK"] = "8" + for dims in self.gpu_dims: + (out, hf), (out_ref, hf_ref) = runner(dims, reference=False) + msg = f"Failed on Dimensions: {dims}" + self.assertTrue( + mx.allclose(out_ref, out, atol=1e-4, rtol=1e-4), msg="Out " + msg + ) + self.assertTrue( + mx.allclose(hf_ref, hf, atol=1e-4, rtol=1e-4), msg="State " + msg + ) + + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_gated_delta_nax(self): + os.environ["GATED_DELTA_CHUNK"] = "16" + for dims in self.gpu_dims: + (out, hf), (out_ref, hf_ref) = runner(dims, reference=False) + msg = f"Failed on Dimensions: {dims}" + self.assertTrue( + mx.allclose(out_ref, out, atol=1e-1, rtol=1e-4), msg="Out " + msg + ) + self.assertTrue( + mx.allclose(hf_ref, hf, atol=1e-1, rtol=1e-4), msg="State " + msg + ) + + @unittest.skipIf(not mx.metal.is_available(), "Metal is not available") + def test_gated_delta_vjp(self): + for dims in self.vjp_dims: + B, Hk, Hv, T, Dk, Dv = dims + + mx.random.seed(0) + q = mx.random.normal(shape=(B, T, Hk, Dk)) + k = mx.random.normal(shape=(B, T, Hk, Dk)) + k = k / (mx.linalg.norm(k, axis=-1, keepdims=True) + 1e-6) + v = mx.random.normal(shape=(B, T, Hv, Dv)) + g = mx.sigmoid(mx.random.normal(shape=(B, T, Hv))) + b = mx.sigmoid(mx.random.normal(shape=(B, T, Hv))) + h0 = mx.random.normal((B, Hv, Dv, Dk), dtype=mx.float32) + primals = [q, k, v, g, b, h0] + + cotans = [ + mx.random.normal(shape=(B, T, Hv, Dv)) * 1e-2, + mx.random.normal(shape=(B, Hv, Dv, Dk)) * 1e-2, + ] + + def f(q, k, v, g, b, h0): + out, state = mx.fast.gated_delta_update(q, k, v, g, b, initial_state=h0) + return out, state + + def run(fallback, chunk): + with mlx_tests.scoped_env( + GATED_DELTA_VJP_FALLBACK="1" if fallback else "0", + GATED_DELTA_CHUNK_VJP=str(chunk), + ): + outs, vjps = mx.vjp(f, primals, cotans) + mx.eval(outs, vjps) + return outs, vjps + + o_ref, vjp_ref = run(True, 0) + + for chunk in (0, 16): + rtol = 1e-5 if chunk == 0 else 1e-2 + atol = 1e-5 if chunk == 0 else 1e-2 + with self.subTest(dims=dims, chunk=chunk): + o_out, vjp_out = run(False, chunk) + for i in range(len(o_ref)): + self.assertTrue( + mx.allclose(o_ref[i], o_out[i], rtol=rtol, atol=atol), + msg=f"Output {i}, dims={dims}, chunk={chunk}", + ) + for i in range(len(vjp_ref)): + self.assertTrue( + mx.allclose(vjp_ref[i], vjp_out[i], rtol=rtol, atol=atol), + msg=f"Grad {i}, dims={dims}, chunk={chunk}", + ) + mx.clear_cache() + + +if __name__ == "__main__": + mlx_tests.MLXTestRunner(failfast=True) diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 3a9c04b075..03a2951e01 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -28,7 +28,6 @@ def mlx_ref_attn(q, k, v, scale=1.0, mask=None, sinks=None): scores = q @ mx.swapaxes(k, -1, -2) is_causal = mask == "causal" if mask is not None: - if is_causal: offset = kL - L q_indices = mx.arange(L) + offset @@ -145,6 +144,60 @@ def test_sdpa_head_dim_72(self): diff = mx.abs(out - ref) - atol * mx.abs(ref) self.assertLessEqual(mx.max(diff).item(), atol) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_pad_head_dim_opt_in(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + with mlx_tests.scoped_env(MLX_SDPA_PAD_HEAD_DIM="1"): + self.test_sdpa_head_dim_72() + self.test_sdpa_head_dim_80() + self.test_sdpa_head_dim_72_80_sinks() + + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_head_dim_80(self): + B, D, qH, kH = (1, 80, 8, 2) + for qL, kL, dtype, mask_str in product( + (64, 65), + (128, 127), + (mx.float16, mx.bfloat16, mx.float32), + (None, "additive", "bool", "causal"), + ): + with self.subTest(qL=qL, kL=kL, dtype=dtype, mask=mask_str): + q, k, v, scale, mask = prepare_inputs( + B, qL, kL, D, qH, kH, mask_str, False, dtype + ) + ref = mlx_ref_attn(q, k, v, scale, mask) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + ) + + if dtype == mx.float32: + atol = 1e-5 + elif dtype == mx.bfloat16: + atol = 5e-3 + else: + atol = 3e-4 + diff = mx.abs(out - ref) - atol * mx.abs(ref) + self.assertLessEqual(mx.max(diff).item(), atol) + + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_head_dim_72_80_sinks(self): + B, qH, kH, qL, kL = (1, 8, 2, 64, 128) + for D, dtype in product((72, 80), (mx.float16, mx.bfloat16)): + with self.subTest(D=D, dtype=dtype): + q, k, v, scale, _ = prepare_inputs( + B, qL, kL, D, qH, kH, None, False, dtype + ) + sinks = 10 * mx.random.normal(shape=(qH,), dtype=dtype) + ref = mlx_ref_attn(q, k, v, scale, sinks=sinks) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, sinks=sinks + ) + + atol = 5e-3 if dtype == mx.bfloat16 else 3e-4 + diff = mx.abs(out - ref) - atol * mx.abs(ref) + self.assertLessEqual(mx.max(diff).item(), atol) + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") def test_sdpa_head_dim_96(self): B, D, qH, kH = (1, 96, 8, 2) @@ -172,6 +225,75 @@ def test_sdpa_head_dim_96(self): diff = mx.abs(out - ref) - atol * mx.abs(ref) self.assertLessEqual(mx.max(diff).item(), atol) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_full_d96_v64(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + mx.random.seed(0) + scale = 96**-0.5 + cells = [ + (1, 40, 40, 9, 33), + (1, 4, 4, 64, 64), + (2, 4, 2, 65, 97), + (1, 4, 4, 16, 9), + (1, 4, 2, 32, 31), + (1, 4, 2, 33, 32), + ] + for dtype, (B, qH, kH, qL, kL) in product( + (mx.float16, mx.bfloat16, mx.float32), cells + ): + q = ( + (0.5 * mx.random.normal((B, qL, qH, 96))) + .astype(dtype) + .transpose(0, 2, 1, 3) + ) + k = (0.5 * mx.random.normal((B, kH, kL + 32, 96))).astype(dtype)[:, :, :kL] + masks = [ + None, + mx.arange(kL) < kL - 3, + mx.random.normal((qL, kL)).astype(dtype), + ] + if qL <= kL: + masks.append("causal") + for dv, mask, with_sinks in product((64, 96), masks, (False, True)): + with self.subTest( + dtype=dtype, + cell=(B, qH, kH, qL, kL), + dv=dv, + mask=type(mask).__name__, + sinks=with_sinks, + ): + v = (0.5 * mx.random.normal((B, kH, kL + 32, dv))).astype(dtype)[ + :, :, :kL + ] + if qL == 9: + # V sliced from the interleaved K/V projection. + v = (0.5 * mx.random.normal((B, kL, kH, 2 * dv))).astype(dtype) + v = v.transpose(0, 2, 1, 3)[..., dv:] + sinks = ( + mx.random.normal((qH,)).astype(dtype) if with_sinks else None + ) + ref = mlx_ref_attn( + q.astype(mx.float32), + k.astype(mx.float32), + v.astype(mx.float32), + scale, + mask, + sinks, + ) + out = mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + mask=mask, + sinks=sinks, + force_fused=True, + ) + self.assertEqual(out.shape, (B, qH, qL, dv)) + tol = 5e-3 if dtype == mx.bfloat16 else 1e-3 + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") def test_sdpa_full_head_dim_256(self): # On NAX devices, large nearly-square causal blocks take the fused @@ -239,6 +361,161 @@ def test_sdpa_full_head_dim_256(self): tol = 5e-3 self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + return + + mx.random.seed(0) + cases = ( + (1, 4, 2, 1024, 1057, 1152), + (2, 2, 1, 1025, 1025, None), + (1, 2, 1, 1024, 4103, 4128), + ) + for dtype, (B, qH, kH, qL, kL, cache_len) in product( + (mx.float16, mx.bfloat16), cases + ): + with self.subTest(dtype=dtype, qL=qL, kL=kL): + q = (0.5 * mx.random.normal((B, qH, qL, 512))).astype(dtype) + kv_len = cache_len or kL + k_cache = (0.5 * mx.random.normal((B, kH, kv_len, 512))).astype(dtype) + v_cache = (0.5 * mx.random.normal((B, kH, kv_len, 512))).astype(dtype) + k = k_cache[..., :kL, :] + v = v_cache[..., :kL, :] + scale = 512**-0.5 + ref = mlx_ref_attn(q, k, v, scale=scale, mask="causal") + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask="causal" + ) + tol = 1e-2 if dtype == mx.bfloat16 else 1e-3 + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + + q = mx.random.normal((1, 2, 1024, 512), mx.float16) + k = mx.random.normal((1, 1, 1057, 512), mx.float16) + v = mx.random.normal((1, 1, 1057, 512), mx.float16) + scale = 512**-0.5 + mask = mx.random.uniform(shape=(1, 1, 1024, 1057)) > 0.2 + sinks = mx.random.normal((2,), mx.float16) + fallback_cases = ( + (v, mask, None), + (v, "causal", sinks), + (v[..., :128], "causal", None), + ) + for v_arg, mask_arg, sinks_arg in fallback_cases: + ref = mlx_ref_attn(q, k, v_arg, scale=scale, mask=mask_arg, sinks=sinks_arg) + out = mx.fast.scaled_dot_product_attention( + q, k, v_arg, scale=scale, mask=mask_arg, sinks=sinks_arg + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) + + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_full_head_dim_512_nax(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + + D = 512 + scale = D**-0.5 + mx.random.seed(0) + + q_probe = mx.random.normal(shape=(1, 2, 9, D)).astype(mx.bfloat16) + k_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16) + v_probe = mx.random.normal(shape=(1, 1, 31, D)).astype(mx.bfloat16) + try: + mx.eval( + mx.fast.scaled_dot_product_attention( + q_probe, + k_probe, + v_probe, + scale=scale, + force_fused=True, + ) + ) + except ValueError as e: + if "plus head dim 512 on NAX GPUs" not in str(e): + raise + self.skipTest("D512 full attention requires NAX") + + cases = [ + # Multiple query tiles with GQA. + (1, 8, 2, 257, 513, None, True), + # Multiple batches and a ragged final tile. + (2, 4, 1, 513, 777, None, True), + # Gemma 4 31B default route at the work threshold with sliced K/V. + (1, 32, 16, 1024, 1025, 1056, False), + ] + for dtype in (mx.float16, mx.bfloat16): + for B, Nq, Nkv, qL, kL, cache_len, force_fused in cases: + with self.subTest( + dtype=dtype, + B=B, + Nq=Nq, + Nkv=Nkv, + qL=qL, + kL=kL, + cache_len=cache_len, + ): + q = mx.random.normal(shape=(B, Nq, qL, D)).astype(dtype) + if cache_len is None: + k = mx.random.normal(shape=(B, Nkv, kL, D)).astype(dtype) + v = mx.random.normal(shape=(B, Nkv, kL, D)).astype(dtype) + else: + k = mx.random.normal(shape=(B, Nkv, cache_len, D)).astype( + dtype + )[..., :kL, :] + v = mx.random.normal(shape=(B, Nkv, cache_len, D)).astype( + dtype + )[..., :kL, :] + + ref = mlx_ref_attn(q, k, v, scale, "causal") + out = mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + mask="causal", + force_fused=force_fused, + ) + tol = 2e-3 if dtype != mx.bfloat16 else 5e-2 + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + + q = mx.random.normal(shape=(1, 8, 33, D)).astype(mx.bfloat16) + k = mx.random.normal(shape=(1, 2, 67, D)).astype(mx.bfloat16) + v = mx.random.normal(shape=(1, 2, 67, D)).astype(mx.bfloat16) + ref = mlx_ref_attn(q, k, v, scale) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, force_fused=True + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-2, rtol=1e-2)) + + bool_mask = mx.random.uniform(shape=(1, 1, 33, 67)) > 0.2 + additive_mask = mx.where(bool_mask, 0.0, -1e4).astype(mx.bfloat16) + for mask in (bool_mask, additive_mask): + ref = mlx_ref_attn(q, k, v, scale, mask) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-2, rtol=1e-2)) + + q_same = mx.random.normal(shape=(1, 8, 33, D)).astype(mx.bfloat16) + k_same = mx.random.normal(shape=(1, 2, 67, D)).astype(mx.bfloat16) + v_slice = mx.random.normal(shape=(1, 2, 67, D // 4)).astype(mx.bfloat16) + v_same = mx.tile(v_slice, (1, 1, 1, 4)) + out_same = mx.fast.scaled_dot_product_attention( + q_same, k_same, v_same, scale=scale, force_fused=True + ) + for d_group in range(1, 4): + self.assertTrue( + mx.array_equal( + out_same[..., : D // 4], + out_same[..., d_group * D // 4 : (d_group + 1) * D // 4], + ) + ) + + sinks = mx.random.normal(shape=(8,)).astype(mx.bfloat16) + ref = mlx_ref_attn(q, k, v, scale, sinks=sinks) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, sinks=sinks, force_fused=True + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-2, rtol=1e-2)) + def test_sdpa_vector_kv_transposed_head_seq(self): D = 64 Nq = 4 @@ -277,6 +554,7 @@ def test_sdpa_vector(self): Nq = 4 Nkv = 1 scale = 1.0 + tol = 1e-3 if mx.cuda.is_available() else 1e-4 mx.random.seed(0) q = 5e-1 * mx.random.normal(shape=(1, Nq, 1, D)) k = 5e-1 * mx.random.normal(shape=(1, Nkv, L, D)) @@ -312,7 +590,7 @@ def test_sdpa_vector(self): scale=scale, mask=m, ) - self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) L = 4096 scale = 1.0 @@ -341,16 +619,22 @@ def test_sdpa_vector(self): scale=scale, mask=m, ) - self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) def test_sdpa_vector_gqa_long(self): scale = 1.0 mx.random.seed(0) - for Nq, Nkv, D in [(32, 4, 128), (64, 8, 64)]: - for L in [8192, 8201]: - q = 5e-1 * mx.random.normal(shape=(1, Nq, 1, D)) - k = 5e-1 * mx.random.normal(shape=(1, Nkv, L + 32, D))[:, :, :L] - v = 5e-1 * mx.random.normal(shape=(1, Nkv, L + 32, D))[:, :, :L] + for Nq, Nkv, D in [ + (32, 4, 128), + (64, 8, 64), + (48, 4, 128), + (64, 4, 128), + (16, 2, 256), + ]: + for B, L in [(1, 8192), (1, 8201), (2, 8192)]: + q = 5e-1 * mx.random.normal(shape=(B, Nq, 1, D)) + k = 5e-1 * mx.random.normal(shape=(B, Nkv, L + 32, D))[:, :, :L] + v = 5e-1 * mx.random.normal(shape=(B, Nkv, L + 32, D))[:, :, :L] kr = mx.repeat(k, Nq // Nkv, axis=1) vr = mx.repeat(v, Nq // Nkv, axis=1) ref = mlx_primitives_sdpa(q, kr, vr, scale) @@ -405,6 +689,126 @@ def test_sdpa_two_pass_partial_overflow(self): mx.array_equal(out, mx.full(out.shape, 32768, mx.float16)) ) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_vector_d96_v64(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + mx.random.seed(0) + scale = 96**-0.5 + # Include MiniCPM3 heads and GQA to reach two-pass on smaller GPUs. + cells = [(1, 40, 40, 1, 127), (1, 40, 40, 8, 1025), (2, 4, 2, 4, 4097)] + for dtype, (B, qH, kH, qL, kL) in product( + (mx.float32, mx.float16, mx.bfloat16), cells + ): + q = mx.random.normal((B, qL, qH, 96)).astype(dtype) + q = q.transpose(0, 2, 1, 3) + k = mx.random.normal((B, kH, kL + 32, 96)).astype(dtype)[:, :, :kL] + v = mx.random.normal((B, kH, kL + 32, 64)).astype(dtype)[:, :, :kL] + masks = ( + None, + "causal", + mx.arange(kL) < kL - 3, + mx.random.normal((qL, kL)).astype(dtype), + ) + for mask in masks: + with self.subTest( + dtype=dtype, cell=(B, qH, kH, qL, kL), mask=type(mask).__name__ + ): + # GPU float32 GEMM may use TF32; keep the reference exact. + with mx.stream(mx.cpu): + ref = mlx_ref_attn( + q.astype(mx.float32), + k.astype(mx.float32), + v.astype(mx.float32), + scale, + mask, + ) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + self.assertEqual(out.shape, (B, qH, qL, 64)) + tol = ( + 1e-5 + if dtype == mx.float32 + else (3e-3 if dtype == mx.float16 else 2e-2) + ) + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) + + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_vector_head_dim_512(self): + if mx.default_device() != mx.gpu: + self.skipTest("requires GPU") + # gemma-4 global attention: 32 query heads over 4 key/value heads. + D = 512 + Nq, Nkv = 32, 4 + scale = D**-0.5 + mx.random.seed(0) + + with mlx_tests.scoped_env(MLX_SDPA_D512_MIN_KL="0"): + # Test 1-pass kernel. + for dtype in (mx.float32, mx.float16, mx.bfloat16): + with self.subTest(L=128, dtype=dtype, threshold="off"): + q = mx.random.normal(shape=(1, Nq, 1, D), dtype=dtype) + k = mx.random.normal(shape=(1, Nkv, 128, D), dtype=dtype) + v = mx.random.normal(shape=(1, Nkv, 128, D), dtype=dtype) + ref = mlx_ref_attn(q, k, v, scale) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, force_fused=True + ) + atol = 1e-5 if dtype == mx.float32 else 2e-2 + self.assertTrue(mx.allclose(ref, out, atol=atol)) + + # Test 2-pass kernel. + for L, dtype in product( + (8192, 8201), (mx.float32, mx.float16, mx.bfloat16) + ): + with self.subTest(L=L, dtype=dtype): + q = mx.random.normal(shape=(1, Nq, 1, D), dtype=dtype) + k = mx.random.normal(shape=(1, Nkv, L, D), dtype=dtype) + v = mx.random.normal(shape=(1, Nkv, L, D), dtype=dtype) + ref = mlx_ref_attn(q, k, v, scale) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, force_fused=True + ) + atol = 1e-5 if dtype == mx.float32 else 2e-2 + self.assertTrue(mx.allclose(ref, out, atol=atol)) + + # Test other heads. + for q_heads, kv_heads in ((8, 8), (32, 8)): + with self.subTest(q_heads=q_heads, kv_heads=kv_heads): + q = mx.random.normal(shape=(1, q_heads, 1, D)) + k = mx.random.normal(shape=(1, kv_heads, L, D)) + v = mx.random.normal(shape=(1, kv_heads, L, D)) + ref = mlx_ref_attn(q, k, v, scale) + out = mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + force_fused=True, + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + + # Test batched. + B = 2 + sinks = 10 * mx.random.normal(shape=(Nq,)) + q = mx.random.normal(shape=(B, Nq, 1, D)) + for L in (256, 8192): + k = mx.random.normal(shape=(B, Nkv, L, D)) + v = mx.random.normal(shape=(B, Nkv, L, D)) + for s_in in (None, sinks): + with self.subTest(L=L, sinks=s_in is not None): + ref = mlx_ref_attn(q, k, v, scale, sinks=s_in) + out = mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + sinks=s_in, + force_fused=True, + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + def test_sdpa_fully_masked(self): Lkv = 8 mask = mx.array(False) @@ -544,6 +948,53 @@ def test_sdpa_vector_batched(self): ref = mlx_ref_attn(q, k, v, mask=mask) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") + def test_sdpa_vector_2pass_threadgroup_limit(self): + for dtype, D, q_heads, kv_heads, q_len in ( + (mx.float16, 192, 32, 8, 8), + (mx.float16, 256, 24, 4, 5), + (mx.float16, 256, 32, 4, 4), + (mx.bfloat16, 256, 24, 4, 5), + (mx.bfloat16, 256, 32, 4, 4), + (mx.float32, 192, 32, 8, 8), + (mx.float32, 256, 24, 4, 5), + (mx.float32, 256, 32, 4, 4), + ): + # float16 only exceeded the limit without a causal mask, so cover + # all three mask kinds. + bool_mask = mx.random.uniform(shape=(1, 1, q_len, 1029)) < 0.5 + for mask in ("causal", None, bool_mask): + mask_name = mask if not isinstance(mask, mx.array) else "bool" + with self.subTest(dtype=dtype, D=D, q_len=q_len, mask=mask_name): + self.assertGreater(32 * q_heads // kv_heads * q_len, 896) + q = mx.random.normal(shape=(1, q_heads, q_len, D), dtype=dtype) + k = mx.random.normal(shape=(1, kv_heads, 1029, D), dtype=dtype) + v = mx.random.normal(shape=(1, kv_heads, 1029, D), dtype=dtype) + scale = D**-0.5 + + if mx.default_device() != mx.gpu: + # The fused kernels need a GPU stream. + with self.assertRaises(ValueError): + mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + continue + + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=True + ) + ref = mlx_ref_attn( + q.astype(mx.float32), + k.astype(mx.float32), + v.astype(mx.float32), + scale=scale, + mask=mask, + ) + atol = 1e-4 if dtype == mx.float32 else 2e-3 + if dtype == mx.bfloat16: + atol = 2e-2 + self.assertTrue(mx.allclose(out.astype(mx.float32), ref, atol=atol)) + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") def test_sdpa_blocks_env_override(self): # MLX_SDPA_BLOCKS used to be applied as-is, and values that are not @@ -554,13 +1005,10 @@ def test_sdpa_blocks_env_override(self): k = mx.random.normal(shape=(1, 8, 8192, D), dtype=mx.float16) v = mx.random.normal(shape=(1, 8, 8192, D), dtype=mx.float16) ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=D**-0.5) - try: - for blocks in (16, 33, 48, 100): - os.environ["MLX_SDPA_BLOCKS"] = str(blocks) + for blocks in (16, 33, 48, 100): + with mlx_tests.scoped_env(MLX_SDPA_BLOCKS=str(blocks)): out = mx.fast.scaled_dot_product_attention(q, k, v, scale=D**-0.5) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) - finally: - del os.environ["MLX_SDPA_BLOCKS"] @unittest.skipIf(not mx.is_available(mx.gpu), "too slow on CPU") def test_sdpa(self): @@ -617,15 +1065,16 @@ def test_sdpa(self): out_ref = do_attention(mlx_ref_attn, q, k, v, scale, mask, t) - out_fst = do_attention( - mx.fast.scaled_dot_product_attention, - q, - k, - v, - scale, - mask, - t, - ) + with mlx_tests.scoped_env(MLX_ENABLE_TF32="0"): + out_fst = do_attention( + mx.fast.scaled_dot_product_attention, + q, + k, + v, + scale, + mask, + t, + ) # For causal mask when qL > kL, first qL-kL rows are undefined # Compare only the valid portion @@ -711,6 +1160,20 @@ def test_sdpa_noncontiguous_inputs(self): ref = mlx_ref_attn(q, k, v, scale=1.0, mask=mask) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + def test_sdpa_vector_reversed_mask(self): + mx.random.seed(0) + q = mx.random.normal(shape=(1, 2, 1, 64)) + k = mx.random.normal(shape=(1, 2, 16, 64)) + v = mx.random.normal(shape=(1, 2, 16, 64)) + masks = [ + mx.random.normal(shape=(1, 2, 1, 16))[..., ::-1], + (mx.arange(16) % 3 != 0).reshape(1, 1, 1, 16)[..., ::-1], + ] + for mask in masks: + out = mx.fast.scaled_dot_product_attention(q, k, v, scale=0.125, mask=mask) + ref = mlx_ref_attn(q, k, v, scale=0.125, mask=mask) + self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + def test_sdpa_promote_mask(self): mask = mx.array(2.0, mx.bfloat16) D = 64 @@ -836,60 +1299,74 @@ def test_grad(slow, fast, args): mask_bool = mx.random.uniform(0, 1, (B, N_q, T, T), dtype=mx.float16) < 0.5 for mask in (None, "causal", mask_additive, mask_bool): - sdpa_slow = lambda q, k, v: mlx_ref_attn( - q, k, v, scale=scale, mask=mask - ) - sdpa_fast = lambda q, k, v: mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, mask=mask - ) + + def sdpa_slow(q, k, v): + return mlx_ref_attn(q, k, v, scale=scale, mask=mask) + + def sdpa_fast(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + ) + test_vjp(sdpa_slow, sdpa_fast, [q, k, v]) - loss_slow = lambda q, k, v: mlx_ref_attn( - q, k, v, scale=scale, mask=mask - ).sum() - loss_fast = lambda q, k, v: mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, mask=mask - ).sum() + def loss_slow(q, k, v): + return mlx_ref_attn(q, k, v, scale=scale, mask=mask).sum() + + def loss_fast(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + ).sum() + test_grad(loss_slow, loss_fast, [q, k, v]) @unittest.skipIf(not mx.metal.is_available(), "Metal kernel path only") def test_sdpa_force_fused_metal(self): if mx.default_device() != mx.gpu: self.skipTest("requires GPU") + mx.random.seed(0) - def make_qkv(qL, kL, D, qH=8, kH=8): - q = mx.random.normal((1, qH, qL, D), mx.float16) - k = mx.random.normal((1, kH, kL, D), mx.float16) - v = mx.random.normal((1, kH, kL, D), mx.float16) + def make_qkv(qL, kL, D, qH=8, kH=8, dtype=mx.float16): + q = mx.random.normal((1, qH, qL, D), dtype) + k = mx.random.normal((1, kH, kL, D), dtype) + v = mx.random.normal((1, kH, kL, D), dtype) return q, k, v # Full attention kernel. - for D, qL, mask in product((192, 256), (9, 16), (None, "causal")): - with self.subTest(head_dim=D, qL=qL, mask=mask): - q, k, v = make_qkv(qL, 512, D, 8, 4) + for D, qL, kL, mask, dtype in product( + (192, 256), + (9, 16), + (31, 512), + (None, "causal"), + (mx.bfloat16, mx.float32), + ): + with self.subTest(head_dim=D, qL=qL, kL=kL, mask=mask): + q, k, v = make_qkv(qL, kL, D, 8, 4) scale = D**-0.5 ref = mlx_ref_attn(q, k, v, scale=scale, mask=mask) out = mx.fast.scaled_dot_product_attention( q, k, v, scale=scale, mask=mask, force_fused=True ) - self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) + tol = 1e-2 if dtype == mx.bfloat16 else 1e-3 + self.assertTrue(mx.allclose(ref, out, atol=tol, rtol=tol)) # Vector attention kernel. - for D in (192, 256): + for D in (192, 256, 512): with self.subTest(head_dim=D): - q, k, v = make_qkv(4, 16385, D, 4, 2) - scale = D**-0.5 - ref = mlx_ref_attn(q, k, v, scale=scale) - out = mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, force_fused=True - ) - self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) + with mlx_tests.scoped_env(MLX_SDPA_D512_MIN_KL="0"): + q, k, v = make_qkv(4, 16385, D, 4, 2) + scale = D**-0.5 + ref = mlx_ref_attn(q, k, v, scale=scale) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, force_fused=True + ) + self.assertTrue(mx.allclose(ref, out, atol=1e-3, rtol=1e-3)) # No full attention fused kernels. with self.assertRaisesRegex(ValueError, "supports head dims"): - q, k, v = make_qkv(16, 512, 512) + q, k, v = make_qkv(16, 512, 1024) mx.fast.scaled_dot_product_attention( - q, k, v, scale=512**-0.5, force_fused=True + q, k, v, scale=1024**-0.5, force_fused=True ) with self.assertRaisesRegex( ValueError, "query sequence to be no longer than the key sequence" @@ -915,6 +1392,12 @@ def make_qkv(qL, kL, D, qH=8, kH=8): mx.fast.scaled_dot_product_attention( q, k, v, scale=64**-0.5, force_fused=True ) + with self.assertRaisesRegex(ValueError, r"requires at least \d+ keys"): + with mlx_tests.scoped_env(MLX_SDPA_D512_MIN_KL=None): + q, k, v = make_qkv(1, 512, 512, qH=32, kH=4) + mx.fast.scaled_dot_product_attention( + q, k, v, scale=512**-0.5, force_fused=True + ) # No CPU fused kernel. with mx.stream(mx.cpu): @@ -936,7 +1419,7 @@ def make_qkv(qL, kL, D, qH=8, kH=8): return q, k, v # Vector attention kernel. - for D in (64, 96, 128): + for D in (64, 96, 128, 256): with self.subTest(head_dim=D): q, k, v = make_qkv(3, 128, D, 4, 2) scale = D**-0.5 diff --git a/python/tests/test_fft.py b/python/tests/test_fft.py index 0820c25093..cd19165f26 100644 --- a/python/tests/test_fft.py +++ b/python/tests/test_fft.py @@ -11,7 +11,7 @@ import torch has_torch = True -except ImportError as e: +except ImportError: has_torch = False @@ -59,6 +59,15 @@ def test_fft(self): x = np.fft.rfft(np.real(a_np)) self.check_mx_np(mx.fft.irfft, np.fft.irfft, x) + # Real transforms of size one + a_np = np.arange(1, 5, dtype=np.float32).reshape(4, 1) + self.check_mx_np(mx.fft.rfft, np.fft.rfft, a_np) + x = np.fft.rfft(a_np) + self.check_mx_np(mx.fft.irfft, np.fft.irfft, x, n=1) + self.check_mx_np(mx.fft.rfft2, np.fft.rfft2, a_np) + x = np.fft.rfft2(a_np) + self.check_mx_np(mx.fft.irfft2, np.fft.irfft2, x, s=(4, 1)) + def test_fftn(self): r = np.random.randn(8, 8, 8).astype(np.float32) i = np.random.randn(8, 8, 8).astype(np.float32) @@ -388,9 +397,9 @@ def test_ifftshift(self): def test_fftshift_errors(self): # Test invalid axes x = mx.array(np.random.rand(4, 4).astype(np.float32)) - with self.assertRaises(ValueError): + with self.assertRaises(IndexError): mx.fft.fftshift(x, axes=[2]) - with self.assertRaises(ValueError): + with self.assertRaises(IndexError): mx.fft.fftshift(x, axes=[-3]) # Test empty array @@ -467,23 +476,165 @@ def make_ffts(self): def test_fft_vmap(self): for fftn, a_np, axes in self.make_ffts(): a = mx.array(a_np) - f = lambda x: fftn(x, axes=axes) + + def f(x): + return fftn(x, axes=axes) + expected = mx.stack([f(a[i]) for i in range(a.shape[0])]) out = mx.vmap(f)(a) self.assertEqual(tuple(out.shape), tuple(expected.shape)) np.testing.assert_allclose(out, expected, atol=1e-5, rtol=1e-5) + def test_fft_vmap_explicit_size(self): + # An inverse real transform to an odd length is not recoverable from + # the input shape. + shape = (3, 8, 6) + a = mx.array(np.random.rand(*shape) + 1j * np.random.rand(*shape)) + for n in [10, 11, 12, 13]: + for fftn, axes in [ + (mx.fft.irfftn, (-1,)), + (mx.fft.irfftn, (-2, -1)), + (mx.fft.ifftn, (-1,)), + ]: + s_arg = [shape[-2], n] if len(axes) == 2 else [n] + + def f(x): + return fftn(x, s=s_arg, axes=axes) + + expected = mx.stack([f(a[i]) for i in range(a.shape[0])]) + out = mx.vmap(f)(a) + self.assertEqual(tuple(out.shape), tuple(expected.shape)) + np.testing.assert_allclose(out, expected, atol=1e-5, rtol=1e-5) + def test_fft_jvp(self): # The fft is linear so the jvp is the fft of the tangent for fftn, a_np, axes in self.make_ffts(): a = mx.array(a_np) t = mx.array(np.random.rand(*a_np.shape).astype(a_np.dtype)) - f = lambda x: fftn(x, axes=axes) + + def f(x): + return fftn(x, axes=axes) + expected = f(t) out = mx.jvp(f, [a], [t])[1][0] self.assertEqual(tuple(out.shape), tuple(expected.shape)) np.testing.assert_allclose(out, expected, atol=1e-5, rtol=1e-5) + @unittest.skipIf(not has_torch, "requires PyTorch") + def test_stft(self): + def check(x_np, win_np, n_fft, hop, win_len, center, pad_mode, norm, one): + win_mx = None if win_np is None else mx.array(win_np) + win_pt = None if win_np is None else torch.tensor(win_np) + z_mx = mx.fft.stft( + mx.array(x_np), + n_fft=n_fft, + hop_length=hop, + win_length=win_len, + window=win_mx, + center=center, + pad_mode=pad_mode, + norm=norm, + onesided=one, + ) + z_pt = torch.stft( + torch.tensor(x_np), + n_fft=n_fft, + hop_length=hop, + win_length=win_len, + window=win_pt, + center=center, + pad_mode="replicate" if pad_mode == "edge" else pad_mode, + normalized=(norm == "ortho"), + onesided=one, + return_complex=True, + ) + np.testing.assert_allclose( + np.array(z_mx), z_pt.numpy(), atol=1e-4, rtol=1e-4 + ) + + np.random.seed(0) + x = np.random.randn(16000).astype(np.float32) + han = np.hanning(400).astype(np.float32) + h256 = np.hanning(256).astype(np.float32) + check(x, han, 400, 160, 400, True, "reflect", "backward", True) + check(x, han, 512, 128, 400, False, "constant", "backward", True) + check(x, han, 400, 160, 400, True, "edge", "backward", True) + check(x, han, 400, 160, 400, True, "reflect", "ortho", True) + check(x, h256, 256, 64, 256, True, "reflect", "backward", False) + check(x, None, 256, 64, 256, True, "reflect", "backward", True) + xb = np.random.randn(2, 16000).astype(np.float32) + check(xb, h256, 256, 64, 256, True, "reflect", "backward", True) + + @unittest.skipIf(not has_torch, "requires PyTorch") + def test_istft(self): + def check(x_np, win_np, n_fft, hop, center, norm, one, length): + win_mx = None if win_np is None else mx.array(win_np) + win_pt = None if win_np is None else torch.tensor(win_np) + z = mx.fft.stft( + mx.array(x_np), + n_fft=n_fft, + hop_length=hop, + window=win_mx, + center=center, + norm=norm, + onesided=one, + ) + y_mx = mx.fft.istft( + z, + n_fft=n_fft, + hop_length=hop, + window=win_mx, + center=center, + norm=norm, + onesided=one, + length=length, + ) + y_pt = torch.istft( + torch.tensor(np.array(z)), + n_fft=n_fft, + hop_length=hop, + window=win_pt, + center=center, + normalized=(norm == "ortho"), + onesided=one, + length=length, + ) + np.testing.assert_allclose( + np.array(y_mx), y_pt.numpy(), atol=1e-4, rtol=1e-4 + ) + + np.random.seed(0) + x = np.random.randn(16000).astype(np.float32) + win = np.hanning(512).astype(np.float32) + check(x, win, 512, 128, True, "backward", True, 16000) + # n_fft not divisible by hop, no explicit length (length must still match) + check(x, win, 512, 160, True, "backward", True, None) + # center=False needs an edge-nonzero window for torch's NOLA check + check(x, None, 512, 160, False, "backward", True, None) + check(x, win, 512, 128, True, "ortho", True, 16000) + check(x, None, 512, 256, True, "backward", False, 16000) + # odd n_fft (passed explicitly, since onesided inference is even) + check( + x, + np.hanning(257).astype(np.float32), + 257, + 64, + True, + "backward", + True, + 16000, + ) + xb = np.random.randn(2, 16000).astype(np.float32) + check(xb, win, 512, 128, True, "backward", True, 16000) + + # norm="forward" has no torch.istft flag; check the round-trip directly + win_mx = mx.array(win) + z = mx.fft.stft( + mx.array(x), n_fft=512, hop_length=128, window=win_mx, norm="forward" + ) + y = mx.fft.istft(z, hop_length=128, window=win_mx, norm="forward", length=16000) + np.testing.assert_allclose(np.array(y)[1000:-1000], x[1000:-1000], atol=1e-4) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_graph.py b/python/tests/test_graph.py index 7c6a114128..147232b663 100644 --- a/python/tests/test_graph.py +++ b/python/tests/test_graph.py @@ -1,7 +1,6 @@ # Copyright © 2023 Apple Inc. import io -import unittest import mlx.core as mx import mlx_tests diff --git a/python/tests/test_init.py b/python/tests/test_init.py index bd8d9fa4f5..a5ca08f74e 100644 --- a/python/tests/test_init.py +++ b/python/tests/test_init.py @@ -1,6 +1,5 @@ # Copyright © 2023 Apple Inc. import math -import unittest import mlx.core as mx import mlx.nn.init as init @@ -129,10 +128,11 @@ def test_orthogonal(self): self.assertEqual(result.shape, shape) self.assertEqual(result.dtype, mx.float32) - I = result @ result.T + identity = result @ result.T eye = mx.eye(shape[0], dtype=mx.float32) self.assertTrue( - mx.allclose(I, eye, atol=1e-5), "Orthogonal init failed on a square matrix." + mx.allclose(identity, eye, atol=1e-5), + "Orthogonal init failed on a square matrix.", ) # Test with a rectangular matrix: more rows than cols @@ -141,10 +141,10 @@ def test_orthogonal(self): self.assertEqual(result.shape, shape) self.assertEqual(result.dtype, mx.float32) - I = result.T @ result + identity = result.T @ result eye = mx.eye(shape[1], dtype=mx.float32) self.assertTrue( - mx.allclose(I, eye, atol=1e-5), + mx.allclose(identity, eye, atol=1e-5), "Orthogonal init failed on a rectangular matrix.", ) diff --git a/python/tests/test_linalg.py b/python/tests/test_linalg.py index 52e02e4d9a..12065835da 100644 --- a/python/tests/test_linalg.py +++ b/python/tests/test_linalg.py @@ -2,7 +2,6 @@ import itertools import math -import unittest import mlx.core as mx import mlx_tests @@ -306,6 +305,35 @@ def test_cholesky(self): for M, L in zip(AB, Ls): self.assertTrue(mx.allclose(L @ L.T, M, rtol=1e-5, atol=1e-7)) + if mx.cuda.is_available(): + # The matrix above is singular, so its factor is undefined past the + # rank boundary and the GPU need not match the CPU there. Use + # positive definite inputs, sized to hit both cuSOLVER paths. + mx.random.seed(7) + for batch, n in [((), 3), ((2,), 2048), ((16,), 8)]: + x = mx.random.normal(batch + (n, n)) + A = x @ mx.swapaxes(x, -1, -2) + n * mx.eye(n) + for upper in [False, True]: + G = mx.linalg.cholesky(A, upper=upper, stream=mx.gpu) + C = mx.linalg.cholesky(A, upper=upper, stream=mx.cpu) + self.assertTrue(mx.allclose(G, C, rtol=1e-4, atol=1e-5)) + tri = mx.tril(G, k=-1) if upper else mx.triu(G, k=1) + self.assertTrue(mx.all(tri == 0)) + + # Empty and non contiguous inputs + self.assertEqual( + mx.linalg.cholesky(mx.zeros((0, 0)), stream=mx.gpu).shape, (0, 0) + ) + At = mx.swapaxes(A, -1, -2) + self.assertTrue( + mx.allclose( + mx.linalg.cholesky(At, stream=mx.gpu), + mx.linalg.cholesky(At, stream=mx.cpu), + rtol=1e-4, + atol=1e-5, + ) + ) + def test_pseudo_inverse(self): A = mx.array([[1, 2, 3], [6, -5, 4], [-9, 8, 7]], dtype=mx.float32) A_plus = mx.linalg.pinv(A, stream=mx.cpu) diff --git a/python/tests/test_load.py b/python/tests/test_load.py index f5947de471..d3c17fde78 100644 --- a/python/tests/test_load.py +++ b/python/tests/test_load.py @@ -65,7 +65,7 @@ def test_save_and_load(self): load_arr_mlx_npy = np.load(save_file_mlx) self.assertTrue(np.array_equal(load_arr_mlx_npy, save_arr_npy)) - save_file = os.path.join(self.test_dir, f"mlx_path.npy") + save_file = os.path.join(self.test_dir, "mlx_path.npy") save_arr = mx.ones((32,)) mx.save(Path(save_file), save_arr) @@ -99,6 +99,26 @@ def test_load_npy_read_error(self): with self.assertRaises(RuntimeError): mx.eval(out) + def test_load_npy_invalid_shape(self): + def write_npy(path, shape): + header = "{'descr': ' 0).item(), 3 + ) + expect(mx.unique(a, 2, return_counts=True)[1], [2, 2]) + + # the inverse has the shape of the input and indexes into the output, + # so values[inverse] rebuilds the input when nothing was truncated + values, inverse = mx.unique(b, 4, return_inverse=True) + expect(values, [1, 2, 3, 4]) + self.assertEqual(inverse.shape, b.shape) + expect(values[inverse], [[3, 1, 3], [2, 1, 4]]) + + # truncation clamps the inverse to keep it in range, so a dropped value + # comes back as the largest kept one instead of reading past the output + values, inverse = mx.unique(a, 2, return_inverse=True) + self.assertTrue(bool(mx.all(inverse < values.size))) + expect(values[inverse], [2, 1, 2, 2, 1]) + + # a size of zero leaves no index to clamp to, the only case where the + # reconstruction is not a valid array + for x in (a, mx.zeros((2, 3), mx.int32), mx.array(5)): + values, inverse = mx.unique(x, 0, return_inverse=True) + self.assertEqual(values.size, 0) + self.assertTrue(mx.array_equal(inverse, mx.zeros(x.shape, mx.uint32))) + with self.assertRaises(ValueError): + mx.eval(values[inverse]) + + # a 0-d input is flattened like any other + values, inverse = mx.unique(mx.array(5), 1, return_inverse=True) + expect(values, [5]) + self.assertEqual(inverse.shape, ()) + + # an empty input needs a fill value if size > 0 + e = mx.array([], mx.float32) + values, inverse, counts = mx.unique( + e, 0, return_inverse=True, return_counts=True + ) + self.assertEqual(values.dtype, mx.float32) + self.assertEqual((values.shape, inverse.shape, counts.shape), ((0,),) * 3) + with self.assertRaises(ValueError): + mx.unique(e, 3) + # the reconstruction stays valid even with size 0 + for size, want in ((0, []), (3, [7.0, 7.0, 7.0])): + values, inverse = mx.unique(e, size, return_inverse=True, fill_value=7) + expect(values, want) + rebuilt = values[inverse] + mx.eval(rebuilt) + self.assertEqual(rebuilt.shape, (0,)) + + # every element identical, and every element distinct + values, counts = mx.unique(mx.full((7,), 4, mx.int32), 7, return_counts=True) + expect(values, [4] * 7) + expect(counts, [7] + [0] * 6) + expect(mx.unique(mx.arange(6), 6), [0, 1, 2, 3, 4, 5]) + + # check 64 bit types work + for dtype in (mx.int64, mx.uint64, mx.complex64): + with self.subTest(dtype=dtype): + values, inverse, counts = mx.unique( + mx.array([3, 1, 2, 1], dtype), + 4, + return_inverse=True, + return_counts=True, + ) + self.assertEqual(values.dtype, dtype) + self.assertTrue(mx.array_equal(values, mx.array([1, 2, 3, 1], dtype))) + expect(inverse, [2, 0, 1, 0]) + expect(counts, [2, 1, 1, 0]) + # in particular the int64 numpy hands over by default + expect(mx.unique(mx.array(np.arange(5)), 5), [0, 1, 2, 3, 4]) + + # bool only works on the cpu stream, the metal sort has no bool kernel + values, inverse, counts = mx.unique( + mx.array([True, False, True]), + 2, + return_inverse=True, + return_counts=True, + stream=mx.cpu, + ) + expect(values, [False, True]) + expect(inverse, [1, 0, 1]) + expect(counts, [1, 2]) + + # NaN sorts last and never equals itself, so each one is kept, and none + # is ever picked as the default fill even though mx.min would return it + nan = float("nan") + values = mx.unique(mx.array([1.0, nan, 2.0, nan], mx.float32), 4) + expect(values[:2], [1.0, 2.0]) + self.assertTrue(bool(mx.all(mx.isnan(values[2:])))) + values = mx.unique(mx.array([3.0, 1.0, nan, 2.0], mx.float32), 6) + expect(values[:3], [1.0, 2.0, 3.0]) + self.assertTrue(bool(mx.isnan(values[3]))) + expect(values[4:], [1.0, 1.0]) + # with nothing but NaN there is no other element to fall back on, so + # the default fill is NaN as well + values = mx.unique(mx.array([nan, nan], mx.float32), 5) + self.assertTrue(bool(mx.all(mx.isnan(values)))) + + # the gradient credits the first occurrence of each unique value, and + # padding routes to that same element + for size, data, want in ( + (3, [3.0, 1.0, 2.0, 1.0], [1.0, 1.0, 1.0, 0.0]), + (4, [3.0, 1.0, 2.0, 1.0], [1.0, 2.0, 1.0, 0.0]), + (2, [1.0, 1.0, 2.0], [1.0, 0.0, 1.0]), + ): + with self.subTest(size=size, data=data): + grad = mx.grad(lambda x: mx.sum(mx.unique(x, size)))(mx.array(data)) + expect(grad, want) + + # the output shape does not depend on the values, so this composes with + # the function transforms + self.assertTrue( + mx.array_equal(mx.compile(lambda x: mx.unique(x, 3))(a), mx.unique(a, 3)) + ) + + # every optional output and a fill value have to survive compilation too + def all_outputs(x): + return mx.unique( + x, + 5, + return_index=True, + return_inverse=True, + return_counts=True, + fill_value=-1, + ) + + for got, want in zip(mx.compile(all_outputs)(a), all_outputs(a)): + self.assertTrue(mx.array_equal(got, want)) + self.assertEqual(got.dtype, want.dtype) + # the batch rows must have different unique sets, otherwise broadcasting + # one row over the batch would pass + rows = mx.array([[2, 1, 2, 3, 1], [7, 7, 5, 5, 9]]) + values, inverse, counts = mx.vmap( + lambda x: mx.unique(x, 3, return_inverse=True, return_counts=True) + )(rows) + expect(values, [[1, 2, 3], [5, 7, 9]]) + expect(inverse, [[1, 0, 1, 2, 0], [1, 1, 0, 0, 2]]) + expect(counts, [[2, 2, 1], [2, 2, 1]]) + + # compare against numpy on random inputs + rng = np.random.RandomState(0) + for n in (1, 2, 17, 1000, 5000): + with self.subTest(n=n): + a_np = rng.randint(-20, 20, size=n).astype(np.int32) + a_mx = mx.array(a_np) + v_np, i_np, c_np = np.unique( + a_np, return_inverse=True, return_counts=True + ) + values, inverse, counts = mx.unique( + a_mx, len(v_np), return_inverse=True, return_counts=True + ) + self.assertTrue(np.array_equal(np.array(values), v_np)) + self.assertTrue( + np.array_equal(np.array(inverse).reshape(-1), i_np.reshape(-1)) + ) + self.assertTrue(np.array_equal(np.array(counts), c_np)) + self.assertTrue(mx.array_equal(values[inverse], a_mx)) + # a padded output holds the same values up front + padded, pad_counts = mx.unique(a_mx, n, return_counts=True) + self.assertEqual(padded.shape, (n,)) + self.assertTrue(np.array_equal(np.array(padded)[: len(v_np)], v_np)) + self.assertEqual(mx.sum(pad_counts > 0).item(), len(v_np)) + + # non contiguous inputs are flattened over their logical elements, + # broadcast multiplicity included, not over their backing memory + base_np = rng.randint(0, 5, size=(4, 6)).astype(np.int32) + base = mx.array(base_np) + for v_mx, v_np in ( + (base.T, base_np.T), + (base[::2], base_np[::2]), + (base[::-1], base_np[::-1]), + (base[:, ::-1], base_np[:, ::-1]), + (mx.broadcast_to(base[0], (3, 6)), np.broadcast_to(base_np[0], (3, 6))), + ): + want = np.unique(v_np) + values, inverse = mx.unique(v_mx, len(want), return_inverse=True) + self.assertTrue(np.array_equal(np.array(values), want)) + # the inverse follows the shape of the view, not of its backing array + self.assertEqual(inverse.shape, v_mx.shape) + self.assertTrue(np.array_equal(np.array(values[inverse]), v_np)) + def test_large_binary(self): a = mx.ones([1000, 2147484], mx.int8) b = mx.ones([2147484], mx.int8) @@ -3216,6 +3720,14 @@ def test_flatten(self): self.assertEqual(x.flatten(start_axis=1).shape, (2, 3 * 4)) self.assertEqual(x.flatten(end_axis=1).shape, (2 * 3, 4)) + def test_reshape_col_contiguous(self): + # Reshape without a copy + a = mx.arange(12).reshape(3, 4).T.reshape(2, 2, 3) + b = mx.arange(12).reshape(3, 2, 2).T + a_np = np.arange(12).reshape(3, 4).T.reshape(2, 2, 3) + b_np = np.arange(12).reshape(3, 2, 2).T + self.assertTrue(np.array_equal(a + b, a_np + b_np)) + def test_clip(self): a = np.array([1, 4, 3, 8, 5], np.int32) expected = np.clip(a, 2, 6) @@ -3420,7 +3932,7 @@ def test_vecdot(self): with self.assertRaises(ValueError): mx.vecdot(mx.array(1), mx.array([1])) - with self.assertRaises(ValueError): + with self.assertRaises(IndexError): mx.vecdot(mx.array([1, 2]), mx.array([1, 2]), axis=1) with self.assertRaises(ValueError): mx.vecdot(mx.array([1, 2]), mx.array([1])) @@ -3773,6 +4285,11 @@ def test_bitwise_ops(self): self.assertEqual(c.shape, (3, 2, 5)) self.assertTrue(mx.array_equal(c, mx.ones((3, 2, 5), dtype=mx.bool_))) + x = mx.array([1, -1, 1, -1]) + y = mx.array([1, 1, -1, -1]) + out = (x > 0) ^ (y > 0) + self.assertEqual(out.tolist(), [False, True, True, False]) + def test_bitwise_grad(self): a = np.random.randint(0, 10, size=(4, 3)) b = np.random.randint(0, 10, size=(4, 3)) @@ -3839,6 +4356,26 @@ def test_view(self): a_out = out.view(mx.int32) self.assertTrue(mx.array_equal(a_out, a, equal_nan=True)) + # Size one last axis + a = mx.arange(4, dtype=mx.int32).reshape(1, 4).T + expected = np.arange(4, dtype=np.int32).reshape(4, 1).view(np.int16) + self.assertTrue(np.array_equal(a.view(mx.int16), expected)) + + # Byte offsets that are not a multiple of the new item size + a = mx.arange(64, dtype=mx.uint8) + a_np = np.arange(64, dtype=np.uint8) + for start in range(8): + out = a[start : start + 16].view(mx.int32) + expected = a_np[start : start + 16].view(np.int32) + self.assertTrue(np.array_equal(out + 0, expected)) # read in a kernel + + # View of an (n, 1) array + a = mx.arange(4, dtype=mx.int32).reshape(4, 1).view(mx.int16) + b = mx.arange(8, dtype=mx.int16).reshape(2, 4).T + expected = np.arange(4, dtype=np.int32).reshape(4, 1).view(np.int16) + expected = expected + np.arange(8, dtype=np.int16).reshape(2, 4).T + self.assertTrue(np.array_equal(a + b, expected)) + def _hadamard(self, N): # Matches scipy.linalg.hadamard H = np.array([[1]], dtype=np.int64) @@ -4069,6 +4606,23 @@ def test_dynamic_slicing(self): expected[1:, 2:, 3:] = update self.assertTrue(mx.array_equal(expected, out)) + # Strided, broadcast and reversed start indices + x = mx.arange(64).reshape(8, 8) + update = mx.zeros((2, 2), dtype=x.dtype) + starts = [ + (mx.array([1, 5, 2, 5])[::2], (1, 2)), + (mx.broadcast_to(mx.array([2]), (2,)), (2, 2)), + (mx.array([4, 1])[::-1], (1, 4)), + ] + for start, (i, j) in starts: + out = mx.slice(x, start, (0, 1), (2, 2)) + self.assertTrue(mx.array_equal(out, x[i : i + 2, j : j + 2])) + + out = mx.slice_update(x, update, start, (0, 1)) + expected = mx.arange(64).reshape(8, 8) + expected[i : i + 2, j : j + 2] = update + self.assertTrue(mx.array_equal(out, expected)) + def test_broadcast_arrays(self): a = mx.array(1) b = mx.array(1.0) @@ -4078,7 +4632,9 @@ def test_broadcast_arrays(self): self.assertEqual(b.shape, ()) self.assertEqual(b.dtype, mx.float32) - a, b = mx.broadcast_arrays(mx.zeros((3, 1, 2)), mx.zeros((4, 1))) + out = mx.broadcast_arrays(mx.zeros((3, 1, 2)), mx.zeros((4, 1))) + self.assertIsInstance(out, tuple) + a, b = out self.assertEqual(a.shape, (3, 4, 2)) self.assertEqual(b.shape, (3, 4, 2)) @@ -4116,6 +4672,16 @@ def test_complex_ops(self): mx_op = getattr(mx, op) self.assertTrue(np.allclose(mx_op(x), np_op(x))) + if mx.metal.is_available() and mx.default_device() == mx.gpu: + x = mx.array( + [1e20 + 1e20j, 2.5e-20 - 3e-20j, 3e38 + 0j, 1e-19j], mx.complex64 + ) + for op in ["abs", "log"]: + with self.subTest(op=op): + np_op = getattr(np, op) + mx_op = getattr(mx, op) + self.assertTrue(np.allclose(mx_op(x), np_op(x), rtol=1e-5)) + x = mx.array( [ 3.0 + 4.0j, @@ -4165,6 +4731,14 @@ def test_integer_power(self): x = mx.power(mx.array([2, -2, 1], dtype), mx.array([-1, -3, -9], dtype)) self.assertEqual(x.tolist(), [0, 0, 0]) + # A single negative exponent must only zero its own element, not the + # whole SIMD vector. Use enough elements to span a vector lane. + with mx.stream(mx.cpu): + base = mx.array([2] * 16, mx.int32) + exp = mx.array([3] * 3 + [-1] + [3] * 12, mx.int32) + expected = [8] * 3 + [0] + [8] * 12 + self.assertEqual(mx.power(base, exp).tolist(), expected) + def test_depends(self): a = mx.array([1.0, 2.0, 3.0]) b = mx.exp(a) @@ -4239,6 +4813,12 @@ def test_masked_scatter(self): ) ) + # source with a negative stride + a = mx.zeros((4,)) + mask = mx.array([True, False, True, True]) + a[mask] = mx.array([1.0, 2.0, 3.0, 4.0])[::-1] + self.assertTrue(mx.array_equal(a, mx.array([4.0, 0.0, 3.0, 2.0]))) + def test_broadcast_shapes(self): # Basic broadcasting self.assertEqual(mx.broadcast_shapes((1, 2, 3), (3,)), (1, 2, 3)) @@ -4277,6 +4857,28 @@ def test_broadcast_shapes(self): with self.assertRaises(ValueError): mx.broadcast_shapes() + def test_sort_transposed(self): + # The sorted axis can keep the smallest or largest stride while the + # axes that are not sorted are no longer a row major block, which is + # what the contiguous kernel's row enumeration assumes. + np.random.seed(0) + for shape in [(3, 4, 8), (2, 1, 6), (2, 3, 4, 2), (2, 1, 3, 4)]: + a_np = np.random.uniform(0, 100, size=shape).astype(np.float32) + a_mx = mx.array(a_np) + for perm in permutations(range(len(shape))): + b_np = np.transpose(a_np, perm) + b_mx = mx.transpose(a_mx, perm) + for axis in range(len(shape)): + with self.subTest(shape=shape, perm=perm, axis=axis): + s_np = np.sort(b_np, axis=axis) + self.assertTrue(np.array_equal(s_np, mx.sort(b_mx, axis=axis))) + idx = np.array(mx.argsort(b_mx, axis=axis)) + self.assertTrue( + np.array_equal( + s_np, np.take_along_axis(b_np, idx, axis=axis) + ) + ) + def test_sort_nan(self): for dtype in [mx.float32, mx.float16, mx.bfloat16]: with self.subTest(dtype=dtype): @@ -4288,6 +4890,11 @@ def test_sort_nan(self): expected = mx.array([0.0 + 1j, 2.0 + 1j, 3.0 + 1j, mx.nan + 2j]) self.assertTrue(mx.array_equal(mx.sort(x), expected, equal_nan=True)) + # A NaN in the imaginary part also sorts last. + x = mx.array([3.0 + 1j, complex(1.0, mx.nan), 2.0 + 1j, 0.0 + 1j]) + expected = mx.array([0.0 + 1j, 2.0 + 1j, 3.0 + 1j, complex(1.0, mx.nan)]) + self.assertTrue(mx.array_equal(mx.sort(x), expected, equal_nan=True)) + def test_argsort_nan(self): for dtype in [mx.float32, mx.float16, mx.bfloat16]: with self.subTest(dtype=dtype): @@ -4297,6 +4904,13 @@ def test_argsort_nan(self): sorted_x = mx.take(x, indices) self.assertTrue(mx.array_equal(sorted_x, expected, equal_nan=True)) + # Also test complex values + for nan_val in [mx.nan + 2j, complex(1.0, mx.nan)]: + x = mx.array([3.0 + 1j, nan_val, 2.0 + 1j, 0.0 + 1j]) + expected = mx.array([0.0 + 1j, 2.0 + 1j, 3.0 + 1j, nan_val]) + sorted_x = mx.take(x, mx.argsort(x)) + self.assertTrue(mx.array_equal(sorted_x, expected, equal_nan=True)) + def test_to_from_fp8(self): vals = mx.array( [448, 256, 192, 128, 96, 64, 48, 32, 24, 16, 12, 8, 6, 4, 3, 2, 0.015625] @@ -4304,6 +4918,17 @@ def test_to_from_fp8(self): self.assertTrue(mx.array_equal(mx.from_fp8(mx.to_fp8(vals)), vals)) self.assertTrue(mx.array_equal(mx.from_fp8(mx.to_fp8(-vals)), -vals)) + # 0x7f and 0xff are NaN in E4M3FN. Arithmetic does not keep the sign of + # a NaN, so only test for NaN. Use float32, numpy has no bfloat16. + nan_encodings = mx.array([0x7F, 0xFF], dtype=mx.uint8) + decoded_np = np.array(mx.from_fp8(nan_encodings, mx.float32)) + self.assertTrue(np.isnan(decoded_np[0]).item()) + self.assertTrue(np.isnan(decoded_np[1]).item()) + + # The carry must not fire one byte early: 0x7e/0xfe stay finite + finite = mx.from_fp8(mx.array([0x7E, 0xFE], dtype=mx.uint8), mx.float32) + self.assertTrue(mx.array_equal(finite, mx.array([448.0, -448.0]))) + def test_zeros_ones_empty_like_dtype(self): x = mx.array([1, 2, 3], dtype=mx.int32) diff --git a/python/tests/test_optimizers.py b/python/tests/test_optimizers.py index 3d51fedf32..94a1809b05 100644 --- a/python/tests/test_optimizers.py +++ b/python/tests/test_optimizers.py @@ -15,10 +15,10 @@ try: import torch - import torch.nn.functional as F + import torch.nn.functional as F # noqa: F401 has_torch = True -except ImportError as e: +except ImportError: has_torch = False @@ -132,7 +132,7 @@ def test_adagrad(self): "first": [mx.zeros((10,)), mx.zeros((1,))], "second": mx.zeros((1,)), } - grads = tree_map(lambda x: mx.ones_like(x), params) + _grads = tree_map(lambda x: mx.ones_like(x), params) # Explicit init optim = opt.Adagrad(learning_rate=1e-2) @@ -150,7 +150,7 @@ def test_adadelta(self): "first": [mx.zeros((10,)), mx.zeros((1,))], "second": mx.zeros((1,)), } - grads = tree_map(lambda x: mx.ones_like(x), params) + _grads = tree_map(lambda x: mx.ones_like(x), params) # Explicit init optim = opt.AdaDelta(learning_rate=1e-2) @@ -263,7 +263,7 @@ def test_lion(self): "first": [mx.zeros((10,)), mx.zeros((1,))], "second": mx.zeros((1,)), } - grads = tree_map(lambda x: mx.ones_like(x), params) + _grads = tree_map(lambda x: mx.ones_like(x), params) # Explicit init optim = opt.Lion(learning_rate=1e-2) @@ -364,6 +364,29 @@ def test_muon(self): optim_no_momentum = opt.Muon(learning_rate=1e-2, momentum=0.0) optim_no_momentum.apply_gradients(grads, params) + def test_weight_decay_keeps_inputs_unchanged(self): + # Weight decay must not write into the gradients or the parameters + # that the caller passed in. + params = {"w": mx.ones((3, 3))} + grads = {"w": mx.full((3, 3), 2.0)} + + optimizer = opt.SGD(learning_rate=1e-2, weight_decay=0.1) + optimizer.apply_gradients(grads, params) + self.assertTrue(mx.array_equal(grads["w"], mx.full((3, 3), 2.0))) + self.assertTrue(mx.array_equal(params["w"], mx.ones((3, 3)))) + + optimizer = opt.Adafactor(learning_rate=1e-2, weight_decay=0.1) + optimizer.apply_gradients(grads, params) + self.assertTrue(mx.array_equal(grads["w"], mx.full((3, 3), 2.0))) + self.assertTrue(mx.array_equal(params["w"], mx.ones((3, 3)))) + + # The same gradients applied twice give the same update + optimizer = opt.SGD(learning_rate=1e-2, weight_decay=0.1) + first = optimizer.apply_gradients(grads, params) + optimizer = opt.SGD(learning_rate=1e-2, weight_decay=0.1) + second = optimizer.apply_gradients(grads, params) + self.assertTrue(mx.array_equal(first["w"], second["w"])) + def test_compiled_optimizer(self): model = nn.Linear(10, 10) x = mx.random.uniform(shape=(2, 10)) @@ -383,7 +406,7 @@ def step(x): uncompiled_params = model.parameters() # Pure version - def loss(params, x): + def loss(params, x): # noqa: F811 model.update(params) return model(x).sum() @@ -403,7 +426,7 @@ def step(params, opt_state, x): self.assertTrue(mx.allclose(pure_params["bias"], uncompiled_params["bias"])) # Impure version - def loss(model, x): + def loss(model, x): # noqa: F811 return model(x).sum() model.update(orig_params) @@ -565,6 +588,57 @@ def test_clip_grad_norm(self): with self.assertRaises(ValueError): opt.clip_grad_norm(small_grads, -1.0) + def test_clip_grad_norm_float16(self): + grads = { + "first": [mx.full((100,), 30.0, dtype=mx.float16)], + "second": mx.array([400.0], dtype=mx.float16), + } + for clip in (opt.clip_grad_norm, mx.compile(opt.clip_grad_norm)): + for max_norm, first, second in ( + (1.0, 0.06, 0.8), + (1e-5, 6e-7, 8e-6), + (0.0, 0.0, 0.0), + (1000.0, 30.0, 400.0), + ): + with self.subTest(clip=clip, max_norm=max_norm): + clipped, total_norm = clip(grads, max_norm) + self.assertEqual(total_norm.dtype, mx.float32) + self.assertAlmostEqual(total_norm.item(), 500.0, places=3) + for actual, expected in ( + (clipped["first"][0], first), + (clipped["second"], second), + ): + self.assertEqual(actual.dtype, mx.float16) + self.assertTrue( + mx.allclose( + actual, mx.array(expected), rtol=1e-3, atol=1e-7 + ) + ) + self.assertTrue(mx.array_equal(grads["first"][0], mx.full((100,), 30.0))) + self.assertTrue(mx.array_equal(grads["second"], mx.array([400.0]))) + + grads = {"w": mx.full((16,), 30000.0, dtype=mx.float16)} + clipped, total_norm = opt.clip_grad_norm(grads, max_norm=1.0) + self.assertAlmostEqual(total_norm.item(), 120000.0, delta=0.1) + self.assertTrue(mx.array_equal(clipped["w"], mx.full((16,), 0.25))) + + def test_clip_grad_norm_mixed_dtypes(self): + grads = { + "first": mx.array([300.0], dtype=mx.float16), + "second": [ + mx.array([400.0], dtype=mx.bfloat16), + mx.array([0.0], dtype=mx.float32), + ], + } + clipped, total_norm = opt.clip_grad_norm(grads, max_norm=1.0) + self.assertTrue(mx.isfinite(total_norm)) + self.assertAlmostEqual(total_norm.item(), 500.0, delta=1.0) + for (_, g), (_, c), expected in zip( + tree_flatten(grads), tree_flatten(clipped), (0.6, 0.8, 0.0) + ): + self.assertEqual(c.dtype, g.dtype) + self.assertTrue(mx.allclose(c, mx.array(expected), rtol=1e-2, atol=1e-7)) + def test_init_from_state(self): class Model(nn.Module): def __init__(self): @@ -634,6 +708,33 @@ def test_multi_optimizer_with_parameterless_layers(self): self.assertFalse(mx.array_equal(w, model.layers[0].weight)) self.assertFalse(mx.array_equal(b, model.layers[0].bias)) + def test_multi_optimizer_with_empty_group(self): + mx.random.seed(0) + # no biases so all the weights are 2D + model = nn.Sequential( + nn.Linear(4, 4, bias=False), nn.ReLU(), nn.Linear(4, 4, bias=False) + ) + mx.eval(model.parameters()) + + loss_and_grad = nn.value_and_grad(model, lambda m, x: m(x).sum()) + _, grads = loss_and_grad(model, mx.ones((1, 4))) + expected = opt.Adam(learning_rate=0.01).apply_gradients(grads, model) + + # SGD gets no weights, first as the fallback and then as the first optimizer + optimizers = [ + opt.MultiOptimizer( + [opt.Adam(learning_rate=0.01), opt.SGD(learning_rate=0.01)], + [lambda _, w: w.ndim >= 2], + ), + opt.MultiOptimizer( + [opt.SGD(learning_rate=0.01), opt.Adam(learning_rate=0.01)], + [lambda _, w: w.ndim < 2], + ), + ] + for optimizer in optimizers: + new_params = optimizer.apply_gradients(grads, model) + self.assertTrue(tree_equal(mx.array_equal, expected, new_params)) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index d860196acf..289d29c015 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -23,7 +23,9 @@ class TestQuantized(mlx_tests.MLXTestCase): def test_quantize_dequantize(self): w = mx.random.normal(shape=(128, 512)) for gs in [32, 64, 128]: - for b in [2, 3, 5, 6, 4, 8]: + for b in [1, 2, 3, 5, 6, 4, 8]: + if b == 1 and mx.cuda.is_available(): + continue with self.subTest(gs=gs, b=b): w_q, scales, biases = mx.quantize(w, group_size=gs, bits=b) w_hat = mx.dequantize(w_q, scales, biases, gs, b) @@ -34,7 +36,9 @@ def test_quantize_dequantize(self): # test quantize/dequantize 0s a = mx.zeros((256, 512)) for gs in [32, 64, 128]: - for b in [2, 3, 4, 5, 6, 8]: + for b in [1, 2, 3, 4, 5, 6, 8]: + if b == 1 and mx.cuda.is_available(): + continue w_q, scales, biases = mx.quantize(a, gs, b) a_hat = mx.dequantize(w_q, scales, biases, gs, b) self.assertTrue(mx.all(a_hat == 0)) @@ -224,6 +228,98 @@ def test_nvfp4_quantize_dequantize(self): ) self.assertTrue(mx.allclose(w, w_hat, rtol=1e-5, atol=1e-5)) + @unittest.skipIf(mx.cuda.is_available(), "1-bit quantization NYI on CUDA") + def test_1bit_quantize_dequantize(self): + """Test 1-bit affine quantization.""" + + # Symmetric binary weights {-0.5, +0.5} should round-trip perfectly + # (affine formula gives scale=1.0, bias=-0.5) + for gs in [32, 64, 128]: + with self.subTest(gs=gs, case="pack_symmetric_weights"): + signs = (mx.random.uniform(shape=(128, 512)) > 0.5).astype(mx.float32) + w = signs * 1.0 - (1 - signs) * 1.0 # {-1.0, +1.0} + w = w * 0.5 # {-0.5, +0.5} + + w_q, scales, biases = mx.quantize(w, group_size=gs, bits=1) + w_hat = mx.dequantize(w_q, scales, biases, gs, 1) + + self.assertLess((w - w_hat).abs().max().item(), 1e-5) + + # Asymmetric binary weights {0.1, 0.9} should round-trip perfectly + # (affine formula gives scale=0.8, bias=0.1) + for gs in [32, 64, 128]: + with self.subTest(gs=gs, case="pack_asymmetric_weights"): + bits = (mx.random.uniform(shape=(128, 512)) > 0.5).astype(mx.float32) + w = bits * 0.9 + (1 - bits) * 0.1 # {0.1, 0.9} + + w_q, scales, biases = mx.quantize(w, group_size=gs, bits=1) + w_hat = mx.dequantize(w_q, scales, biases, gs, 1) + + self.assertLess((w - w_hat).abs().max().item(), 1e-5) + + # Verify dequantized values are exactly {bias, bias + scale} + w = mx.random.normal(shape=(64, 256)) + for gs in [32, 64, 128]: + with self.subTest(gs=gs, case="dequant_values"): + w_q, scales, biases = mx.quantize(w, group_size=gs, bits=1) + w_hat = mx.dequantize(w_q, scales, biases, gs, 1) + + for i in range(scales.shape[0]): + for j in range(scales.shape[1]): + s = scales[i, j].item() + b = biases[i, j].item() + row_start = j * gs + row_end = row_start + gs + vals = w_hat[i, row_start:row_end] + mx.eval(vals) + for v in vals.tolist(): + self.assertTrue( + abs(v - b) < 1e-5 or abs(v - (b + s)) < 1e-5, + f"Value {v} not in {{bias={b}, bias+scale={b + s}}}", + ) + + # 1-bit quantize/dequantize zeros — scale floors to eps, bias=0 + a = mx.zeros((256, 512)) + for gs in [32, 64, 128]: + w_q, scales, biases = mx.quantize(a, gs, 1) + a_hat = mx.dequantize(w_q, scales, biases, gs, 1) + self.assertLess(a_hat.abs().max().item(), 1e-5) + + # Quantized matmul with symmetric binary weights + key = mx.random.key(42) + k1, k2 = mx.random.split(key) + for gs in [32, 64, 128]: + with self.subTest(gs=gs, case="quantized_matmul_symmetric"): + x = mx.random.normal(shape=(4, 256), key=k1) + signs = (mx.random.uniform(shape=(128, 256), key=k2) > 0.5).astype( + mx.float32 + ) + w = signs * 0.3 - (1 - signs) * 0.3 # {-0.3, +0.3} + + w_q, scales, biases = mx.quantize(w, gs, 1) + w_hat = mx.dequantize(w_q, scales, biases, gs, 1) + y_q = mx.quantized_matmul(x, w_q, scales, biases, True, gs, 1) + y_hat = x @ w_hat.T + self.assertEqual(y_q.shape, y_hat.shape) + self.assertLess((y_q - y_hat).abs().max().item(), 1e-5) + + # Quantized matmul with asymmetric binary weights + for gs in [32, 64, 128]: + with self.subTest(gs=gs, case="quantized_matmul_asymmetric"): + x = mx.random.normal(shape=(4, 256), key=k1) + bits = (mx.random.uniform(shape=(128, 256), key=k2) > 0.5).astype( + mx.float32 + ) + w = bits * 0.7 + (1 - bits) * 0.1 # {0.1, 0.7} + + w_q, scales, biases = mx.quantize(w, gs, 1) + w_hat = mx.dequantize(w_q, scales, biases, gs, 1) + y_q = mx.quantized_matmul(x, w_q, scales, biases, True, gs, 1) + y_hat = x @ w_hat.T + self.assertEqual(y_q.shape, y_hat.shape) + tol = 2e-5 if platform.system() == "Windows" else 1e-5 + self.assertLess((y_q - y_hat).abs().max().item(), tol) + def test_qqmv(self): key = mx.random.key(0) k1, k2 = mx.random.split(key) @@ -276,6 +372,7 @@ def test_qqmm(self): self.skipTest("Not implemented for CPU") return + tol = 5e-2 if mx.cuda.is_available() else 1e-3 key = mx.random.key(0) k1, k2 = mx.random.split(key) tests = product( @@ -318,7 +415,65 @@ def test_qqmm(self): ) y_hat = x_hat @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) + + @unittest.skipIf( + not mx.metal.is_available(), "Global scale is only supported on Metal backend" + ) + def test_qqmm_global_scale_matrix_kernels(self): + mx.random.seed(0) + dtype = mx.bfloat16 + for M, N, K in product( + [32, 64], + [128, 130], + [96, 128], + ): + with self.subTest(shape=(M, N, K)): + x = mx.random.normal((M, K)).astype(dtype) + w = mx.random.normal((N, K)).astype(dtype) + global_scale_x = mx.max(mx.abs(x)).astype(mx.float32) + global_scale_w = mx.max(mx.abs(w)).astype(mx.float32) + x_hat = mx.dequantize( + *mx.quantize(x, mode="nvfp4", global_scale=global_scale_x), + mode="nvfp4", + dtype=dtype, + global_scale=global_scale_x, + ) + w_q, scales = mx.quantize(w, mode="nvfp4", global_scale=global_scale_w) + w_hat = mx.dequantize( + w_q, + scales, + mode="nvfp4", + dtype=dtype, + global_scale=global_scale_w, + ) + + expected = x_hat @ mx.swapaxes(w_hat, -1, -2) + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.qqmm( + x, + w_q, + scales, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + continue + actual = mx.qqmm( + x, + w_q, + scales, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + delta = mx.abs(actual.astype(mx.float32) - expected.astype(mx.float32)) + relative_error = delta.max() / mx.maximum( + mx.abs(expected.astype(mx.float32)).max(), 1e-20 + ) + self.assertLess(relative_error, 3e-2) def test_qmm(self): key = mx.random.key(0) @@ -326,13 +481,15 @@ def test_qmm(self): dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 tests = product( [128, 64, 32], # group_size - [2, 4, 8], # bits + [1, 2, 4, 8], # bits [8, 32, 33, 64], # M [128, 256], # N [128, 256], # K [True, False], # transposed ) for group_size, bits, M, N, K, transposed in tests: + if bits == 1 and mx.cuda.is_available(): + continue with self.subTest( shape=(M, N, K), group_size=group_size, @@ -512,6 +669,167 @@ def test_qmm_small_m_block(self): ) self.assertLess((y_ref - y).abs().max(), 1e-3) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmm_splitk_precision(self): + # Split-K sums the partitions in float32 and rounds the result to the + # input type once. Rounding each partition first gives two to three + # times the error of a single rounding at these shapes. + if mx.default_device() == mx.cpu: + self.skipTest("Covers GPU kernels only") + K, N = 2560, 1024 + # Keep M at or above get_qmv_batch_limit on all devices. Below it the + # qmv kernel runs, which dequantizes in float32 and not in the input type. + for mode, dtype, M in product( + ["affine", "mxfp4"], [mx.bfloat16, mx.float16], [25, 33, 65] + ): + with self.subTest(mode=mode, dtype=dtype, M=M): + k1, k2 = mx.random.split(mx.random.key(0)) + x = mx.random.normal((M, K), key=k1).astype(dtype) + w = (0.02 * mx.random.normal((N, K), key=k2)).astype(dtype) + group_size, bits = (64, 4) if mode == "affine" else (None, None) + wq = mx.quantize(w, group_size=group_size, bits=bits, mode=mode) + w_hat = mx.dequantize(*wq, group_size=group_size, bits=bits, mode=mode) + y_ref = x.astype(mx.float32) @ w_hat.astype(mx.float32).T + y = mx.quantized_matmul( + x, *wq, transpose=True, group_size=group_size, bits=bits, mode=mode + ) + error = (y.astype(mx.float32) - y_ref).abs().mean() + rounding = (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() + self.assertLess(error.item(), 1.1 * rounding.item()) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmm_mid_m(self): + # Mid-size M with narrow outputs, where a single batch routes to the + # split-K and vector kernels: every split count, both row tilings and + # the boundaries between the routes. + if mx.default_device() == mx.cpu: + self.skipTest("Covers GPU kernels only") + shapes = [ + (256, 4096), + (1024, 6144), + (2560, 1024), + (4096, 2048), + ] + for (K, N), M, bits, group_size, dtype in product( + shapes, + [8, 31, 33, 130], + [2, 3, 4, 6, 8], + [32, 64, 128], + [mx.bfloat16, mx.float16, mx.float32], + ): + if K % group_size != 0: + continue + with self.subTest( + K=K, N=N, M=M, bits=bits, group_size=group_size, dtype=dtype + ): + k1, k2 = mx.random.split(mx.random.key(M * K + N)) + x = mx.random.normal((M, K), key=k1).astype(dtype) + w = (0.02 * mx.random.normal((N, K), key=k2)).astype(dtype) + wq = mx.quantize(w, group_size=group_size, bits=bits) + w_hat = mx.dequantize(*wq, group_size=group_size, bits=bits) + y_ref = x.astype(mx.float32) @ w_hat.astype(mx.float32).T + y = mx.quantized_matmul( + x, *wq, transpose=True, group_size=group_size, bits=bits + ) + self.assertEqual(y.shape, (M, N)) + error = (y.astype(mx.float32) - y_ref).abs().mean() + if dtype == mx.float32: + rounding = mx.array(1) + else: + rounding = ( + (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() + ) + # The split-K and NAX routes round once. The vector kernels + # (below 16384 outputs, or when K does not split in two) reach + # ~1.6x the output rounding. + splits = K % (2 * max(64, group_size)) == 0 + tol = 1.1 if M * N >= 16384 and splits else 2.0 + if error.item() >= tol * rounding.item(): + # Vector kernels can dequantize weights in float32. + qw, scales, biases = wq + w_hat = mx.dequantize( + qw, + scales.astype(mx.float32), + biases.astype(mx.float32), + group_size=group_size, + bits=bits, + ) + y_ref = mx.matmul(x.astype(mx.float32), w_hat.T, stream=mx.cpu) + error = (y.astype(mx.float32) - y_ref).abs().mean() + rounding = ( + (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() + ) + tol = 1.1 + self.assertLess(error.item(), tol * rounding.item()) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmm_fp4_half_loader(self): + if mx.default_device() == mx.cpu: + self.skipTest("Covers GPU kernels only") + mx.random.seed(0) + + def rel_err(got, expected): + d = mx.abs(got.astype(mx.float32) - expected.astype(mx.float32)) + return d.max() / mx.abs(expected.astype(mx.float32)).max() + + tests = [ + (512, 8192, 1040, ()), # 64 x 64 + (552, 8224, 1040, ()), # 64 x 64, M % 64 == 40, N % 64 == 32 + (300, 8192, 1040, (2,)), # 64 x 64, batched w + (40, 1040, 1200, ()), # 32 x 32, N % 32 == 16 + (40, 512, 1024, ()), # split K + (40, 528, 1024, ()), # split K, N % 32 == 16 + ] + modes = [("nvfp4", 16), ("mxfp4", 32)] + dtypes = [mx.bfloat16, mx.float16] + for (M, N, K, batch), (mode, group_size), dtype in product( + tests, modes, dtypes + ): + K -= K % group_size + with self.subTest(M=M, N=N, K=K, batch=batch, mode=mode, dtype=dtype): + w = mx.random.normal(batch + (N, K)).astype(dtype) + w_q, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(w_q, scales, mode=mode, dtype=dtype) + x = (mx.random.normal(batch + (M, K)) / K**0.5).astype(dtype) + out = mx.quantized_matmul(x, w_q, scales, mode=mode) + self.assertLess(rel_err(out, x @ w_hat.swapaxes(-1, -2)), 3e-2) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmm_few_rows(self): + if mx.default_device() == mx.cpu: + self.skipTest("Covers GPU kernels only") + mx.random.seed(0) + K = 4224 + + def rel_err(got, expected): + d = mx.abs(got.astype(mx.float32) - expected.astype(mx.float32)) + return d.max() / mx.abs(expected.astype(mx.float32)).max() + + modes = ["nvfp4", "mxfp4", "mxfp8"] + dtypes = [mx.bfloat16, mx.float16, mx.float32] + for N, mode, dtype in product([4128, 4112], modes, dtypes): + tol = 1e-5 if dtype == mx.float32 else 3e-2 + w = mx.random.normal((N, K)).astype(dtype) + w_q, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(w_q, scales, mode=mode, dtype=dtype) + for M in [5, 6, 8, 13, 16, 17]: + with self.subTest(N=N, mode=mode, dtype=dtype, M=M): + x = (mx.random.normal((M, K)) / K**0.5).astype(dtype) + out = mx.quantized_matmul(x, w_q, scales, mode=mode) + self.assertLess(rel_err(out, x @ w_hat.T), tol) + + # Views at odd offsets must not reach the Metal vector loads + x = (mx.random.normal((16 * K + 1,)) / K**0.5).astype(dtype) + s = mx.concatenate([mx.zeros((1,), mx.uint8), scales.reshape(-1)]) + views = { + "x": (x[1:].reshape(16, K), scales), + "scales": (x[:-1].reshape(16, K), s[1:].reshape(scales.shape)), + } + for name, (xv, sv) in views.items(): + with self.subTest(N=N, mode=mode, dtype=dtype, offset=name): + out = mx.quantized_matmul(xv, w_q, sv, mode=mode) + self.assertLess(rel_err(out, xv @ w_hat.T), tol) + def test_qmm_vjp(self): key = mx.random.key(0) k1, k2 = mx.random.split(key) @@ -580,12 +898,13 @@ def test_qmm_shapes(self): w = mx.random.normal(shape=(32, 256), key=k2) w_q, scales, biases = mx.quantize(w, group_size, bits) w_hat = mx.dequantize(w_q, scales, biases, group_size, bits) + tol = 2e-2 if mx.cuda.is_available() else 1e-3 for s in [(3, 256), (2, 1, 7, 256)]: x = mx.random.normal(shape=s, key=k1) y_q = mx.quantized_matmul(x, w_q, scales, biases, True, group_size, bits) y_hat = x @ w_hat.T self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) w = mx.random.normal(shape=(256, 256), key=k2) w_q, scales, biases = mx.quantize(w, group_size, bits) @@ -595,7 +914,7 @@ def test_qmm_shapes(self): y_q = mx.quantized_matmul(x, w_q, scales, biases, False, group_size, bits) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) def test_qmv(self): key = mx.random.key(0) @@ -624,9 +943,168 @@ def test_qmv(self): self.assertEqual(y_q.shape, y_hat.shape) self.assertLess((y_q - y_hat).abs().max(), 1e-3) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmv_affine_bias_sum_precision(self): + # The bias contributes bias * sum(x), and a sum accumulated in the input + # type loses the small values: the sum of [1, 1 / denom, -1, 0] cancels + # to zero. + for n, k, gs, dtype, sign, bits in product( + [1, 4, 8, 12], + [64, 96, 512], + [32, 64], + [mx.bfloat16, mx.float16], + [-1, 1], + [2, 3, 4, 5, 6, 8], + ): + if k % gs: + continue + with self.subTest(n=n, k=k, gs=gs, dtype=dtype, sign=sign, bits=bits): + # 1 / denom is exactly half an ulp at 1.0, so 1 + 1 / denom + # rounds back to 1 (ties-to-even) in the input type. + denom = 2048 if dtype == mx.float16 else 256 + x = mx.tile(mx.array([1, 1 / denom, -1, 0], dtype), k // 4) + x = (sign * x).reshape(1, k) + # Zero scales and unit biases dequantize to all ones, so the + # product is exactly sum(x) = sign * k / (4 * denom). + q = mx.zeros((n, k * bits // 32), mx.uint32) + scales = mx.zeros((n, k // gs), dtype) + biases = mx.ones((n, k // gs), dtype) + y = mx.quantized_matmul(x, q, scales, biases, group_size=gs, bits=bits) + expected = mx.full((1, n), sign * k / (4 * denom), dtype) + self.assertTrue(mx.array_equal(y, expected).item()) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmv_fast_unaligned_n(self): + # Output sizes that are not a multiple of 8 with an aligned input size. + # "vector" is one input row, "batched" two weight batches, and "rows" + # is M = 3, which reaches this kernel only on GPUs before gen 15, since + # later ones route M >= 2 to qmv_wide. + for n, k, bits, gs, dtype, layout in product( + [1, 3, 5, 12, 17], + [512, 1024], + [2, 3, 4, 5, 6, 8], + [64], + [mx.float32, mx.bfloat16], + ["vector", "batched", "rows"], + ): + with self.subTest(n=n, k=k, bits=bits, gs=gs, dtype=dtype, layout=layout): + key = mx.random.key(n * 7 + k + bits) + if layout == "batched": + w_shape, x_shape = (2, n, k), (2, 1, k) + elif layout == "rows": + w_shape, x_shape = (n, k), (3, k) + else: + w_shape, x_shape = (n, k), (1, k) + w = mx.random.normal(w_shape, key=key) / k**0.5 + x = mx.random.normal(x_shape, key=mx.random.split(key)[0]) + x = (x / k**0.5).astype(dtype) + q, s, b = mx.quantize(w.astype(dtype), group_size=gs, bits=bits) + w_hat = mx.dequantize(q, s, b, group_size=gs, bits=bits) + y_hat = x.astype(mx.float32) @ mx.swapaxes( + w_hat.astype(mx.float32), -1, -2 + ) + y = mx.quantized_matmul(x, q, s, b, group_size=gs, bits=bits) + tol = 1e-3 if dtype == mx.float32 else 1.5e-3 + self.assertEqual(y.shape, y_hat.shape) + self.assertLess((y - y_hat).abs().max().item(), tol) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_fp_qmv_fast_unaligned_n(self): + for n, k, mode, dtype, batched in product( + [1, 3, 5, 7, 8, 9, 12, 17], + [256, 512, 544, 1024], + ["mxfp4", "mxfp8", "nvfp4"], + [mx.float32, mx.float16, mx.bfloat16], + [False, True], + ): + with self.subTest(n=n, k=k, mode=mode, dtype=dtype, batched=batched): + key = mx.random.key(n * 7 + k) + w_shape = (2, n, k) if batched else (n, k) + x_shape = (2, 1, k) if batched else (1, k) + w = mx.random.normal(w_shape, key=key) / k**0.5 + x = mx.random.normal(x_shape, key=mx.random.split(key)[0]) + x = (x / k**0.5).astype(dtype) + q, s = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(q, s, mode=mode, dtype=mx.float32) + expected = x.astype(mx.float32) @ mx.swapaxes(w_hat, -1, -2) + actual = mx.quantized_matmul(x, q, s, mode=mode) + self.assertEqual(actual.shape, expected.shape) + self.assertLess((actual - expected).abs().max().item(), 1e-3) + + # Compare aligned inputs with the existing full-tile kernel. + alignment = 256 if mode == "mxfp8" else 512 + if k % alignment == 0: + padding = [(0, 0)] * q.ndim + padding[-2] = (0, (-n) % 8) + padded = mx.quantized_matmul( + x, mx.pad(q, padding), mx.pad(s, padding), mode=mode + ) + self.assertTrue(mx.array_equal(actual, padded[..., :n]).item()) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_fp_qmv_fast_unaligned_n_global_scale(self): + for n, k, m, dtype in product( + [1, 3, 5, 7, 8, 9, 12, 17], + [512, 544, 1024], + [1, 3], + [mx.float32, mx.float16, mx.bfloat16], + ): + with self.subTest(n=n, k=k, m=m, dtype=dtype): + key = mx.random.key(n * 7 + k) + w = mx.random.normal((n, k), key=key) / k**0.5 + x = mx.random.normal((m, k), key=mx.random.split(key)[0]) + x = (x / k**0.5).astype(dtype) + global_scale_x = mx.max(mx.abs(x)).astype(mx.float32) + global_scale_w = mx.max(mx.abs(w)).astype(mx.float32) + q, s = mx.quantize(w, mode="nvfp4", global_scale=global_scale_w) + w_hat = mx.dequantize( + q, s, mode="nvfp4", global_scale=global_scale_w, dtype=mx.float32 + ) + x_hat = mx.dequantize( + *mx.quantize(x, mode="nvfp4", global_scale=global_scale_x), + mode="nvfp4", + global_scale=global_scale_x, + dtype=dtype, + ) + expected = x_hat.astype(mx.float32) @ w_hat.T + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.qqmm( + x, + q, + s, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + continue + actual = mx.qqmm( + x, + q, + s, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + self.assertEqual(actual.shape, expected.shape) + self.assertLess((actual - expected).abs().max().item(), 1e-3) + + if k % 512 == 0: + padded = mx.qqmm( + x, + mx.pad(q, [(0, (-n) % 8), (0, 0)]), + mx.pad(s, [(0, (-n) % 8), (0, 0)]), + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + ) + self.assertTrue(mx.array_equal(actual, padded[..., :n]).item()) + def test_fp_qmv(self): key = mx.random.key(0) k1, k2 = mx.random.split(key) + tol = 2e-2 if mx.cuda.is_available() else 1e-3 tests = product( [256, 512, 67, 5, 7], # M -- 5, 7 exercise out_vec_size < 8 (#3762) [64, 256], # N @@ -651,7 +1129,7 @@ def test_fp_qmv(self): ) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test multiple of 16 but not 32 M = 128 @@ -673,7 +1151,7 @@ def test_fp_qmv(self): ) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) def test_fp_qmv_large_output(self): key = mx.random.key(0) @@ -711,6 +1189,7 @@ def test_fp_qmv_large_output(self): self.assertTrue(mx.allclose(y_q, y_hat, rtol=tol, atol=tol)) def test_qmv_wide(self): + tol = 5e-2 if mx.cuda.is_available() else 1e-3 # M in [2, vector_limit) routes to qmv_wide -- except K in {64, 128} # with power-of-2 bits, which stays on qmv_quad. Check both paths # against a dequantize-then-matmul reference, with ragged M (token @@ -741,7 +1220,7 @@ def test_qmv_wide(self): ) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # FP modes (group_size and bits implied by the mode). for mode, K in product(["mxfp4", "nvfp4", "mxfp8"], [128, 512]): @@ -756,7 +1235,7 @@ def test_qmv_wide(self): y_q = mx.quantized_matmul(x, w_q, scales, transpose=True, mode=mode) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Tiny shapes (M, K, N): small K and non-multiple output rows. tiny = [(2, 32, 10), (4, 32, 7), (3, 64, 5), (5, 64, 3)] @@ -785,7 +1264,7 @@ def test_qmv_wide(self): ) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) def test_qvm(self): key = mx.random.key(0) @@ -909,6 +1388,167 @@ def test_fp_qvm(self): self.assertEqual(y_q.shape, y_hat.shape) self.assertLess((y_q - y_hat).abs().max(), 2e-3) + FP_TAIL_TOLS = {mx.float32: 2e-3, mx.float16: 5e-3, mx.bfloat16: 4e-2} + + def _fp_tail_dtypes(self): + # The half types only run on the GPU + if mx.default_device() == mx.gpu: + return [mx.float32, mx.float16, mx.bfloat16] + return [mx.float32] + + def test_fp_qmm_non_multiple_of_32(self): + key = mx.random.key(0) + k1, k2 = mx.random.split(key) + + def check(M, K, N, transpose, mode, dtype): + with self.subTest( + M=M, K=K, N=N, transpose=transpose, mode=mode, dtype=dtype + ): + w_shape = (N, K) if transpose else (K, N) + x = (mx.random.normal(shape=(M, K), key=k1) / K**0.5).astype(dtype) + w = mx.random.normal(shape=w_shape, key=k2).astype(dtype) + w_q, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(w_q, scales, mode=mode) + + y_q = mx.quantized_matmul( + x, w_q, scales, transpose=transpose, mode=mode + ) + # An unbounded store of the N tail spills onto the next output + # row and races the threadgroup that owns it, so two identical + # runs must agree bit for bit. + y_q2 = mx.quantized_matmul( + x, w_q, scales, transpose=transpose, mode=mode + ) + y_hat = x @ (mx.swapaxes(w_hat, -1, -2) if transpose else w_hat) + + self.assertEqual(y_q.shape, y_hat.shape) + self.assertTrue(mx.array_equal(y_q, y_q2)) + self.assertLess((y_q - y_hat).abs().max(), self.FP_TAIL_TOLS[dtype]) + + # (M, K, N, transpose). M is kept clear of the qmv batch limit + # (get_qmv_batch_limit caps at 32) so these route to the tiled kernel. + nvfp4_shapes = [ + (50, 1040, 128, True), # K % 32 == 16 + (33, 528, 64, True), # K % 32 == 16, M just over one BM tile + (50, 512, 1040, False), # N % 32 == 16 + (50, 1040, 1040, False), # both dims carry a tail + (50, 16, 128, True), # K is a single partial tile + ] + control_shapes = [ + (50, 1056, 128, True), # K % 32 == 0 + (50, 512, 1056, False), # N % 32 == 0 + ] + + for dtype in self._fp_tail_dtypes(): + for M, K, N, transpose in nvfp4_shapes: + check(M, K, N, transpose, "nvfp4", dtype) + for mode in ["mxfp4", "mxfp8"]: + for M, K, N, transpose in control_shapes: + check(M, K, N, transpose, mode, dtype) + + def test_fp_qmm_non_multiple_of_32_vjp(self): + # The backward of quantized_matmul runs the same kernels with the + # transpose flipped, so cover both directions at a tail shape. + key = mx.random.key(0) + k1, k2, k3 = mx.random.split(key, 3) + M, K, N = 50, 1040, 128 + + for dtype in self._fp_tail_dtypes(): + for transpose in [True, False]: + with self.subTest(transpose=transpose, dtype=dtype): + w_shape = (N, K) if transpose else (K, N) + x = (mx.random.normal(shape=(M, K), key=k1) / K**0.5).astype(dtype) + w = mx.random.normal(shape=w_shape, key=k2).astype(dtype) + w_q, scales = mx.quantize(w, mode="nvfp4") + w_hat = mx.dequantize(w_q, scales, mode="nvfp4") + cot = (mx.random.normal(shape=(M, N), key=k3) / N**0.5).astype( + dtype + ) + + def f(x): + return mx.quantized_matmul( + x, w_q, scales, transpose=transpose, mode="nvfp4" + ) + + (out,), (grad,) = mx.vjp(f, (x,), (cot,)) + tol = self.FP_TAIL_TOLS[dtype] + + # The forward runs the tail kernel for this transpose; the + # backward runs it for the other one, we might as well check both. + out_hat = x @ (mx.swapaxes(w_hat, -1, -2) if transpose else w_hat) + self.assertEqual(out.shape, out_hat.shape) + self.assertLess((out - out_hat).abs().max(), tol) + + grad_hat = cot @ ( + w_hat if transpose else mx.swapaxes(w_hat, -1, -2) + ) + self.assertEqual(grad.shape, grad_hat.shape) + self.assertLess((grad - grad_hat).abs().max(), tol) + + def test_fp_gather_qmm_non_multiple_of_32(self): + # Both gather_qmm kernels: the sorted-indices (MoE prefill) kernel and + # the tiled gather kernel. + key = mx.random.key(0) + k1, k2, k3 = mx.random.split(key, 3) + mode = "nvfp4" + E = 4 + + def check(K, N, transpose, sorted_indices, dtype): + with self.subTest( + K=K, + N=N, + transpose=transpose, + sorted_indices=sorted_indices, + dtype=dtype, + ): + w_shape = (E, N, K) if transpose else (E, K, N) + w = mx.random.normal(shape=w_shape, key=k2).astype(dtype) + w_q, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(w_q, scales, mode=mode) + + if sorted_indices: + T = 64 + x = (mx.random.normal(shape=(T, 1, K), key=k1) / K**0.5).astype( + dtype + ) + rhs = mx.sort(mx.random.randint(0, E, shape=(T,), key=k3)).astype( + mx.uint32 + ) + lhs = None + else: + B, M = 8, 50 + x = (mx.random.normal(shape=(B, M, K), key=k1) / K**0.5).astype( + dtype + ) + rhs = mx.random.randint(0, E, shape=(B,), key=k3).astype(mx.uint32) + lhs = mx.arange(B, dtype=mx.uint32) + + y_q = mx.gather_qmm( + x, + w_q, + scales, + lhs_indices=lhs, + rhs_indices=rhs, + transpose=transpose, + mode=mode, + sorted_indices=sorted_indices, + ) + w_sel = mx.take(w_hat, rhs, axis=0) + y_hat = x @ (mx.swapaxes(w_sel, -1, -2) if transpose else w_sel) + + self.assertEqual(y_q.shape, y_hat.shape) + self.assertLess((y_q - y_hat).abs().max(), self.FP_TAIL_TOLS[dtype]) + + # (K, N, transpose): transpose puts the tail on K, else on N. + shapes = [ + (1040, 128, True), # K % 32 == 16 + (512, 1040, False), # N % 32 == 16 + ] + for dtype in self._fp_tail_dtypes(): + for K, N, transpose in shapes: + for sorted_indices in [True, False]: + check(K, N, transpose, sorted_indices, dtype) + def test_mode_error_cases(self): w = mx.random.normal(shape=(256, 256)) x = mx.random.normal(shape=(1, 256)) @@ -991,6 +1631,7 @@ def test_throw(self): mx.eval(y) def test_small_matrix(self): + tol = 3e-2 if mx.cuda.is_available() else 1e-3 for w_shape in [(8, 256), (1, 8, 256), (3, 8, 256)]: with self.subTest(w_shape=w_shape): w = mx.random.normal(shape=(w_shape)) @@ -1003,30 +1644,31 @@ def test_small_matrix(self): y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm_t x = mx.random.normal(shape=(3, 10, 256)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ mx.swapaxes(w_hat, -1, -2) self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qvm x = mx.random.normal(shape=(3, 1, 8)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm x = mx.random.normal(shape=(3, 10, 8)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) def test_non_multiples(self): + tol = 3e-2 if mx.cuda.is_available() else 1e-3 w = mx.random.normal(shape=(33, 256)) w_q, scales, biases = mx.quantize(w) w_hat = mx.dequantize(w_q, scales, biases) @@ -1035,28 +1677,28 @@ def test_non_multiples(self): x = mx.random.normal(shape=(1, 256)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ w_hat.T - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm_t x = mx.random.normal(shape=(10, 256)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ w_hat.T self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qvm x = mx.random.normal(shape=(1, 33)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm x = mx.random.normal(shape=(10, 33)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Smaller than 8 w = mx.random.normal(shape=(3, 256)) @@ -1067,28 +1709,28 @@ def test_non_multiples(self): x = mx.random.normal(shape=(1, 256)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ w_hat.T - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm_t x = mx.random.normal(shape=(10, 256)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ w_hat.T self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qvm x = mx.random.normal(shape=(1, 3)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test qmm x = mx.random.normal(shape=(10, 3)) y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=False) y_hat = x @ w_hat self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) # Test with larger than 128 unaligned sizes w = mx.random.normal(shape=(99, 256)) @@ -1098,7 +1740,7 @@ def test_non_multiples(self): y_q = mx.quantized_matmul(x, w_q, scales, biases, transpose=True) y_hat = x @ w_hat.T self.assertEqual(y_q.shape, y_hat.shape) - self.assertLess((y_q - y_hat).abs().max(), 1e-3) + self.assertLess((y_q - y_hat).abs().max(), tol) def test_qmv_small_non_multiples(self): # Test very small K and N dimensions (e.g., [MxK] x [NxK].T = [MxN]) @@ -1184,6 +1826,9 @@ def test_shape( group_size=None, bits=None, mode="affine", + noncontiguous_x=False, + rtol=1e-5, + atol=1e-4, ): with self.subTest( M=M, @@ -1198,6 +1843,9 @@ def test_shape( group_size=group_size, bits=bits, mode=mode, + noncontiguous_x=noncontiguous_x, + rtol=rtol, + atol=atol, ): x = mx.random.normal(shape=batch_A + (M, K)).astype(dtype) w = mx.random.normal( @@ -1205,6 +1853,9 @@ def test_shape( ).astype(dtype) w_hat, qw, s, b = quantize(w, transpose, group_size, bits, mode=mode) + if noncontiguous_x: + x = mx.concatenate([x, x], axis=-1)[..., : x.shape[-1]] + if lhs_indices is not None: lhs_indices = mx.array(lhs_indices) if rhs_indices is not None: @@ -1223,7 +1874,7 @@ def test_shape( bits=bits, mode=mode, ) - self.assertTrue(mx.allclose(c1, c2, atol=1e-4)) + self.assertTrue(mx.allclose(c1, c2, rtol=rtol, atol=atol)) inputs = ( { @@ -1300,6 +1951,71 @@ def test_shape( test_shape(32, 512, 32, transpose=False, **kwargs) test_shape(1, 512, 32, transpose=False, **kwargs) + # Long K with many gathered vectors uses the nvfp4 gather qmv kernel on + # the GPU. Low precision outputs need a tolerance of about one ulp. + on_gpu = mx.default_device() == mx.gpu + bf16 = dict(dtype=mx.bfloat16 if on_gpu else mx.float32, rtol=1e-2, atol=1e-2) + f16 = dict(dtype=mx.float16 if on_gpu else mx.float32, rtol=1e-3, atol=1e-3) + test_shape( + 1, + 32, + 1024, + batch_A=(1,), + batch_B=(3,), + lhs_indices=(0,), + rhs_indices=(2, 1, 0, 2, 1, 0, 2, 1, 0), + mode="nvfp4", + **bf16, + ) + test_shape( + 1, + 33, + 1024, + batch_A=(2, 2), + batch_B=(2,), + lhs_indices=((0,), (3,)), + rhs_indices=((1, 0, 1),), + mode="nvfp4", + noncontiguous_x=True, + **f16, + ) + # K = 1056 leaves one warp lane active in the second reduction step. + test_shape( + 1, + 32, + 1056, + batch_A=(1,), + batch_B=(3,), + lhs_indices=(0,), + rhs_indices=(2, 1, 0, 2, 1, 0, 2, 1, 0), + mode="nvfp4", + ) + for mode in ("mxfp4", "mxfp8"): + test_shape( + 1, + 33, + 1024, + batch_A=(1,), + batch_B=(3,), + lhs_indices=(0,), + rhs_indices=(2, 1, 0, 2, 1, 0, 2, 1, 0), + mode=mode, + **bf16, + ) + for mode in ("nvfp4", "mxfp4", "mxfp8"): + for K, tol in ((448, 1e-1), (512, 1e-2), (704, 1e-2)): + test_shape( + 1, + 33, + K, + batch_A=(1,), + batch_B=(3,), + lhs_indices=(0,), + rhs_indices=(2, 1, 0, 2, 1, 0, 2, 1, 0), + mode=mode, + **{**bf16, "rtol": tol, "atol": tol}, + ) + def test_gather_qqmm(self): if mx.default_device() == mx.cpu: self.skipTest("Not implemented for CPU") @@ -1394,6 +2110,74 @@ def test_gather_qqmm(self): self.assertEqual(y_q.shape, y_hat.shape) self.assertLess((y_q - y_hat).abs().max(), 1e-3) + def test_gather_qqmm_global_scale_matrix_paths(self): + if mx.default_device() == mx.cpu: + self.skipTest("Not implemented for CPU") + + E, N, K = 3, 64, 256 + w = mx.random.normal((E, N, K), key=mx.random.key(10)).astype(mx.bfloat16) + global_scale_w = mx.max(mx.abs(w), axis=(1, 2)).astype(mx.float32) + quantized = [ + mx.quantize(w[e], mode="nvfp4", global_scale=global_scale_w[e]) + for e in range(E) + ] + w_q = mx.stack([q for q, _ in quantized]) + scales_w = mx.stack([scales for _, scales in quantized]) + w_hat = mx.stack( + [ + mx.dequantize( + q, + scales, + mode="nvfp4", + dtype=mx.bfloat16, + global_scale=global_scale_w[e], + ) + for e, (q, scales) in enumerate(quantized) + ] + ) + + def check(x, rhs, lhs=None, sorted_indices=False): + global_scale_x = mx.max(mx.abs(x)).astype(mx.float32) + x_hat = mx.dequantize( + *mx.quantize(x, mode="nvfp4", global_scale=global_scale_x), + mode="nvfp4", + dtype=mx.bfloat16, + global_scale=global_scale_x, + ) + actual = mx.gather_qqmm( + x, + w_q, + scales_w, + lhs, + rhs, + mode="nvfp4", + global_scale_x=global_scale_x, + global_scale_w=global_scale_w, + sorted_indices=sorted_indices, + ) + expected = mx.gather_mm( + x_hat, + mx.swapaxes(w_hat, -1, -2), + lhs, + rhs, + sorted_indices=sorted_indices, + ) + error = mx.abs(actual.astype(mx.float32) - expected.astype(mx.float32)) + scale = mx.maximum(mx.abs(expected.astype(mx.float32)).max(), 1e-20) + tol = 1e-1 if mx.cuda.is_available() else 3e-2 + self.assertLess(error.max() / scale, tol) + + # Sorted indices select the RHS-grouped matrix kernel. + x = mx.random.normal((24, 1, K), key=mx.random.key(20)).astype(mx.bfloat16) + rhs = mx.array([0] * 8 + [1] * 8 + [2] * 8) + check(x, rhs, sorted_indices=True) + + # A large M selects the gathered matrix kernel. + x = mx.random.normal((2, 64, K), key=mx.random.key(30)).astype(mx.bfloat16) + lhs = mx.array([0, 1, 0, 1]) + rhs = mx.array([0, 1, 2, 0]) + check(x, rhs, lhs) + def test_qmm_fp_type(self): indices = mx.array([[2], [0], [1]], dtype=mx.uint32) @@ -1534,8 +2318,10 @@ def scatter_unsort(x, inv_order, shape=None): k1, k2, k3 = mx.random.split(key, 3) dtype = mx.float16 if (mx.default_device() == mx.gpu) else mx.float32 - for L, K, D, E, I, transpose, mode in parameters: - with self.subTest(L=L, K=K, D=D, E=E, I=I, transpose=transpose, mode=mode): + for L, K, D, E, num_indices, transpose, mode in parameters: + with self.subTest( + L=L, K=K, D=D, E=E, I=num_indices, transpose=transpose, mode=mode + ): if mode != "affine": group_size = None dtype = ( @@ -1548,7 +2334,7 @@ def scatter_unsort(x, inv_order, shape=None): ) K, D = (K, D) if transpose else (D, K) - ishape = (L, I) + ishape = (L, num_indices) xshape = (L, 1, 1, K) wshape = (E, D, K) if transpose else (E, K, D) @@ -1673,6 +2459,49 @@ def test_affine_qmm_cpu_low_precision_accumulation(self): actual = mx.quantized_matmul(x, *packed, group_size=32, bits=bits) self.assertTrue(mx.array_equal(actual, expected)) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_gather_qmm_sorted_nax_large_m(self): + E, N, K, group_size = 16, 64, 64, 32 + dtype = mx.float16 + mx.random.seed(0) + w = (mx.random.normal((E, N, K)) * 0.1).astype(dtype) + w_q, scales, biases = mx.quantize(w, group_size=group_size, bits=4) + w_hat = mx.dequantize(w_q, scales, biases, group_size=group_size, bits=4) + + for M in (32767, 32768, 32769, 32832): + with self.subTest(M=M): + x = (mx.random.normal((M, 1, K)) * 0.1).astype(dtype) + rhs_indices = (mx.arange(M) * E // M).astype(mx.uint32) + y_hat = mx.gather_mm( + x.astype(mx.float32), + mx.swapaxes(w_hat, -1, -2).astype(mx.float32), + rhs_indices=rhs_indices, + sorted_indices=True, + ) + mx.eval(y_hat) + mx.synchronize() + + for value in (-31.0, 47.0): + poison = mx.full(y_hat.shape, value, dtype=mx.float16) + mx.eval(poison) + mx.synchronize() + del poison + + y_q = mx.gather_qmm( + x, + w_q, + scales, + biases, + rhs_indices=rhs_indices, + transpose=True, + group_size=group_size, + bits=4, + sorted_indices=True, + ) + max_error = (y_q.astype(mx.float32) - y_hat).abs().max() + self.assertLess(float(max_error.item()), 5e-2) + del y_q, max_error + @unittest.skipIf(mx.cuda.is_available(), "Not implemented for CUDA") @unittest.skipUnless(mx.metal.is_available(), "Metal tail-load regression") def test_gather_qmm_sorted_partial_tiles(self): @@ -1763,6 +2592,114 @@ def test_gather_qmm_sorted_sliced_weight(self): ) ) + def test_gather_qmm_sorted_unaligned_k(self): + # Every case in test_gather_qmm_sorted uses K % 64 == 0, so the tail of + # the K loop is never exercised. When K is not a multiple of the block + # size the sorted path has to zero the partial tile correctly, otherwise + # it silently drops the tail contribution for part of the output. + L, D, E = 128, 256, 4 + key = mx.random.key(0) + k1, k2, k3 = mx.random.split(key, 3) + on_gpu = mx.default_device() == mx.gpu + + dtype = mx.float16 if on_gpu else mx.float32 + + for mode, group_size in ( + ("affine", 32), + ("mxfp4", None), + ("mxfp8", None), + ("nvfp4", None), + ): + for K in (160, 288, 544): + with self.subTest(mode=mode, K=K): + indices = mx.sort( + (mx.random.uniform(shape=(L,), key=k1) * E).astype(mx.uint32) + ) + x = (mx.random.normal((L, 1, K), key=k2) / K**0.5).astype(dtype) + w = (mx.random.normal((E, D, K), key=k3) / K**0.5).astype(dtype) + + if mode == "affine": + wq = mx.quantize(w, group_size=group_size, mode=mode) + else: + wq = mx.quantize(w, mode=mode) + + kwargs = dict( + group_size=group_size, + mode=mode, + transpose=True, + rhs_indices=indices, + ) + y_sorted = mx.gather_qmm(x, *wq, sorted_indices=True, **kwargs) + y_unsorted = mx.gather_qmm(x, *wq, sorted_indices=False, **kwargs) + + tol = 1e-3 if on_gpu else 1.5e-5 + self.assertLess((y_sorted - y_unsorted).abs().max(), tol) + + @unittest.skipIf(not mx.cuda.is_available(), "CUDA kernel path only") + def test_gather_qmm_sorted_rhs_cuda(self): + # Sorted rows with a shared LHS take the sorted-RHS matrix kernel. Row + # counts cover the 16/32/64-row tiles and a row tail; random routing + # gives runs of unequal length that cross tile edges. + mx.random.seed(0) + shapes = [(64, 4, 2816, 704)] + [ + (rows, 8, 256, 256) for rows in (16, 24, 40, 64, 100, 200, 1000) + ] + for rows, experts, n, k in shapes: + for dtype in (mx.bfloat16, mx.float16): + x = (mx.random.normal((rows, 1, 1, k)) / k**0.5).astype(dtype) + w = mx.random.normal((experts, n, k)).astype(dtype) + indices = mx.sort(mx.random.randint(0, experts, (rows,))).astype( + mx.uint32 + )[:, None] + for mode in ("nvfp4", "mxfp4", "mxfp8"): + with self.subTest(rows=rows, dtype=dtype, mode=mode): + qw, scales = mx.quantize(w, mode=mode) + w_hat = mx.dequantize(qw, scales, mode=mode) + reference = mx.gather_mm( + x, w_hat.swapaxes(-1, -2), rhs_indices=indices + ) + expected = mx.gather_qmm( + x, + qw, + scales, + rhs_indices=indices, + transpose=True, + mode=mode, + sorted_indices=False, + ) + mx.eval(reference, expected) + # Successive runs in one CTA reuse its shared memory; + # repeat to catch a race between them. + for _ in range(3): + actual = mx.gather_qmm( + x, + qw, + scales, + rhs_indices=indices, + transpose=True, + mode=mode, + sorted_indices=True, + ) + mx.eval(actual) + self.assertLess( + mx.max(mx.abs(expected - actual)).item(), 1e-2 + ) + self.assertTrue( + mx.allclose(reference, actual, rtol=2e-2, atol=2e-2) + ) + + # One x row broadcast over the sorted indices stays on the generic + # gathered kernel. + rows, experts, n, k = 16, 4, 256, 256 + x = mx.random.normal((1, 1, k)).astype(mx.bfloat16) + w = mx.random.normal((experts, n, k)).astype(mx.bfloat16) + qw, scales = mx.quantize(w, mode="mxfp8") + indices = mx.repeat(mx.arange(experts), rows // experts).astype(mx.uint32) + kwargs = dict(rhs_indices=indices, transpose=True, mode="mxfp8") + expected = mx.gather_qmm(x, qw, scales, sorted_indices=False, **kwargs) + actual = mx.gather_qmm(x, qw, scales, sorted_indices=True, **kwargs) + self.assertLess(mx.max(mx.abs(expected - actual)).item(), 1e-3) + def test_gather_qmm_grad(self): def gather_qmm_ref(x, w, s, b, lhs, rhs, trans, sort): if lhs is not None: @@ -1808,8 +2745,9 @@ def gather_qmm(x, w, s, b, lhs, rhs, trans, sort): self.assertLess((o1 - o2).abs().max(), 1e-4) self.assertTrue(mx.allclose(o1, o2, atol=1e-4)) self.assertTrue(mx.allclose(dx1, dx2, atol=1e-4)) - self.assertTrue(mx.allclose(ds1, ds2, atol=1e-3)) - self.assertTrue(mx.allclose(db1, db2, atol=1e-3)) + tol = 5e-1 if mx.cuda.is_available() else 1e-3 + self.assertTrue(mx.allclose(ds1, ds2, atol=tol)) + self.assertTrue(mx.allclose(db1, db2, atol=tol)) def test_vjp_scales_biases(self): mx.random.seed(0) @@ -1824,6 +2762,7 @@ def mm(sb, x, wq): dparams = mx.grad(mm)((s, b), x, wq) eps = 8e-3 + delta = 5e-1 if mx.cuda.is_available() else 2e-2 # numerical grad check with a few indices indices = [(0, 0), (11, 4), (22, 7)] for idx in indices: @@ -1834,7 +2773,7 @@ def mm(sb, x, wq): out_down = mm(params, x, wq) params[p][idx] += eps num_ds = (out_up - out_down) / (2 * eps) - self.assertAlmostEqual(dparams[p][idx], num_ds, delta=2e-2) + self.assertAlmostEqual(dparams[p][idx], num_ds, delta=delta) def test_fp_vjp_scales_throws(self): mx.random.seed(0) @@ -1848,7 +2787,7 @@ def mm(s, x, wq): # Should raise with self.assertRaises(ValueError): - ds = mx.grad(mm)(s, x, wq) + mx.grad(mm)(s, x, wq) rhs_indices = mx.array(0) with self.assertRaises(ValueError): @@ -1862,7 +2801,116 @@ def gmm(s, x, wq): mode=mode, ).sum() - ds = mx.grad(gmm)(s, x, wq) + _ds = mx.grad(gmm)(s, x, wq) + + @unittest.skipIf( + not mx.is_available(mx.gpu), "Global scale is only supported on the GPU" + ) + def test_gather_qmm_global_scale(self): + mx.random.seed(0) + N, K = 128, 256 + + def rel_err(got, expected): + # Per row + d = mx.abs(got.astype(mx.float32) - expected.astype(mx.float32)) + scale = mx.abs(expected.astype(mx.float32)) + axes = tuple(range(1, d.ndim)) + return (d.max(axis=axes) / mx.maximum(scale.max(axis=axes), 1e-20)).max() + + def quantize_experts(w): + """One tensor scale per expert.""" + E = w.shape[0] + gs = mx.stack([mx.abs(w[e]).max().astype(mx.float32) for e in range(E)]) + qs = [mx.quantize(w[e], mode="nvfp4", global_scale=gs[e]) for e in range(E)] + w_hat = mx.stack( + [ + mx.dequantize( + q, sc, mode="nvfp4", global_scale=gs[e], dtype=w.dtype + ) + for e, (q, sc) in enumerate(qs) + ] + ) + return ( + mx.stack([q for q, _ in qs]), + mx.stack([sc for _, sc in qs]), + gs, + w_hat, + ) + + tests = product( + [4, 128, 234], # E + [mx.float32, mx.float16, mx.bfloat16], # dtype + [True, False], # transpose + [(32, 2, False), (1, 2, False), (256, 4, True)], # M, B, sort + ) + for E, dtype, transpose, (M, B, sort) in tests: + with self.subTest(E=E, dtype=dtype, transpose=transpose, M=M, B=B): + # Each expert has a different scale, so we multiply by a factor + # to make the experts have different magnitudes. + factors = mx.array( + [[1, 2, 4, 8][e % 4] for e in range(E)], mx.float32 + ).reshape((E, 1, 1)) + wshape = (E, N, K) if transpose else (E, K, N) + w = (mx.random.normal(wshape) * factors).astype(dtype) + wq, s, gs, w_hat = quantize_experts(w) + self.assertEqual(gs.shape, (E,)) + + x = mx.random.normal((B, M, K)).astype(dtype) + indices = mx.random.randint(0, E, (B,)) + if sort: + indices = mx.sort(indices) + + wg = w_hat[indices] + expected = x @ (wg.swapaxes(-1, -2) if transpose else wg) + kwargs = dict( + rhs_indices=indices, + transpose=transpose, + mode="nvfp4", + sorted_indices=sort, + ) + + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.gather_qmm(x, wq, s, global_scale=gs, **kwargs) + continue + + out = mx.gather_qmm(x, wq, s, global_scale=gs, **kwargs) + tol = ( + 1e-5 if dtype == mx.float32 and not mx.cuda.is_available() else 3e-2 + ) + self.assertLess(rel_err(out, expected), tol) + + # Each expert uses its own scale, not a neighbour's + rotated = mx.concatenate([gs[1:], gs[:1]]) + wrong = mx.gather_qmm(x, wq, s, global_scale=rotated, **kwargs) + self.assertGreater(rel_err(wrong, expected), 0.5) + + # Repeated and out-of-order experts with explicit lhs indices on the + # M=1 vector path; each output must pick its own expert's scale. The + # long K is the decode shape that long-K vector kernels take. + E = 6 + for K in (K, 2048): + with self.subTest(K=K): + w = (mx.random.normal((E, N, K)) / K**0.5).astype(mx.bfloat16) + wq, s, gs, w_hat = quantize_experts(w) + indices = mx.array([3, 0, 5, 3, 1, 0], mx.uint32) + x = (mx.random.normal((2, 1, K)) / K**0.5).astype(mx.bfloat16) + lhs = mx.array([0, 1, 0, 1, 0, 1], mx.uint32) + expected = x[lhs] @ w_hat[indices].swapaxes(-1, -2) + kwargs = dict( + lhs_indices=lhs, + rhs_indices=indices, + mode="nvfp4", + global_scale=gs, + ) + if mx.default_device() != mx.gpu: + # Global scale is only supported on the GPU. + with self.assertRaises(ValueError): + mx.gather_qmm(x, wq, s, **kwargs) + continue + out = mx.gather_qmm(x, wq, s, **kwargs) + self.assertLess(rel_err(out, expected), 3e-2) def test_quantize_strided(self): N = 64 @@ -1875,6 +2923,28 @@ def test_quantize_strided(self): expected = mx.dequantize(w_q, mx.contiguous(scales), mode=mode) self.assertTrue(mx.allclose(w_hat, expected)) + def test_quantized_matmul_batched_split_k(self): + tol = 3e-2 if mx.cuda.is_available() else 1e-3 + K, N = 2048, 512 + w = mx.random.normal(shape=(K, N)) + w_q, scales, biases = mx.quantize(w, group_size=64, bits=4) + w_hat = mx.dequantize(w_q, scales, biases, group_size=64, bits=4) + + shapes = [ + (2, K), + (2, 1, K), + (3, 1, K), + (2, 1, 1, K), + ] + for shape in shapes: + x = mx.random.normal(shape=shape) + y_q = mx.quantized_matmul( + x, w_q, scales, biases, transpose=False, group_size=64, bits=4 + ) + y_hat = x @ w_hat + self.assertEqual(y_q.shape, y_hat.shape) + self.assertLess((y_q - y_hat).abs().max(), tol) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_random.py b/python/tests/test_random.py index 96a789b608..5374d4abba 100644 --- a/python/tests/test_random.py +++ b/python/tests/test_random.py @@ -1,7 +1,6 @@ # Copyright © 2023 Apple Inc. import math -import unittest import mlx.core as mx import mlx_tests @@ -112,6 +111,16 @@ def test_normal_and_laplace(self): a = abs(distribution_sampler(shape=(10000,), loc=0, scale=1, dtype=hp)) self.assertTrue(mx.all(a < mx.inf)) + def test_normal_loc_scale_shape(self): + msg = r"\[normal\] Cannot generate random values" + with self.assertRaisesRegex(ValueError, msg): + mx.random.normal(shape=(3,), loc=mx.zeros((2, 3))) + with self.assertRaisesRegex(ValueError, msg): + mx.random.normal(shape=(3,), scale=mx.ones((2, 3))) + + x = mx.random.normal(shape=(2, 3), loc=mx.zeros((3,)), scale=mx.ones((2, 1))) + self.assertEqual(x.shape, (2, 3)) + def test_multivariate_normal(self): key = mx.random.key(0) mean = mx.array([0, 0]) diff --git a/python/tests/test_reduce.py b/python/tests/test_reduce.py index 164e2dd803..4abdc11a11 100644 --- a/python/tests/test_reduce.py +++ b/python/tests/test_reduce.py @@ -1,5 +1,7 @@ # Copyright © 2023 Apple Inc. +import math +import unittest from itertools import combinations, permutations import mlx.core as mx @@ -56,6 +58,33 @@ def test_row_reduce_negative_stride(self): actual = getattr(mx, op)(x_mlx, axis=-1) self.assertTrue(np.allclose(expected, actual)) + def test_col_reduce_negative_stride(self): + # Exercises each Metal column reduction kernel on a negative-stride view. + cases = [ + ((2, 1024, 16), 1), + ((2, 2, 1024, 16), 2), + ((2, 512, 2, 2, 16), (1, 3)), + ((2, 512, 64), 1), + ((2, 64, 512), 1), + ((2, 16, 16), 1), + ] + for shape, axis in cases: + size = math.prod(shape) + x_npy = np.arange(1, size + 1).reshape(shape)[::-1] + x_mlx = mx.arange(1, size + 1).reshape(shape)[::-1] + for op in ["sum", "max", "min", "mean", "var"]: + with self.subTest(shape=shape, axis=axis, op=op): + expected = getattr(np, op)(x_npy, axis=axis) + actual = getattr(mx, op)(x_mlx, axis=axis) + self.assertTrue(np.allclose(expected, actual)) + x_ones = mx.ones(shape, dtype=mx.float32)[::-1] + with self.subTest(shape=shape, axis=axis, op="prod"): + self.assertTrue(mx.all(mx.prod(x_ones, axis=axis) == 1).item()) + x_bool = mx.ones(shape, dtype=mx.bool_)[::-1] + for op in ["all", "any"]: + with self.subTest(shape=shape, axis=axis, op=op): + self.assertTrue(mx.all(getattr(mx, op)(x_bool, axis=axis)).item()) + def test_dtypes(self): int_dtypes = [ "int8", @@ -159,6 +188,35 @@ def test_zero_size(self): with self.assertRaises(ValueError): getattr(mx, op)(a_mx, axis=axis) + # sum and prod have identities, so an empty reduction returns them for + # every dtype. The unsigned outputs (uint32, uint64) had no init kernel + # on Metal and aborted the process instead. + dtypes = [ + mx.bool_, + mx.uint8, + mx.uint16, + mx.uint32, + mx.uint64, + mx.int8, + mx.int16, + mx.int32, + mx.int64, + mx.float16, + mx.float32, + ] + for dtype in dtypes: + a = mx.zeros((0,), dtype=dtype) + for op, identity in [("sum", 0), ("prod", 1)]: + out = getattr(mx, op)(a) + mx.eval(out) + self.assertEqual(out.item(), identity, f"{op} of empty {dtype}") + # empty because of another axis, reduced over a non-empty one + b = mx.zeros((0, 3), dtype=dtype) + for op in ["sum", "prod"]: + out = getattr(mx, op)(b, axis=-1) + mx.eval(out) + self.assertEqual(out.shape, (0,)) + def test_sum_bool(self): x = np.random.uniform(0, 1, size=(10, 10, 10)) > 0.5 y = mx.array(x) @@ -256,7 +314,7 @@ def test_long_column(self): def test_and_or_negative_zero(self): # -0.0 equals zero but has its sign bit set, so it must not be treated # as truthy just because its bit pattern is nonzero - for dtype in ["float32", "float16", "float64"]: + for dtype in ["float32", "float16", "float64", "complex64"]: with self.subTest(dtype=dtype): for values in [ [0.0, -0.0], @@ -282,6 +340,58 @@ def test_and_or_negative_zero(self): getattr(np, op)(x_np, axis=1).tolist(), ) + def test_large_offsets(self): + # Row r holds r % 251 and row 2**15 starts at offset 2**31, so any + # reduction that narrows offsets or sizes to 32 bits reads the wrong + # rows. The views below have fewer than 2**31 elements themselves. + rows, cols = 2**15 + 1, 2**16 + row_max = (mx.arange(rows) % 251).astype(mx.uint8) + x = mx.contiguous(mx.broadcast_to(row_max[:, None], (rows, cols))) + + self.assertTrue(mx.array_equal(x[:, 7:].max(axis=-1), row_max)) + self.assertTrue(mx.array_equal(x[:, 7:].min(axis=-1), row_max)) + y = x.reshape(rows, 256, 256)[:, 1:, 1:] + self.assertTrue(mx.array_equal(y.max(axis=(1, 2)), row_max)) + y = x.reshape(rows, 16, 16, 256)[:, 1:, :, 1:] + expected = mx.broadcast_to(row_max[:, None], (rows, 16)) + self.assertTrue(mx.array_equal(y.max(axis=(1, 3)), expected)) + + # Reducing all 2**31 + 2**16 elements at once + self.assertEqual(x.max().item(), 250) + self.assertTrue(x.any().item()) + self.assertFalse(x.all().item()) + + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_init_reduce_large_output(self): + # The output is 4 GiB. The macOS runners of the fork CI have a 3.5 GiB + # Metal buffer limit and 7 GB of memory, so skip where it cannot fit. + size = 4 * 2**30 + info = mx.device_info(mx.gpu) + if mx.default_device() == mx.gpu: + fits = info["max_buffer_length"] >= size + else: + fits = info["memory_size"] >= 4 * size + if not fits: + self.skipTest("the 4 GiB output does not fit on this device") + out = mx.all(mx.zeros((0, 4, 2**30), dtype=mx.bool_), axis=0) + mx.eval(out) + self.assertTrue(mx.all(out).item()) + + def test_minmax(self): + x = mx.array([[3.0, 1.0, 4.0], [2.0, 6.0, 5.0]]) + out = mx.minmax(x) + self.assertIsInstance(out, tuple) + self.assertEqual(len(out), 2) + self.assertEqual(tuple(a.item() for a in out), (1.0, 6.0)) + for axis in (None, 0, (0, 1)): + for keepdims in (False, True): + with self.subTest(axis=axis, keepdims=keepdims): + out = mx.minmax(x, axis=axis, keepdims=keepdims) + for actual, op in zip(out, (mx.min, mx.max)): + expected = op(x, axis=axis, keepdims=keepdims) + self.assertEqual(actual.shape, expected.shape) + self.assertTrue(mx.array_equal(actual, expected)) + if __name__ == "__main__": mlx_tests.MLXTestRunner(failfast=True) diff --git a/python/tests/test_threads.py b/python/tests/test_threads.py index e939ca83a7..3d2aa65191 100644 --- a/python/tests/test_threads.py +++ b/python/tests/test_threads.py @@ -1,7 +1,6 @@ # Copyright © 2026 Apple Inc. import threading -import unittest import mlx.core as mx import mlx_tests diff --git a/python/tests/test_tree.py b/python/tests/test_tree.py index 96184bd233..c7d2fadaae 100644 --- a/python/tests/test_tree.py +++ b/python/tests/test_tree.py @@ -1,6 +1,5 @@ # Copyright © 2023 Apple Inc. -import unittest import mlx.core as mx import mlx.nn as nn @@ -97,7 +96,8 @@ class Params(NamedTuple): params1 = Params(m=mx.array([0, 1]), b=mx.array(2)) dict1 = {"m": mx.array([0, 1]), "b": mx.array(2)} - add_one = lambda x: x + 1 + def add_one(x): + return x + 1 list2 = mlx.utils.tree_map(add_one, list1) tuple2 = mlx.utils.tree_map(add_one, tuple1) diff --git a/python/tests/test_upsample.py b/python/tests/test_upsample.py index 9a8ab9184c..d71ff90eae 100644 --- a/python/tests/test_upsample.py +++ b/python/tests/test_upsample.py @@ -12,7 +12,7 @@ import torch.nn.functional as F has_torch = True -except ImportError as e: +except ImportError: has_torch = False @@ -97,7 +97,9 @@ def run_upsample( @unittest.skipIf(not has_torch, "requires Torch") def test_torch_upsample_antialias(self): - """Test antialiased downsampling matches PyTorch F.interpolate(antialias=True).""" + """Test antialiased downsampling matches + PyTorch F.interpolate(antialias=True). + """ def run_antialias( N, @@ -146,7 +148,8 @@ def run_antialias( self.assertEqual(out_pt.shape, out_mx.shape) self.assertTrue( np.allclose(out_pt, out_mx, atol=atol), - f"antialias {mode} ac={align_corners} scale={scale_factor} max_diff=" + f"antialias {mode} ac={align_corners}" + f" scale={scale_factor} max_diff=" f"{np.abs(out_pt - np.array(out_mx)).max():.2e}", ) diff --git a/python/tests/test_vmap.py b/python/tests/test_vmap.py index b050a80384..570947d259 100644 --- a/python/tests/test_vmap.py +++ b/python/tests/test_vmap.py @@ -1,7 +1,6 @@ # Copyright © 2023-2024 Apple Inc. import gc -import unittest import mlx.core as mx import mlx_tests @@ -9,8 +8,8 @@ class TestVmap(mlx_tests.MLXTestCase): def test_basics(self): - # Can't vmap over scalars - with self.assertRaises(ValueError): + # Can't vmap over scalars, axis 0 is out of bounds for a 0d array + with self.assertRaises(IndexError): mx.vmap(mx.exp)(mx.array(1.0)) # Invalid input @@ -21,13 +20,13 @@ def test_basics(self): with self.assertRaises(ValueError): mx.vmap(mx.exp, in_axes="hello")(mx.array([0, 1])) - with self.assertRaises(ValueError): + with self.assertRaises(IndexError): mx.vmap(mx.exp, in_axes=2)(mx.array([0, 1])) with self.assertRaises(ValueError): mx.vmap(mx.exp, out_axes="hello")(mx.array([0, 1])) - with self.assertRaises(ValueError): + with self.assertRaises(IndexError): mx.vmap(mx.exp, out_axes=2)(mx.array([0, 1])) def test_unary(self): @@ -219,6 +218,19 @@ def test_vmap_indexing(self): ) self.assertTrue(mx.array_equal(out, expected)) + def test_vmap_strided_slice_single_element(self): + # A strided slice selecting exactly one element must vmap to the + # batched version of what the un-batched slice returns (regression: + # the stored stride was collapsed to 1 without narrowing stop, so + # re-deriving the region returned every element in the span). + x = mx.arange(24, dtype=mx.float32).reshape(4, 2, 3) + out = mx.vmap(lambda t: t[0::2])(x) + self.assertTrue(mx.array_equal(out, x[:, 0:1])) + + y = mx.arange(48, dtype=mx.float32).reshape(4, 4, 3) + out = mx.vmap(lambda t: t[0::2])(y) + self.assertTrue(mx.array_equal(out, y[:, 0:4:2])) + def test_vmap_reduce(self): a = mx.ones((5, 5), mx.int32) out = mx.vmap(lambda x: x.sum())(a) @@ -347,11 +359,11 @@ def test_mismatch_input_sizes(self): b = mx.ones((1, 1, 1, 5)) with self.assertRaises(ValueError): - out = mx.vmap(lambda x, y: x + y)(a, b) + mx.vmap(lambda x, y: x + y)(a, b) b = mx.ones((10, 5)) with self.assertRaises(ValueError): - out = mx.vmap(lambda x, y: x + y, in_axes=(0, 1))(a, b) + mx.vmap(lambda x, y: x + y, in_axes=(0, 1))(a, b) def test_vmap_matmul(self): a = mx.random.uniform(shape=(2, 3, 4)) @@ -395,10 +407,14 @@ def test_vmap_matmul(self): def test_vmap_svd(self): a = mx.random.uniform(shape=(3, 4, 2)) - cpu_svd_full = lambda x: mx.linalg.svd(x, compute_uv=True, stream=mx.cpu) - cpu_svd_singular = lambda x: mx.linalg.svd(x, compute_uv=False, stream=mx.cpu) + def cpu_svd_full(x): + return mx.linalg.svd(x, compute_uv=True, stream=mx.cpu) + + def cpu_svd_singular(x): + return mx.linalg.svd(x, compute_uv=False, stream=mx.cpu) - # Vmap over the first axis (this is already supported natively by the primitive). + # Vmap over the first axis (this is already supported natively by the + # primitive). Us, Ss, Vts = mx.vmap(cpu_svd_full, in_axes=(0,))(a) self.assertEqual(Us.shape, (a.shape[0], a.shape[1], a.shape[1])) self.assertEqual(Ss.shape, (a.shape[0], a.shape[2])) @@ -450,9 +466,11 @@ def test_vmap_inverse(self): mx.random.seed(42) a = mx.random.uniform(shape=(3, 4, 4)) - cpu_inv = lambda x: mx.linalg.inv(x, stream=mx.cpu) + def cpu_inv(x): + return mx.linalg.inv(x, stream=mx.cpu) - # Vmap over the first axis (this is already supported natively by the primitive). + # Vmap over the first axis (this is already supported natively by the + # primitive). invs = mx.vmap(cpu_inv, in_axes=(0,))(a) for i in range(a.shape[0]): @@ -547,6 +565,41 @@ def scatter_add(a): expected = mx.array([[2.0, 3.0, 4.0], [2.0, 3.0, 4.0]]) self.assertTrue(mx.allclose(out, expected)) + def test_vmap_scatter_higher_rank(self): + # The vmap axis becomes an extra scattered source axis, so the + # singleton added to the updates has to land at that axis rather than + # at the front of the source dims. Only shows up for a vmap axis >= 2, + # where the misplaced singleton actually reorders a non-unit dim. + def unstack(x, axis): + return [s.squeeze(axis) for s in mx.split(x, x.shape[axis], axis=axis)] + + for shape in [(2, 3), (2, 3, 4), (2, 3, 4, 5)]: + n = 1 + for d in shape: + n *= d + a = mx.arange(n, dtype=mx.float32).reshape(shape) + + fns = { + "add_derived": lambda x: x.at[mx.array([0])].add(x[:1]), + "add_const": lambda x: x.at[mx.array([0])].add( + mx.ones((1,) + tuple(x.shape[1:]), dtype=x.dtype) + ), + "add_dup": lambda x: x.at[mx.array([0, 0])].add( + mx.ones((2,) + tuple(x.shape[1:]), dtype=x.dtype) + ), + "maximum": lambda x: x.at[mx.array([0])].maximum(x[:1] + 1.0), + } + for name, fn in fns.items(): + for ax in range(len(shape)): + out = mx.vmap(fn, in_axes=ax, out_axes=ax)(a) + expected = mx.stack([fn(s) for s in unstack(a, ax)], axis=ax) + self.assertEqual( + out.shape, expected.shape, f"{name} ax{ax} {shape}" + ) + self.assertTrue( + mx.array_equal(out, expected), f"{name} ax{ax} {shape}" + ) + # Multiple indices def scatter(a): a[mx.array([0, 1]), mx.array([0, 1])] = mx.array((1.0, 1.0)) @@ -866,7 +919,7 @@ def transform_tuple(t): def transform_vector(t): return Vector([t[0] + 10, t[1] * 10]) - x = State(mx.array(1), mx.array(2)) + _x = State(mx.array(1), mx.array(2)) vmap_transform = mx.vmap(transform) vmap_transform_tuple = mx.vmap(transform_tuple) @@ -1037,6 +1090,17 @@ def test_vmap_argsort(self): out = mx.vmap(lambda x: mx.argsort(x, axis=axis), in_axes=1, out_axes=1)(a) self.assertTrue(mx.array_equal(out, expected)) + def test_vmap_view(self): + a = mx.arange(16, dtype=mx.uint8).reshape(4, 4) + b = mx.arange(16, dtype=mx.int32).reshape(4, 4) + for x, dtype in [(a, mx.int8), (a, mx.int16), (a, mx.int32), (b, mx.uint8)]: + for in_axes in [0, 1, -1]: + expected = mx.stack( + [mx.take(x, i, axis=in_axes).view(dtype) for i in range(4)] + ) + out = mx.vmap(lambda y: y.view(dtype), in_axes=in_axes)(x) + self.assertTrue(mx.array_equal(out, expected)) + if __name__ == "__main__": mlx_tests.MLXTestRunner() diff --git a/python/tests/test_zero_copy.py b/python/tests/test_zero_copy.py index 231e2e45ee..47c082bb7e 100644 --- a/python/tests/test_zero_copy.py +++ b/python/tests/test_zero_copy.py @@ -1,6 +1,10 @@ # Copyright © 2024 Apple Inc. +import faulthandler import gc +import os +import tempfile +import threading import unittest import mlx.core as mx @@ -51,6 +55,45 @@ def test_copy_false_dtype_conversion_raises(self): with self.assertRaises(Exception): mx.asarray(a, dtype=mx.float32, copy=False) + def test_dtype_mismatch_same_width_converts(self): + # Same item size, different dtype: values must be converted, not reinterpreted + a = np.arange(16, dtype=np.int32) + x = mx.asarray(a, dtype=mx.float32) + self.assertTrue(np.array_equal(np.array(x), a.astype(np.float32))) + y = mx.array([1.5, 2.5]) + np.array([1, 2], dtype=np.int32) + self.assertTrue(mx.array_equal(y, mx.array([2.5, 4.5]))) + with self.assertRaisesRegex(ValueError, "Cannot convert array"): + mx.asarray(a, dtype=mx.float32, copy=False) + + def test_misaligned_source_copies(self): + # Pointer not aligned to the item size + raw = np.arange(64, dtype=np.uint8) + a = raw[6:22].view(np.int32) + x = mx.asarray(a) + self.assertTrue(np.array_equal(x + 1, a + 1)) + with self.assertRaises(ValueError): + mx.asarray(a, copy=False) + + def test_ops_do_not_write_to_source(self): + a = np.ones(4096, np.float32) + mx.eval(mx.exp(a)) + self.assertTrue(np.array_equal(a, np.ones(4096, np.float32))) + + b = np.ones(4096, np.float32).tobytes() + mx.eval(mx.exp(mx.asarray(np.frombuffer(b, dtype=np.float32)))) + self.assertEqual(b, np.ones(4096, np.float32).tobytes()) + + def test_ops_on_read_only_memmap(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "a.npy") + np.save(path, np.ones(1 << 16, np.float32)) + a = np.load(path, mmap_mode="r") + y = mx.exp(mx.asarray(a)) + mx.eval(y) + self.assertTrue(np.allclose(np.array(y), np.exp(1.0))) + self.assertTrue(np.array_equal(np.load(path), np.ones(1 << 16))) + del a, y + def test_source_lifetime(self): if not mx.metal.is_available(): self.skipTest("copy=False requires Metal") @@ -83,6 +126,66 @@ def test_adopt_in_loop_not_recycled(self): mx.eval(r) self.assertTrue(True) # reaching here without crashing is the assertion + def _adopted_source(self, n): + # A square source buffer that mx.asarray can adopt, else a skip. + if not mx.metal.is_available(): + self.skipTest("copy=False requires Metal") + a = np.zeros((n, n), dtype=np.float32) + if a.ctypes.data % 16384 != 0: + self.skipTest("source buffer not page-aligned; adopt path not taken") + return a + + @staticmethod + def _submit_work(a): + # The adopted array is an input of the first matmul and is dropped here, + # so only the completion handler of the command buffer that is in flight + # keeps its Python owner. The caller must keep the output until the end. + n = a.shape[0] + w = mx.ones((n, n)) + y = mx.asarray(a, copy=False) @ w + for _ in range(4): + y = y @ w + mx.async_eval(y) + return y + + # A stream callback can free an adopted buffer, which takes the GIL. A call + # that waits for a stream must release the GIL, else the two deadlock. + # faulthandler reports such a deadlock, its timer is a C thread. A watchdog + # in Python would never run. + def test_synchronize_releases_gil(self): + a = self._adopted_source(1024) + faulthandler.dump_traceback_later(30, exit=True) + try: + for _ in range(4): + y = self._submit_work(a) + mx.synchronize() + del y + finally: + faulthandler.cancel_dump_traceback_later() + + def test_clear_streams_releases_gil(self): + a = self._adopted_source(1024) + errors = [] + + # clear_streams destroys the streams of the calling thread, so it runs + # in a thread that ends right after. + def worker(): + try: + y = self._submit_work(a) + mx.clear_streams() + del y + except Exception as e: + errors.append(e) + + faulthandler.dump_traceback_later(30, exit=True) + try: + thread = threading.Thread(target=worker) + thread.start() + thread.join() + finally: + faulthandler.cancel_dump_traceback_later() + self.assertEqual(errors, []) + if __name__ == "__main__": unittest.main() diff --git a/python/tests/xp-tests/skips.txt b/python/tests/xp-tests/skips.txt new file mode 100644 index 0000000000..2bd738bb74 --- /dev/null +++ b/python/tests/xp-tests/skips.txt @@ -0,0 +1,7 @@ +# 64bit dtype not supported https://github.com/ml-explore/mlx/issues/4300 +array_api_tests/test_creation_functions.py::test_eye + +array_api_tests/test_array_object.py::test_getitem_arrays_and_ints_2[None] +array_api_tests/test_array_object.py::test_getitem_arrays_and_ints_2[1] +array_api_tests/test_array_object.py::test_getitem_arrays_and_ints_1[None] +array_api_tests/test_array_object.py::test_getitem_arrays_and_ints_1[1] \ No newline at end of file diff --git a/python/tests/xp-tests/xfail.txt b/python/tests/xp-tests/xfail.txt new file mode 100644 index 0000000000..6ea2707acf --- /dev/null +++ b/python/tests/xp-tests/xfail.txt @@ -0,0 +1,421 @@ +# test_linalg.py +## Missing Extensions (linalg, fft) +array_api_tests/test_linalg.py::test_cholesky +array_api_tests/test_linalg.py::test_det +array_api_tests/test_linalg.py::test_diagonal +array_api_tests/test_linalg.py::test_eigh +array_api_tests/test_linalg.py::test_eigvalsh +array_api_tests/test_linalg.py::test_eig +array_api_tests/test_linalg.py::test_eigvals +array_api_tests/test_linalg.py::test_inv +array_api_tests/test_linalg.py::test_linalg_matmul +array_api_tests/test_linalg.py::test_matmul +array_api_tests/test_linalg.py::test_matrix_norm +array_api_tests/test_linalg.py::test_matrix_power +array_api_tests/test_linalg.py::test_matrix_rank +array_api_tests/test_linalg.py::test_linalg_matrix_transpose +array_api_tests/test_linalg.py::test_outer +array_api_tests/test_linalg.py::test_pinv +array_api_tests/test_linalg.py::test_qr +array_api_tests/test_linalg.py::test_slogdet +array_api_tests/test_linalg.py::test_solve +array_api_tests/test_linalg.py::test_svd +array_api_tests/test_linalg.py::test_svdvals +array_api_tests/test_linalg.py::test_linalg_tensordot +array_api_tests/test_linalg.py::test_tensordot +array_api_tests/test_linalg.py::test_trace +array_api_tests/test_linalg.py::test_linalg_vecdot +array_api_tests/test_linalg.py::test_vecdot +array_api_tests/test_linalg.py::test_vecdot_conj +array_api_tests/test_linalg.py::test_vector_norm +array_api_tests/test_linalg.py::test_eigvals + +# test_fft.py +## Missing Extensions (linalg, fft) +array_api_tests/test_fft.py::test_hfft +array_api_tests/test_fft.py::test_ihfft +array_api_tests/test_fft.py::test_fftfreq +array_api_tests/test_fft.py::test_rfftfreq + +# test_has_names.py +## Missing Functions +array_api_tests/test_has_names.py::test_has_names[linalg-diagonal] +array_api_tests/test_has_names.py::test_has_names[linalg-matmul] +array_api_tests/test_has_names.py::test_has_names[linalg-matrix_norm] +array_api_tests/test_has_names.py::test_has_names[linalg-matrix_power] +array_api_tests/test_has_names.py::test_has_names[linalg-matrix_rank] +array_api_tests/test_has_names.py::test_has_names[linalg-matrix_transpose] +array_api_tests/test_has_names.py::test_has_names[linalg-outer] +array_api_tests/test_has_names.py::test_has_names[linalg-svdvals] +array_api_tests/test_has_names.py::test_has_names[linalg-tensordot] +array_api_tests/test_has_names.py::test_has_names[linalg-trace] +array_api_tests/test_has_names.py::test_has_names[linalg-vecdot] +array_api_tests/test_has_names.py::test_has_names[linalg-vector_norm] +array_api_tests/test_has_names.py::test_has_names[fft-hfft] +array_api_tests/test_has_names.py::test_has_names[fft-ihfft] +array_api_tests/test_has_names.py::test_has_names[elementwise-copysign] +array_api_tests/test_has_names.py::test_has_names[elementwise-hypot] +array_api_tests/test_has_names.py::test_has_names[elementwise-nextafter] +array_api_tests/test_has_names.py::test_has_names[elementwise-signbit] +array_api_tests/test_has_names.py::test_has_names[array_method-to_device] +array_api_tests/test_has_names.py::test_has_names[array_attribute-device] +array_api_tests/test_has_names.py::test_has_names[set-isin] +array_api_tests/test_has_names.py::test_has_names[set-unique_all] +array_api_tests/test_has_names.py::test_has_names[set-unique_counts] +array_api_tests/test_has_names.py::test_has_names[set-unique_inverse] +array_api_tests/test_has_names.py::test_has_names[set-unique_values] +array_api_tests/test_has_names.py::test_has_names[searching-nonzero] + +# test_signatures.py +## Missing Extensions (linalg, fft) +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.cholesky] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.det] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.diagonal] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.eigh] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.eigvalsh] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.inv] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.matmul] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.matrix_norm] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.matrix_power] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.matrix_rank] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.matrix_transpose] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.outer] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.pinv] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.qr] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.slogdet] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.solve] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.svd] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.svdvals] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.tensordot] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.trace] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.vecdot] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.vector_norm] +array_api_tests/test_signatures.py::test_extension_func_signature[fft.hfft] +array_api_tests/test_signatures.py::test_extension_func_signature[fft.ihfft] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.cholesky] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.det] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.eigh] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.eigvalsh] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.inv] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.slogdet] +array_api_tests/test_signatures.py::test_extension_func_signature[linalg.solve] + +## Missing functions +array_api_tests/test_signatures.py::test_array_method_signature[to_device] +array_api_tests/test_signatures.py::test_func_signature[signbit] +array_api_tests/test_signatures.py::test_func_signature[nextafter] +array_api_tests/test_signatures.py::test_func_signature[hypot] +array_api_tests/test_signatures.py::test_func_signature[copysign] +array_api_tests/test_signatures.py::test_func_signature[nonzero] +array_api_tests/test_signatures.py::test_func_signature[isin] +array_api_tests/test_signatures.py::test_func_signature[unique_all] +array_api_tests/test_signatures.py::test_func_signature[unique_counts] +array_api_tests/test_signatures.py::test_func_signature[unique_inverse] +array_api_tests/test_signatures.py::test_func_signature[unique_values] + +## Missing arguments +### Missing argument `include_initial` +array_api_tests/test_signatures.py::test_func_signature[cumulative_sum] +### Missing argument `include_initial` +array_api_tests/test_signatures.py::test_func_signature[cumulative_prod] +### Missing argument `dtype` +array_api_tests/test_signatures.py::test_func_signature[prod] +### Missing argument `correction` +array_api_tests/test_signatures.py::test_func_signature[std] +### Missing argument `dtype` +array_api_tests/test_signatures.py::test_func_signature[sum] +### Missing argument `correction` +array_api_tests/test_signatures.py::test_func_signature[var] +### Missing argument `sorter` +array_api_tests/test_signatures.py::test_func_signature[searchsorted] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[asarray] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[empty_like] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[from_dlpack] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[full_like] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[ones_like] +### Missing argument `device` +array_api_tests/test_signatures.py::test_func_signature[zeros_like] +### Missing arguments `prepend` `append` +array_api_tests/test_signatures.py::test_func_signature[diff] +### rejects an integer `axes` argument +array_api_tests/test_signatures.py::test_func_signature[permute_dims] +### Missing argument `copy` +array_api_tests/test_signatures.py::test_func_signature[reshape] +### Missing arguments `descending` `stable` +array_api_tests/test_signatures.py::test_func_signature[argsort] +### Missing arguments `descending` `stable` +array_api_tests/test_signatures.py::test_func_signature[sort] +### Missing `min` argument +array_api_tests/test_signatures.py::test_func_signature[clip] + + +# test_operators_and_elementwise_functions.py +## Missing functions +array_api_tests/test_operators_and_elementwise_functions.py::test_copysign +array_api_tests/test_operators_and_elementwise_functions.py::test_hypot +array_api_tests/test_operators_and_elementwise_functions.py::test_nextafter +array_api_tests/test_operators_and_elementwise_functions.py::test_signbit +array_api_tests/test_operators_and_elementwise_functions.py::test_binary_with_scalars_real[nextafter] +array_api_tests/test_operators_and_elementwise_functions.py::test_binary_with_scalars_real[hypot] +array_api_tests/test_operators_and_elementwise_functions.py::test_binary_with_scalars_real[copysign] + +## Missing complex kernels +array_api_tests/test_operators_and_elementwise_functions.py::test_acosh +array_api_tests/test_operators_and_elementwise_functions.py::test_asinh +array_api_tests/test_operators_and_elementwise_functions.py::test_atanh +array_api_tests/test_operators_and_elementwise_functions.py::test_expm1 + +## Missing arguments +### edge case +array_api_tests/test_operators_and_elementwise_functions.py::test_clip + +## Loss of precision in the complex plane +array_api_tests/test_operators_and_elementwise_functions.py::test_acos +array_api_tests/test_operators_and_elementwise_functions.py::test_asin +array_api_tests/test_operators_and_elementwise_functions.py::test_atan + +## Other failures +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_bitwise_left_shift[bitwise_left_shift(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_bitwise_left_shift[__lshift__(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_bitwise_left_shift[__ilshift__(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_bitwise_right_shift[__rshift__(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_bitwise_right_shift[__irshift__(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_divide[divide(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_divide[__truediv__(x1, x2)] +### wraps shift counts instead of returning zero for shifts >= the integer width +array_api_tests/test_operators_and_elementwise_functions.py::test_divide[__itruediv__(x1, x2)] +### truncates toward zero instead of flooring negative results +array_api_tests/test_operators_and_elementwise_functions.py::test_log1p +### does not accept a scalar argument +array_api_tests/test_operators_and_elementwise_functions.py::test_binary_with_scalars_real[atan2] + +# test_inspection_functions.py +## Missing arguments +### Missing argument `device` +array_api_tests/test_inspection_functions.py::test_array_namespace_info_dtypes + +## Other failures +### Missing attribute '__array_api_version__' +array_api_tests/test_inspection_functions.py::TestInspection::test_capabilities + +# test_statistical_functions.py +## Missing arguments +### Missing argument `correction` +array_api_tests/test_statistical_functions.py::test_std +### Missing argument `correction` +array_api_tests/test_statistical_functions.py::test_var +### Missing argument `include_initial` and does not promote uint8 results to uint32 +array_api_tests/test_statistical_functions.py::test_cumulative_sum +### Missing argument `include_initial` and does not promote uint8 results to uint32 +array_api_tests/test_statistical_functions.py::test_cumulative_prod +### Missing argument `include_initial` and does not promote uint8 results to uint32 +array_api_tests/test_statistical_functions.py::test_prod +### Missing argument `include_initial` and does not promote uint8 results to uint32 +array_api_tests/test_statistical_functions.py::test_sum + +# test_manipulation_functions.py +## Missing arguments +### Missing argument `copy` +array_api_tests/test_manipulation_functions.py::test_reshape + +## Other failures +### `repeats` only accepts int +array_api_tests/test_manipulation_functions.py::test_repeat +### `source` `destination` only accepts ints +array_api_tests/test_manipulation_functions.py::test_moveaxis + +# test_data_type_functions.py +## Missing arguments +### Missing argument `copy` +array_api_tests/test_data_type_functions.py::test_astype +### +array_api_tests/test_data_type_functions.py::test_can_cast +### +array_api_tests/test_data_type_functions.py::test_finfo[dtype0] +### +array_api_tests/test_data_type_functions.py::test_finfo[dtype1] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype0] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype1] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype2] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype3] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype4] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype5] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype6] +### Missing attribute `bits` +array_api_tests/test_data_type_functions.py::test_iinfo[dtype7] + +## Other failures +### MLX result_type() does not accept Python scalar values alongside dtypes +array_api_tests/test_data_type_functions.py::TestResultType::test_with_scalars +### MLX broadcast_shapes() requires at least one shape +array_api_tests/test_data_type_functions.py::TestBroadcastShapes::test_empty + + +# test_searching_functions.py +## Missing arguments +### Missing argument `sorter` +array_api_tests/test_searching_functions.py::test_searchsorted +### Missing argument `sorter` +array_api_tests/test_searching_functions.py::test_searchsorted_with_scalars + +## Other failures +### returns uint32 indices instead of the required default signed integer dtype +array_api_tests/test_searching_functions.py::test_argmax +### returns uint32 indices instead of the required default signed integer dtype +array_api_tests/test_searching_functions.py::test_argmin + +# test_utility_functions.py +## Misisng arguments +### Missing argument `append` `prepend` +array_api_tests/test_utility_functions.py::test_diff_append_prepend +## Other failures +### AssertionError: out=False, but should be True [any()] +array_api_tests/test_utility_functions.py::test_any + +# test_creation_functions.py +## Other failures +### copy=False is not supported, https://github.com/ml-explore/mlx/pull/4036 +array_api_tests/test_creation_functions.py::test_asarray_arrays + +# test_dlpack.py +## Other failures +array_api_tests/test_dlpack.py::test_from_dlpack + +# test_sorting_functions.py +## Missing attributes +### Missing attribute `stable` +array_api_tests/test_sorting_functions.py::test_argsort +### Missing attribute `stable` +array_api_tests/test_sorting_functions.py::test_sort + +# test_special_cases.py +## Special cases +array_api_tests/test_special_cases.py::test_unary[expm1((real(x_i) is +0 or real(x_i) == -0) and imag(x_i) is +0) -> 0 + 0j] +array_api_tests/test_special_cases.py::test_unary[expm1(isfinite(real(x_i)) and imag(x_i) is +infinity) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[expm1(isfinite(real(x_i)) and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is +infinity and imag(x_i) is +0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is -infinity and imag(x_i) is +infinity) -> -1 + 0j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is +infinity and imag(x_i) is +infinity) -> infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is -infinity and imag(x_i) is NaN) -> -1 + 0j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is +infinity and imag(x_i) is NaN) -> infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is NaN and imag(x_i) is +0) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is NaN and not imag(x_i) == 0) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[expm1(real(x_i) is NaN and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[log1p((real(x_i) is +infinity or real(x_i) == -infinity) and imag(x_i) is NaN) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[log1p(real(x_i) is NaN and imag(x_i) is +infinity) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[sign(x_i is NaN) -> NaN] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is +0) -> False] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is -0) -> True] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is +infinity) -> False] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is -infinity) -> True] +array_api_tests/test_special_cases.py::test_unary[signbit(isfinite(x_i) and x_i > 0) -> False] +array_api_tests/test_special_cases.py::test_unary[signbit(isfinite(x_i) and x_i < 0) -> True] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is +NaN) -> False] +array_api_tests/test_special_cases.py::test_unary[signbit(x_i is -NaN) -> True] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is +0 and imag(x_i) is +infinity) -> 0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is +0 and imag(x_i) is NaN) -> 0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is +infinity and imag(x_i) is +0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is +infinity and imag(x_i) is +infinity) -> infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is +infinity and imag(x_i) is NaN) -> infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[sinh(real(x_i) is NaN and imag(x_i) is +0) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[sqrt(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +infinity + 0 j] +array_api_tests/test_special_cases.py::test_unary[tanh(real(x_i) is +0 and imag(x_i) is +infinity) -> +0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[tanh(real(x_i) is +0 and imag(x_i) is NaN) -> +0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[tanh(real(x_i) is +infinity and imag(x_i) is +infinity) -> 1 + 0j] +array_api_tests/test_special_cases.py::test_unary[tanh(real(x_i) is +infinity and imag(x_i) is NaN) -> 1 + 0j] +array_api_tests/test_special_cases.py::test_unary[tanh(real(x_i) is NaN and imag(x_i) is +0) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_binary[copysign(x1_i is NaN and x2_i < 0) -> NaN] +array_api_tests/test_special_cases.py::test_binary[copysign(x1_i is NaN and x2_i is -0) -> NaN] +array_api_tests/test_special_cases.py::test_binary[copysign(x1_i is NaN and x2_i is +0) -> NaN] +array_api_tests/test_special_cases.py::test_binary[copysign(x1_i is NaN and x2_i > 0) -> NaN] +array_api_tests/test_special_cases.py::test_binary[nextafter(x1_i is NaN or x2_i is NaN) -> NaN] +array_api_tests/test_special_cases.py::test_binary[nextafter(x1_i is -0 and x2_i is +0) -> +0] +array_api_tests/test_special_cases.py::test_binary[nextafter(x1_i is +0 and x2_i is -0) -> -0] +array_api_tests/test_special_cases.py::test_binary[remainder(x1_i is -0 and x2_i > 0) -> +0] +array_api_tests/test_special_cases.py::test_binary[remainder(x1_i is +0 and x2_i < 0) -> -0] +array_api_tests/test_special_cases.py::test_binary[__mod__(x1_i is -0 and x2_i > 0) -> +0] +array_api_tests/test_special_cases.py::test_binary[__mod__(x1_i is +0 and x2_i < 0) -> -0] +array_api_tests/test_special_cases.py::test_iop[__imod__(x1_i is -0 and x2_i > 0) -> +0] +array_api_tests/test_special_cases.py::test_iop[__imod__(x1_i is +0 and x2_i < 0) -> -0] +array_api_tests/test_special_cases.py::test_unary[acos((real(x_i) is +0 or real(x_i) == -0) and imag(x_i) is NaN) -> \u03c0/2 + NaN j] +array_api_tests/test_special_cases.py::test_unary[acos(isfinite(real(x_i)) and imag(x_i) is +infinity) -> \u03c0/2] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is -infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> \u03c0] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +0] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is -infinity and imag(x_i) is +infinity) -> 3\u03c0/4] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is +infinity and imag(x_i) is +infinity) -> \u03c0/4] +array_api_tests/test_special_cases.py::test_unary[acos((real(x_i) is +infinity or real(x_i) == -infinity) and imag(x_i) is NaN) -> NaN \u00b1 infinity j] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is NaN and imag(x_i) is +infinity) -> NaN] +array_api_tests/test_special_cases.py::test_unary[acosh((real(x_i) is +0 or real(x_i) == -0) and imag(x_i) is +0) -> +0 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[acosh(isfinite(real(x_i)) and imag(x_i) is +infinity) -> +infinity + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[acosh(isfinite(real(x_i)) and real(x_i) != 0 and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is +0 and imag(x_i) is NaN) -> NaN \u00b1 \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is -infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +infinity + \u03c0j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is -infinity and imag(x_i) is +infinity) -> +infinity + 3\u03c0j/4] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is +infinity and imag(x_i) is +infinity) -> +infinity + \u03c0j/4] +array_api_tests/test_special_cases.py::test_unary[acosh((real(x_i) is +infinity or real(x_i) == -infinity) and imag(x_i) is NaN) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is NaN and isfinite(imag(x_i))) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is NaN and imag(x_i) is +infinity) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is NaN and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is +0 and imag(x_i) is +0) -> +0 + 0j] +array_api_tests/test_special_cases.py::test_unary[asinh(isfinite(real(x_i)) and real(x_i) > 0 and imag(x_i) is +infinity) -> +infinity + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[asinh(isfinite(real(x_i)) and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is +infinity and imag(x_i) is +infinity) -> +infinity + \u03c0j/4] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is NaN and imag(x_i) is +0) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is NaN and isfinite(imag(x_i)) and imag(x_i) != 0) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is NaN and imag(x_i) is +infinity) -> \u00b1infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is NaN and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[atan(x_i is -0) -> -0] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is +0 and imag(x_i) is +0) -> +0 + 0j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is +0 and imag(x_i) is NaN) -> +0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is 1 and imag(x_i) is +0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[atanh(isfinite(real(x_i)) and real(x_i) > 0 and imag(x_i) is +infinity) -> +0 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[atanh(isfinite(real(x_i)) and real(x_i) != 0 and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +0 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is +infinity and imag(x_i) is +infinity) -> +0 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is +infinity and imag(x_i) is NaN) -> +0 + NaN j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is NaN and isfinite(imag(x_i))) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is NaN and imag(x_i) is +infinity) -> \u00b10 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is NaN and imag(x_i) is NaN) -> NaN + NaN j] +array_api_tests/test_special_cases.py::test_unary[clip(x_i is NaN) -> NaN] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is +0 and imag(x_i) is +infinity) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is +0 and imag(x_i) is NaN) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is +infinity and imag(x_i) is +0) -> +infinity + 0j] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is +infinity and imag(x_i) is +infinity) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is +infinity and imag(x_i) is NaN) -> +infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[cosh(real(x_i) is NaN and (imag(x_i) is +0 or imag(x_i) == -0)) -> NaN + 0j] +array_api_tests/test_special_cases.py::test_unary[acos((real(x_i) is +infinity or real(x_i) == -infinity) and imag(x_i) is NaN) -> NaN \xb1 infinity j] +array_api_tests/test_special_cases.py::test_unary[acosh(real(x_i) is +0 and imag(x_i) is NaN) -> NaN \xb1 \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is +infinity and imag(x_i) is +infinity) -> \u03c0/4 - infinity j] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is -infinity and imag(x_i) is +infinity) -> 3\u03c0/4 - infinity j] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is NaN and imag(x_i) is +infinity) -> NaN - infinity j] +array_api_tests/test_special_cases.py::test_unary[asinh(real(x_i) is NaN and imag(x_i) is +infinity) -> \xb1infinity + NaN j] +array_api_tests/test_special_cases.py::test_unary[atanh(real(x_i) is NaN and imag(x_i) is +infinity) -> \xb10 + \u03c0j/2] +array_api_tests/test_special_cases.py::test_unary[acos(isfinite(real(x_i)) and imag(x_i) is +infinity) -> \u03c0/2 - infinity j] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is -infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> \u03c0 - infinity j] +array_api_tests/test_special_cases.py::test_unary[acos(real(x_i) is +infinity and isfinite(imag(x_i)) and imag(x_i) > 0) -> +0 - infinity j] +array_api_tests/test_special_cases.py::test_unary[sign((real(x_i) is -0 or real(x_i) == +0) and (imag(x_i) is -0 or imag(x_i) == +0)) -> 0 + 0j] +array_api_tests/test_special_cases.py::test_unary[ceil(x_i.is_integer()) -> x_i] +array_api_tests/test_special_cases.py::test_unary[floor(x_i.is_integer()) -> x_i] +array_api_tests/test_special_cases.py::test_unary[round(x_i.is_integer()) -> x_i] +array_api_tests/test_special_cases.py::test_unary[trunc(x_i.is_integer()) -> x_i] diff --git a/scripts/check_forkdiff.py b/scripts/check_forkdiff.py index 91ae6abe47..2ff1210829 100644 --- a/scripts/check_forkdiff.py +++ b/scripts/check_forkdiff.py @@ -153,8 +153,8 @@ def check_base(repo: Path, base: str, head: str, upstream_ref: str | None) -> li git("merge-base", "--is-ancestor", base, upstream_ref, cwd=repo) except RuntimeError: problems.append( - f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must name " - "a commit on upstream main, not a fork commit." + f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must " + "name a commit on upstream main, not a fork commit." ) merge_base = git("merge-base", head, upstream_ref, cwd=repo) if merge_base != base: @@ -183,10 +183,11 @@ def review_status(problems: list[str], detail: str) -> list[dict]: ), "detail": detail, "how_to_fix": ( - "See docs/forkdiff.md. After a rebase: set base.hash to " - "`git merge-base HEAD upstream/main`. For new files: add them to " - "the section that explains them (or to a global `ignore` if they " - "are not code). Then run `python3 scripts/check_forkdiff.py " + "See FORKDIFF.md. After an upstream merge: set base.hash " + "to `git merge-base HEAD upstream/main`. For new files: add " + "them to the section that explains them (or to a global " + "`ignore` if they are not code). Then run " + "`python3 scripts/check_forkdiff.py " "--upstream-ref upstream/main` locally." ), } @@ -233,7 +234,8 @@ def main(argv: list[str] | None = None) -> int: uncovered, stale, hits = check_coverage(paths, globs) if uncovered: problems.append( - f"{len(uncovered)} changed file(s) are not described by any fork.yaml section" + f"{len(uncovered)} changed file(s) are not described by any fork.yaml " + "section" ) lines.append("Uncovered files (add each to the section that explains it):") lines += [f" - {p}" for p in uncovered] diff --git a/setup.py b/setup.py index 52cc4f7492..72cf59668e 100644 --- a/setup.py +++ b/setup.py @@ -25,13 +25,13 @@ def cuda_toolkit_major_version(): def get_version(): with open("mlx/version.h", "r") as fid: - for l in fid: - if "#define MLX_VERSION_MAJOR" in l: - major = l.split()[-1] - if "#define MLX_VERSION_MINOR" in l: - minor = l.split()[-1] - if "#define MLX_VERSION_PATCH" in l: - patch = l.split()[-1] + for line in fid: + if "#define MLX_VERSION_MAJOR" in line: + major = line.split()[-1] + if "#define MLX_VERSION_MINOR" in line: + minor = line.split()[-1] + if "#define MLX_VERSION_PATCH" in line: + patch = line.split()[-1] version = f"{major}.{minor}.{patch}" pypi_release = int(os.environ.get("PYPI_RELEASE", 0)) dev_release = int(os.environ.get("DEV_RELEASE", 0)) @@ -57,7 +57,8 @@ def get_version(): # # Frontend package: # - Triggered with `MLX_BUILD_FRONTEND_PACKAGE=1` -# - Include everything except backend-specific binaries (e.g. libmlx.so, mlx.metallib, etc) +# - Include everything except backend-specific binaries (e.g. libmlx.so, mlx.metallib, +# etc) # - Wheel has Python ABI and platform tags # - Wheel should be built for the cross-product of python version and platforms # - Package name is "mlx" and it depends on backend packages (e.g. mlx-metal, mlx-cuda) @@ -339,6 +340,7 @@ def is_backend_file(file): "nvidia-cublas-cu12==12.9.*", "nvidia-cufft-cu12==11.4.*", "nvidia-cuda-nvrtc-cu12==12.9.*", + "nvidia-cusolver-cu12==11.7.*", ] elif toolkit == 13: install_requires += [ @@ -346,6 +348,7 @@ def is_backend_file(file): "nvidia-cufft==12.*", "nvidia-cuda-nvrtc==13.*", "nvidia-cuda-runtime==13.*", + "nvidia-cusolver==12.*", ] else: raise ValueError(f"Unknown toolkit {toolkit}") diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c80d20c1e3..dcfe8b42c5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,11 +7,16 @@ FetchContent_MakeAvailable(doctest) add_executable(tests ${PROJECT_SOURCE_DIR}/tests/tests.cpp) if(MLX_BUILD_METAL OR MLX_BUILD_CUDA) - set(METAL_TEST_SOURCES gpu_tests.cpp) + set(GPU_TEST_SOURCES gpu_tests.cpp) +endif() + +if(MLX_BUILD_CUDA) + list(APPEND GPU_TEST_SOURCES cuda_tests.cpp) + target_link_libraries(tests PRIVATE CUDA::cudart) endif() if(MLX_BUILD_METAL) - list(APPEND METAL_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp) + list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp) endif() include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) @@ -38,7 +43,7 @@ target_sources( utils_tests.cpp vmap_tests.cpp linalg_tests.cpp - ${METAL_TEST_SOURCES}) + ${GPU_TEST_SOURCES}) target_link_libraries(tests PRIVATE mlx doctest) target_compile_options(tests PRIVATE ${SANITIZER_COMPILE_FLAGS}) diff --git a/tests/allocator_tests.cpp b/tests/allocator_tests.cpp index bab64689bc..5d46c9f228 100644 --- a/tests/allocator_tests.cpp +++ b/tests/allocator_tests.cpp @@ -13,40 +13,42 @@ #include "mlx/allocator.h" #include "mlx/device.h" #include "mlx/memory.h" +#include "mlx/ops.h" #include "mlx/scheduler.h" #include "mlx/stream.h" +#include "mlx/transforms.h" using namespace mlx::core; TEST_CASE("test simple allocations") { { - auto buffer = allocator::malloc(sizeof(float)); + auto buffer = allocator::allocator().malloc(sizeof(float)); auto fptr = static_cast(buffer.raw_ptr()); *fptr = 0.5f; CHECK_EQ(*fptr, 0.5f); - allocator::free(buffer); + allocator::allocator().free(buffer); } { - auto buffer = allocator::malloc(128 * sizeof(int)); + auto buffer = allocator::allocator().malloc(128 * sizeof(int)); int* ptr = static_cast(buffer.raw_ptr()); for (int i = 0; i < 128; ++i) { ptr[i] = i; } - allocator::free(buffer); + allocator::allocator().free(buffer); } { - auto buffer = allocator::malloc(0); - allocator::free(buffer); + auto buffer = allocator::allocator().malloc(0); + allocator::allocator().free(buffer); } } TEST_CASE("test large allocations") { size_t size = 1 << 30; for (int i = 0; i < 100; ++i) { - auto buffer = allocator::malloc(size); - allocator::free(buffer); + auto buffer = allocator::allocator().malloc(size); + allocator::allocator().free(buffer); } } @@ -54,20 +56,38 @@ TEST_CASE("test cached allocation keeps capacity") { auto old_limit = set_cache_limit(1 << 20); clear_cache(); - auto large = allocator::malloc(8192); - allocator::free(large); + auto large = allocator::allocator().malloc(8192); + allocator::allocator().free(large); auto cached = get_cache_memory(); CHECK_GE(cached, 8192); - auto small = allocator::malloc(6000); + auto small = allocator::allocator().malloc(6000); CHECK_GE(allocator::allocator().size(small), cached); - allocator::free(small); + allocator::allocator().free(small); CHECK_GE(get_cache_memory(), cached); clear_cache(); set_cache_limit(old_limit); } +TEST_CASE("test array buffer size") { + auto a = array({1.0f, 2.0f, 3.0f, 4.0f}); + auto view = reshape(a, {2, 2}); + + CHECK_THROWS_AS(get_array_buffer_size({view}), std::invalid_argument); + + eval(view); + auto a_size = a.buffer_size(); + CHECK_EQ(get_array_buffer_size({}), 0); + CHECK_EQ(get_array_buffer_size({a}), a_size); + CHECK_EQ(get_array_buffer_size({a, a}), a_size); + CHECK_EQ(get_array_buffer_size({a, view}), a_size); + + auto b = array({5.0f, 6.0f}); + CHECK_EQ(get_array_buffer_size({a, b}), a_size + b.buffer_size()); + CHECK_EQ(get_array_buffer_size({array({})}), 0); +} + TEST_CASE("test clear cache synchronizes cpu streams") { if (is_available(Device{Device::gpu})) { return; @@ -76,8 +96,8 @@ TEST_CASE("test clear cache synchronizes cpu streams") { auto old_limit = set_cache_limit(1 << 20); clear_cache(); - auto cached = allocator::malloc(8192); - allocator::free(cached); + auto cached = allocator::allocator().malloc(8192); + allocator::allocator().free(cached); CHECK_GE(get_cache_memory(), 8192); auto task_started = std::make_shared>(); @@ -124,11 +144,11 @@ TEST_CASE("test clear cache synchronizes cpu streams") { TEST_CASE("test coherent memory snapshot during cache transfers") { auto old_limit = set_cache_limit(1 << 20); clear_cache(); - auto live = allocator::malloc(32768); - auto moving = allocator::malloc(65536); + auto live = allocator::allocator().malloc(32768); + auto moving = allocator::allocator().malloc(65536); auto moving_bytes = allocator::allocator().size(moving); auto active = get_memory_snapshot(); - allocator::free(moving); + allocator::allocator().free(moving); auto cached = get_memory_snapshot(); CHECK_EQ(active.active_memory, cached.active_memory + moving_bytes); CHECK_EQ(active.cache_memory + moving_bytes, cached.cache_memory); @@ -142,8 +162,8 @@ TEST_CASE("test coherent memory snapshot during cache transfers") { started.set_value(); size_t transfers = 0; do { - auto buffer = allocator::malloc(65536); - allocator::free(buffer); + auto buffer = allocator::allocator().malloc(65536); + allocator::allocator().free(buffer); ++transfers; } while (!stop.load(std::memory_order_relaxed)); return transfers; @@ -160,7 +180,7 @@ TEST_CASE("test coherent memory snapshot during cache transfers") { CHECK_GT(churn.get(), 0); CHECK_EQ(inconsistent, 0); - allocator::free(live); + allocator::allocator().free(live); clear_cache(); set_cache_limit(old_limit); } @@ -192,20 +212,20 @@ TEST_CASE("allocation footprint bounds fresh and cached buffer owners") { for (size_t size : {size_t(4), size_t(6000), size_t(24576), size_t(65536)}) { auto bound = get_allocation_size_upper_bound(size); CHECK_GE(bound, size); - auto buffer = allocator::malloc(size); + auto buffer = allocator::allocator().malloc(size); CHECK_LE(allocator::allocator().size(buffer), bound); - allocator::free(buffer); + allocator::allocator().free(buffer); } clear_cache(); - auto large = allocator::malloc(49152); + auto large = allocator::allocator().malloc(49152); auto larger_bytes = allocator::allocator().size(large); - allocator::free(large); - auto reused = allocator::malloc(32768); + allocator::allocator().free(large); + auto reused = allocator::allocator().malloc(32768); CHECK_LE( allocator::allocator().size(reused), get_allocation_size_upper_bound(32768)); CHECK_GE(larger_bytes, 49152); - allocator::free(reused); + allocator::allocator().free(reused); clear_cache(); set_cache_limit(old_limit); } diff --git a/tests/arg_reduce_tests.cpp b/tests/arg_reduce_tests.cpp index 124fd67ede..6bcce81bdb 100644 --- a/tests/arg_reduce_tests.cpp +++ b/tests/arg_reduce_tests.cpp @@ -1,5 +1,7 @@ // Copyright © 2023 Apple Inc. +#include + #include "doctest/doctest.h" #include "mlx/mlx.h" @@ -187,6 +189,27 @@ TEST_CASE("test arg reduce edge cases") { CHECK_THROWS(argmax(array({}))); } +TEST_CASE("test arg reduce NaN") { + auto d = default_device(); + auto nan = std::numeric_limits::quiet_NaN(); + auto x = array({3.0f, nan, 1.0f, 5.0f, nan, -1.0f}, {2, 3}); + test_arg_reduce_small(d, x, ArgReduce::ArgMin, {2}, 1, {1, 1}); + test_arg_reduce_small(d, x, ArgReduce::ArgMax, {2}, 1, {1, 1}); + + std::vector wide(1024, 0.0f); + wide[17] = nan; + wide[529] = nan; + x = array(wide.data(), {1024}); + test_arg_reduce_small(d, x, ArgReduce::ArgMin, {}, 0, {17}); + test_arg_reduce_small(d, x, ArgReduce::ArgMax, {}, 0, {17}); + + if (d == Device::cpu) { + auto z = array({complex64_t{1.0f, 0.0f}, complex64_t{1.0f, nan}}, {2}); + test_arg_reduce_small(d, z, ArgReduce::ArgMin, {}, 0, {1}); + test_arg_reduce_small(d, z, ArgReduce::ArgMax, {}, 0, {1}); + } +} + TEST_CASE("test arg reduce irregular strides") { auto x = array( {0, 2, 1, 7, 5, -5, 0, 2, 1, 7, 5, -5, diff --git a/tests/array_tests.cpp b/tests/array_tests.cpp index 68a4bed3a8..f126ce3276 100644 --- a/tests/array_tests.cpp +++ b/tests/array_tests.cpp @@ -1,6 +1,7 @@ // Copyright © 2023 Apple Inc. #include #include +#include #include #include @@ -581,7 +582,8 @@ TEST_CASE("test array shared buffer") { Shape shape = {2, 2}; auto n_elem = shape[0] * shape[1]; - allocator::Buffer buf_b = allocator::malloc(n_elem * sizeof(float)); + allocator::Buffer buf_b = + allocator::allocator().malloc(n_elem * sizeof(float)); void* buf_b_ptr = buf_b.raw_ptr(); float* float_buf_b = (float*)buf_b_ptr; @@ -594,11 +596,11 @@ TEST_CASE("test array shared buffer") { auto deleter = [float_buf_b](allocator::Buffer buf) { CHECK_EQ(float_buf_b, (float*)buf.raw_ptr()); CHECK_EQ(float_buf_b[0], ((float*)buf.raw_ptr())[0]); - allocator::free(buf); + allocator::allocator().free(buf); }; array a = ones(shape, float32); - array b = array(buf_b, shape, float32, deleter); + array b = array(allocator::Data(buf_b, deleter), shape, float32); eval(a + b); } @@ -647,6 +649,19 @@ TEST_CASE("test make array from user buffer") { CHECK_EQ(count, 1); } +TEST_CASE("test user buffer is not donated") { + int size = 4096; + std::vector buffer(size, 1.0f); + auto out = exp(array(buffer.data(), Shape{size}, float32, [](void*) {})); + eval(out); + CHECK_EQ(buffer[0], 1.0f); +} + +TEST_CASE("test null deleter is not owned") { + allocator::Data data(allocator::Buffer(nullptr), nullptr); + CHECK_FALSE(data.is_owned()); +} + TEST_CASE("test negative indexing for shape/strides") { // 2D array: shape = {2, 3} std::vector data(6, 1.0f); @@ -690,3 +705,76 @@ TEST_CASE("test siblings circular references without eval") { fun(); CHECK(tracker.expired()); } + +// https://github.com/ml-explore/mlx/pull/4453 +TEST_CASE("test siblings circular references released by assignment") { + std::weak_ptr tracker; + auto fun = [&]() { + array sink({3, 4}); + array key({1, 2}); + auto splits = split(key, 2); + { + // Set fake data as a tracker for ArrayDesc's lifetime. + splits[0].set_data(allocator::malloc(0)); + tracker = splits[0].data_shared_ptr(); + } + // Drop both outputs by assigning over them rather than destroying + // them. The siblings hold each other, so unless assignment runs the + // same check the destructor does, nothing ever releases them. + splits[0] = sink; // copy assignment + splits[1] = array({5, 6}); // move assignment + }; + fun(); + CHECK(tracker.expired()); +} + +TEST_CASE("test siblings circular references released by overwrite") { + std::weak_ptr tracker; + auto fun = [&]() { + array key({1, 2}); + auto splits = split(key, 2); + { + // Set fake data as a tracker for ArrayDesc's lifetime. + splits[0].set_data(allocator::malloc(0)); + tracker = splits[0].data_shared_ptr(); + } + // Leave one output as the last reference, then replace it in place. + // This is the path __setitem__ takes, with no compile involved. + array last = splits[0]; + splits.clear(); + last.overwrite_descriptor(array({7, 8})); + }; + fun(); + CHECK(tracker.expired()); +} + +TEST_CASE("test assigning a sibling over the last reference keeps the cycle") { + array key({1, 2}); + auto splits = split(key, 2); + // Leave one output as the last outside reference to the pair, then assign + // its sibling over it. The sibling is reachable only through the array + // being replaced, so it has to be held before the old descriptor is + // checked: checked first, the pair looks unreferenced, its cycle is broken + // and the sibling list the new value lives in is freed before it is read. + array last = splits[0]; + splits.clear(); + last = last.siblings()[0]; + REQUIRE_EQ(last.siblings().size(), 1); + CHECK(array_equal(last, array({2})).item()); +} + +TEST_CASE("test unaligned scalar item") { + uint64_t expected = 0x0123456789abcdef; + for (size_t offset = 1; offset < sizeof(expected); ++offset) { + std::vector data(offset + sizeof(expected)); + std::memcpy(data.data() + offset, &expected, sizeof(expected)); + auto storage = array(data.data(), {static_cast(data.size())}, uint8); + auto scalar = view(as_strided(storage, {8}, {1}, offset), uint64); + eval(scalar); + if (default_device() == Device::cpu) { + CHECK_EQ(scalar.data(), storage.data() + offset); + } + CHECK_EQ(scalar.item(), expected); + CHECK_EQ(static_cast(scalar).item(), expected); + } +} diff --git a/tests/autograd_tests.cpp b/tests/autograd_tests.cpp index 5a0aca0800..2aa2dc441b 100644 --- a/tests/autograd_tests.cpp +++ b/tests/autograd_tests.cpp @@ -749,7 +749,7 @@ TEST_CASE("test op vjps") { TEST_CASE("test gather and take grads") { // Check linear takes auto linear_f = [](array indices) { - auto fun_linear = [&indices](array input) { return take(input, indices); }; + auto fun_linear = [indices](array input) { return take(input, indices); }; return fun_linear; }; @@ -1111,6 +1111,14 @@ TEST_CASE("test as_strided grads") { out = vjp(fun, x, reshape(astype(arange(9), x.dtype()), {3, 3})).second; expected = array({0, 0, 0, 9, 12, 15, 0, 0, 0, 0, 0}); CHECK(array_equal(out, expected).item()); + + x = transpose(reshape(arange(12, float32), {3, 4})); + out = vjp(fun, x, ones(shape)).second; + expected = reshape(array({0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0}), x.shape()); + CHECK(array_equal(out, expected).item()); + + out = jvp(fun, x, x).second; + CHECK(array_equal(out, fun(x)).item()); } TEST_CASE("test jvp from vjp") { @@ -1532,3 +1540,89 @@ TEST_CASE("test masked_scatter autograd") { CHECK(array_equal(grads[1], array({1.f, 1.f}, {2})).item()); } } + +TEST_CASE("test pad vjp with axes subset and negative axes") { + // Pad only the last axis, given as a negative index + { + auto x = ones({2, 3}); + auto fun = [](array in) { + return pad(in, {-1}, {1}, {2}, array(0), "constant"); + }; + auto cotan = reshape(arange(12), {2, 6}); + auto [out, dout] = vjp(fun, x, cotan); + CHECK_EQ(out.shape(), Shape{2, 6}); + CHECK_EQ(dout.shape(), Shape{2, 3}); + auto expected = slice(cotan, {0, 1}, {2, 4}); + CHECK(array_equal(dout, expected).item()); + } + + // Pad sizes must be matched with axes by position, not by axis value + { + auto x = ones({2, 3}); + auto fun = [](array in) { + return pad(in, {1, 0}, {1, 2}, {3, 0}, array(0), "constant"); + }; + auto cotan = reshape(arange(28), {4, 7}); + auto [out, dout] = vjp(fun, x, cotan); + CHECK_EQ(out.shape(), Shape{4, 7}); + CHECK_EQ(dout.shape(), Shape{2, 3}); + auto expected = slice(cotan, {2, 1}, {4, 4}); + CHECK(array_equal(dout, expected).item()); + } +} + +TEST_CASE("test pad vjp and jvp with the pad value") { + auto x = reshape(arange(6.f), {2, 3}); + auto v = array(2.f); + auto pad_fn = [](const array& a, const array& value) { + return pad(a, {0, 1}, {1, 2}, {1, 2}, value, "constant"); + }; + + // Padded sum of the cotangent: 406 - 87 = 319 + auto cotan = reshape(arange(1.f, 29.f), {4, 7}); + auto interior = slice(cotan, {1, 2}, {3, 5}); + auto loss = [&](const std::vector& in) { + return std::vector{sum(multiply(pad_fn(in[0], in[1]), cotan))}; + }; + auto grads = [&](std::vector argnums, const array& value) { + return value_and_grad(loss, argnums)({x, value}).second; + }; + + auto g0 = grads({0}, v); + CHECK_EQ(g0.size(), 1); + CHECK(array_equal(g0[0], interior).item()); + + auto g1 = grads({1}, v); + CHECK_EQ(g1.size(), 1); + CHECK_EQ(g1[0].shape(), Shape{}); + CHECK_EQ(g1[0].item(), 319.0f); + + auto g01 = grads({0, 1}, v); + CHECK_EQ(g01.size(), 2); + CHECK(array_equal(g01[0], interior).item()); + CHECK_EQ(g01[1].item(), 319.0f); + + auto g1_vec = grads({1}, array({2.f}, {1})); + CHECK_EQ(g1_vec[0].shape(), Shape{1}); + CHECK_EQ(g1_vec[0].item(), 319.0f); + + // Padded elements: 1000 * 1000 - 998 * 998 = 3996 + auto big_loss = [](const std::vector& in) { + return std::vector{sum(pad(in[0], 1, in[1]))}; + }; + auto big_fn = value_and_grad(big_loss, std::vector{1}); + auto big_grads = big_fn({zeros({998, 998}, bfloat16), array(2.f, bfloat16)}); + CHECK(allclose(big_grads.second[0], array(3996.f), 1e-2, 0).item()); + + auto tx = reshape(arange(10.f, 16.f), {2, 3}); + auto tv = array(5.f); + auto dx = jvp([&](const array& a) { return pad_fn(a, v); }, x, tx).second; + CHECK(array_equal(dx, pad_fn(tx, array(0.f))).item()); + auto dv = jvp([&](const array& a) { return pad_fn(x, a); }, v, tv).second; + CHECK(array_equal(dv, pad_fn(zeros_like(x), tv)).item()); + auto fun = [&](const std::vector& in) { + return std::vector{pad_fn(in[0], in[1])}; + }; + auto dboth = jvp(fun, {x, v}, {tx, tv}).second; + CHECK(array_equal(dboth[0], pad_fn(tx, tv)).item()); +} diff --git a/tests/cuda_tests.cpp b/tests/cuda_tests.cpp new file mode 100644 index 0000000000..9afa980cd7 --- /dev/null +++ b/tests/cuda_tests.cpp @@ -0,0 +1,121 @@ +// Copyright © 2026 Apple Inc. + +#include "doctest/doctest.h" +#include "mlx/mlx.h" + +#ifdef _WIN32 +#include "mlx/backend/cuda/wddm.h" +#endif + +#include + +#include +#include + +using namespace mlx::core; + +namespace { + +bool memory_pools_supported() { + int supported = 0; + REQUIRE_EQ( + cudaDeviceGetAttribute(&supported, cudaDevAttrMemoryPoolsSupported, 0), + cudaSuccess); + return supported; +} + +struct CacheLimitGuard { + ~CacheLimitGuard() { + set_cache_limit(previous); + } + + size_t previous; +}; + +struct MemoryLimitGuard { + ~MemoryLimitGuard() { + set_memory_limit(previous); + } + + size_t previous; +}; + +} // namespace + +constexpr uint64_t gib = 1ULL << 30; + +#ifdef _WIN32 +TEST_CASE("test memory limit from budget") { + CHECK_EQ( + cu::memory_limit_from_budget(24 * gib, 8 * gib, 6 * gib), + 22 * gib - (24 * gib) / 20); + CHECK_EQ( + cu::memory_limit_from_budget(24 * gib, 4 * gib, 6 * gib), + 24 * gib - (24 * gib) / 20); + CHECK_EQ(cu::memory_limit_from_budget(24 * gib, 25 * gib, 0), 0); +} + +TEST_CASE("test wddm memory limit") { + MemoryLimitGuard memory_limit{ + set_memory_limit(std::numeric_limits::max())}; + cudaDeviceProp default_properties{}; + REQUIRE_EQ(cudaGetDeviceProperties(&default_properties, 0), cudaSuccess); + auto default_limit = get_memory_limit(); + if (default_properties.memoryPoolsSupported && + !default_properties.integrated && !default_properties.tccDriver && + default_properties.luidDeviceNodeMask != 0) { + CHECK_LT(default_limit, std::numeric_limits::max()); + } +} +#endif // _WIN32 + +TEST_CASE("test clear cache trims CUDA pool") { + if (!memory_pools_supported()) { + return; + } + + cudaMemPool_t pool = nullptr; + REQUIRE_EQ(cudaDeviceGetDefaultMemPool(&pool, 0), cudaSuccess); + + CacheLimitGuard cache_limit{set_cache_limit(gib)}; + clear_cache(); + + uint64_t initial_reserved = 0; + REQUIRE_EQ( + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &initial_reserved), + cudaSuccess); + + auto s = default_stream(Device::gpu); + { + auto a = zeros({16 * 1024 * 1024}, float32, s); + eval(a); + synchronize(s); + } + CHECK_GE(get_cache_memory(), 64ULL << 20); + + uint64_t allocated_reserved = 0; + REQUIRE_EQ( + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &allocated_reserved), + cudaSuccess); + CHECK_GT(allocated_reserved, initial_reserved); + + clear_cache(); + uint64_t final_reserved = 0; + REQUIRE_EQ( + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &final_reserved), + cudaSuccess); + CHECK_LT(final_reserved, allocated_reserved); +} + +TEST_CASE("test eval after cuda error") { + auto s = default_stream(Device::gpu); + // A failed allocation sets a CUDA error on the calling thread. + CHECK_THROWS(eval(zeros({1 << 20, 1 << 20}, float32, s))); + // The error must not resurface in later evaluations. + auto a = ones({4}, float32, s); + CHECK_NOTHROW(eval(a)); + CHECK(array_equal(a, ones({4})).item()); +} diff --git a/tests/fft_tests.cpp b/tests/fft_tests.cpp index 7dc1b6e666..fd70078520 100644 --- a/tests/fft_tests.cpp +++ b/tests/fft_tests.cpp @@ -134,6 +134,9 @@ TEST_CASE("test real ffts") { TEST_CASE("test fftn") { auto x = zeros({5, 5, 5}); CHECK_THROWS_AS(fft::fftn(x, {}, {0, 3}), std::invalid_argument); + // Matching n/axes sizes so the bounds check is what trips. + CHECK_THROWS_AS(fft::fftn(x, {5, 5}, {0, 3}), std::out_of_range); + CHECK_THROWS_AS(fft::fftn(x, {5, 5}, {0, -4}), std::out_of_range); CHECK_THROWS_AS(fft::fftn(x, {}, {0, -4}), std::invalid_argument); CHECK_THROWS_AS(fft::fftn(x, {}, {0, 0}), std::invalid_argument); CHECK_THROWS_AS(fft::fftn(x, {5, 5, 5}, {0}), std::invalid_argument); @@ -388,8 +391,74 @@ TEST_CASE("test fftshift and ifftshift") { CHECK(array_equal(y, expected).item()); // Test error cases - CHECK_THROWS_AS(fft::fftshift(x, {3}), std::invalid_argument); - CHECK_THROWS_AS(fft::fftshift(x, {-5}), std::invalid_argument); - CHECK_THROWS_AS(fft::ifftshift(x, {3}), std::invalid_argument); - CHECK_THROWS_AS(fft::ifftshift(x, {-5}), std::invalid_argument); + CHECK_THROWS_AS(fft::fftshift(x, {3}), std::out_of_range); + CHECK_THROWS_AS(fft::fftshift(x, {-5}), std::out_of_range); + CHECK_THROWS_AS(fft::ifftshift(x, {3}), std::out_of_range); + CHECK_THROWS_AS(fft::ifftshift(x, {-5}), std::out_of_range); +} + +TEST_CASE("test stft and istft") { + auto win = ones({16}, float32); + + // Real, centered input -> (n_freq, n_frames). + auto x = astype(arange(64), float32); + auto z = fft::stft(x, 16, 8, 16, win, /* center = */ true); + CHECK_EQ(z.ndim(), 2); + CHECK_EQ(z.shape(0), 9); // n_fft / 2 + 1 + CHECK_EQ(z.shape(1), 9); // 1 + (64 + 16 - 16) / 8 + CHECK_EQ(z.dtype(), complex64); + + // Batched input -> (batch, n_freq, n_frames). + auto xb = reshape(astype(arange(2 * 64), float32), {2, 64}); + auto zb = fft::stft(xb, 16, 8, 16, win, true); + CHECK_EQ(zb.ndim(), 3); + CHECK_EQ(zb.shape(0), 2); + CHECK_EQ(zb.shape(1), 9); + + // Non-overlapping rectangular window reconstructs the signal exactly. + auto x2 = astype(arange(32), float32); + auto win2 = ones({8}, float32); + auto z2 = fft::stft(x2, 8, 8, 8, win2, /* center = */ false); + auto y2 = fft::istft( + z2, + /* n_fft = */ 8, + /* hop_length = */ 8, + /* win_length = */ 8, + win2, + /* center = */ false, + fft::FFTNorm::Backward, + /* onesided = */ true, + /* length = */ 32); + CHECK_EQ(y2.shape(0), 32); + CHECK(allclose(y2, x2, 1e-4, 1e-4).item()); + + // Overlapping window: round-trip recovers the fully covered interior. + auto x3 = astype(arange(64), float32); + auto z3 = fft::stft(x3, 16, 8, 16, win, /* center = */ false); + auto y3 = fft::istft(z3, 16, 8, 16, win, false, fft::FFTNorm::Backward, true); + CHECK_EQ(y3.shape(0), 64); // n_fft + (n_frames - 1) * hop = 16 + 6 * 8 + CHECK(allclose(slice(y3, {8}, {56}), slice(x3, {8}, {56}), 1e-4, 1e-4) + .item()); + + // n_fft not divisible by hop: length is n_fft + (n_frames - 1) * hop. + auto w7 = ones({7}, float32); + auto z4 = fft::stft(x3, 7, 3, 7, w7, /* center = */ false); + auto y4 = fft::istft(z4, 7, 3, 7, w7, false, fft::FFTNorm::Backward, true); + CHECK_EQ(y4.shape(0), 64); // n_frames = 20 -> 7 + 19 * 3 + + // Two-sided transform keeps all frequency bins. + auto zf = fft::stft( + x, 16, 8, 16, win, true, "reflect", fft::FFTNorm::Backward, false); + CHECK_EQ(zf.shape(0), 16); + + // Edge padding. + auto ze = fft::stft(x, 16, 8, 16, win, true, "edge"); + CHECK_EQ(ze.shape(0), 9); + + // Error cases. + CHECK_THROWS_AS(fft::stft(x, 0), std::invalid_argument); + CHECK_THROWS_AS( + fft::stft(x, 16, 8, 16, ones({32}, float32)), std::invalid_argument); + CHECK_THROWS_AS( + fft::stft(x, 16, 8, 16, win, true, "bogus"), std::invalid_argument); } diff --git a/tests/gptoss_mxfp4_tests.cpp b/tests/gptoss_mxfp4_tests.cpp index 5a3f82e6d0..472d1e35b6 100644 --- a/tests/gptoss_mxfp4_tests.cpp +++ b/tests/gptoss_mxfp4_tests.cpp @@ -68,6 +68,7 @@ TEST_CASE( 32, 4, "mxfp4", + std::nullopt, true, Device::gpu); eval(reference); @@ -85,6 +86,7 @@ TEST_CASE( 32, 4, "mxfp4", + std::nullopt, true, Device::gpu); eval(actual); @@ -169,6 +171,7 @@ TEST_CASE("gptoss mxfp4 fast gather covers the final 320 input values") { 32, 4, "mxfp4", + std::nullopt, false, Device::gpu); eval(reference); @@ -185,6 +188,7 @@ TEST_CASE("gptoss mxfp4 fast gather covers the final 320 input values") { 32, 4, "mxfp4", + std::nullopt, false, Device::gpu); eval(actual); diff --git a/tests/gpu_tests.cpp b/tests/gpu_tests.cpp index 18018a4632..9d577efd8a 100644 --- a/tests/gpu_tests.cpp +++ b/tests/gpu_tests.cpp @@ -58,6 +58,24 @@ TEST_CASE("test gpu full") { } } +TEST_CASE("test gpu strided scan grid") { + // Regression for #4419 strided_scan writes out of bounds. + std::vector values(72, 1.0f); + auto x = array(values.data(), {72}); + x = transpose(reshape(x, {2, 9, 4}, Device::gpu), {0, 2, 1}, Device::gpu); + x = cumsum(x, -1, false, true, Device::gpu); + + auto causal = tril(ones({9, 9}, float32, Device::gpu), 0, Device::gpu); + auto relative = subtract( + expand_dims(x, -1, Device::gpu), + expand_dims(x, -2, Device::gpu), + Device::gpu); + eval(relative, causal); + + auto expected = tri(9, 9, 0, float32, Device::cpu); + CHECK(array_equal(causal, expected, Device::cpu).item()); +} + TEST_CASE("test gpu astype") { array x = array({-4, -3, -2, -1, 0, 1, 2, 3}); // Check all types work @@ -448,6 +466,59 @@ TEST_CASE("test gpu matmul") { } } +TEST_CASE("test gpu gather/scatter indices") { + // Run with METAL_DEVICE_WRAPPER_TYPE=1 to validate the metadata bindings. + + SUBCASE("scatter scalar indices") { + auto x = array({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, {3, 4}); + + SUBCASE("non-leading axis") { + auto out = take(x, array(2), 1, Device::gpu); + CHECK(array_equal(out, array({2, 6, 10}), Device::cpu).item()); + } + + SUBCASE("strided source") { + auto src = transpose(x, Device::gpu); + auto out = take(src, array(-1), 0, Device::gpu); + CHECK(array_equal(out, array({3, 7, 11}), Device::cpu).item()); + } + + SUBCASE("multiple scalar indices") { + auto out = gather(x, {array(1), array(-2)}, {0, 1}, {1, 1}, Device::gpu); + CHECK(array_equal(out, array({6}, {1, 1}), Device::cpu).item()); + } + } + + SUBCASE("gather without indices") { + SUBCASE("scalar source") { + auto out = gather(array(7), {}, std::vector{}, {}, Device::gpu); + CHECK_EQ(out.item(), 7); + } + + SUBCASE("matrix source") { + auto x = array({0, 1, 2, 3}, {2, 2}); + auto out = gather(x, {}, std::vector{}, {2, 2}, Device::gpu); + CHECK(array_equal(out, x, Device::cpu).item()); + } + } + + SUBCASE("scatter without indices") { + SUBCASE("scalar update") { + auto out = + scatter_max(array(1), {}, array(2), std::vector{}, Device::gpu); + CHECK_EQ(out.item(), 2); + } + + SUBCASE("strided update") { + auto x = array({0, 1, 2, 3}, {2, 2}); + auto updates = transpose(array({1, 2, 3, 4}, {2, 2}), Device::gpu); + auto out = scatter_add(x, {}, updates, std::vector{}, Device::gpu); + CHECK(array_equal(out, array({1, 4, 4, 7}, {2, 2}), Device::cpu) + .item()); + } + } +} + TEST_CASE("test gpu validation") { // Run this test with Metal validation enabled // METAL_DEVICE_WRAPPER_TYPE=1 METAL_DEBUG_ERROR_MODE=0 ./tests/tests \ diff --git a/tests/load_tests.cpp b/tests/load_tests.cpp index 6ef7bc276e..b4b54046a3 100644 --- a/tests/load_tests.cpp +++ b/tests/load_tests.cpp @@ -257,6 +257,104 @@ TEST_CASE("test gguf tensor data offset validation") { } } +// Writes a one-tensor GGUF whose tensor header carries `dims` and `type` +// verbatim, so a test can drive the dimension product independently of the +// amount of tensor data in the file. The name ends in ".weight" because the +// quantized loader derives the scales and biases names from it. +void write_raw_gguf_dims( + const std::string& path, + const std::vector& dims, + uint32_t type, + size_t data_bytes) { + std::ofstream out(path, std::ios::binary); + auto u32 = [&out](uint32_t v) { + out.write(reinterpret_cast(&v), 4); + }; + auto u64 = [&out](uint64_t v) { + out.write(reinterpret_cast(&v), 8); + }; + out.write("GGUF", 4); + u32(3); // version + u64(1); // tensor_count + u64(0); // metadata_kv_count + u64(8); // tensor name length + out.write("w.weight", 8); + u32(dims.size()); + for (auto dim : dims) { + u64(dim); + } + u32(type); + u64(0); // tensor data offset + while (out.tellp() % 32 != 0) { // default GGUF alignment + out.put(0); + } + std::vector data(data_bytes, 0); + out.write(data.data(), data.size()); +} + +TEST_CASE("test gguf tensor dimension validation") { + // The element count exists in two widths: gguflib keeps the 64 bit product in + // tensor.num_weights, and get_shape narrows each dimension to a 32 bit + // ShapeElem. Only the byte size is checked against the file, so dimensions + // that make the two disagree size a buffer from one and index it with the + // other. See ml-explore/mlx#4244. + const uint32_t q8_0 = 8; + + SUBCASE("valid quantized tensor loads") { + std::string file_path = get_temp_file("test_gguf_dims_ok.gguf"); + // One block of 32 weights: 2 bytes of scale plus 32 bytes of weights. + write_raw_gguf_dims(file_path, {32}, q8_0, 34); + auto [weights, metadata] = load_gguf(file_path); + CHECK_EQ(weights.at("w.weight").shape(), Shape{8}); + CHECK_EQ(weights.at("w.scales").shape(), Shape{1}); + CHECK_EQ(weights.at("w.biases").shape(), Shape{1}); + } + + SUBCASE("dimension past the ShapeElem range") { + // Narrows to a shape of 32 that no longer describes the file. + std::string file_path = get_temp_file("test_gguf_dim_narrowed.gguf"); + write_raw_gguf_dims(file_path, {(1ull << 32) + 32}, q8_0, 34); + CHECK_THROWS_AS(load_gguf(file_path), std::runtime_error); + } + + SUBCASE("dimension that narrows to a negative shape") { + std::string file_path = get_temp_file("test_gguf_dim_negative.gguf"); + write_raw_gguf_dims(file_path, {1ull << 31}, q8_0, 34); + CHECK_THROWS_AS(load_gguf(file_path), std::runtime_error); + } + + SUBCASE("dimension product that wraps to a small byte size") { + // 96 * 384307168202282326 wraps to 64, so the tensor needs only 68 bytes of + // data and passes the byte size check, while the narrowed shape + // {1431655766, 96} still describes 2^37 elements. That drives the scales + // element count past INT32_MAX, which is what truncates the allocation size + // while the extractor still loops over the full count. + std::string file_path = get_temp_file("test_gguf_dim_wrap.gguf"); + write_raw_gguf_dims(file_path, {96, 384307168202282326ull}, q8_0, 68); + CHECK_THROWS_AS(load_gguf(file_path), std::runtime_error); + } + + SUBCASE("dimension product that wraps to zero") { + // Wraps num_weights to exactly 0, so the tensor claims no data at all. + std::string file_path = get_temp_file("test_gguf_dim_wrap_zero.gguf"); + write_raw_gguf_dims( + file_path, + {(1ull << 32) + (1ull << 25), + (1ull << 32) + (1ull << 15), + (1ull << 32) + (1ull << 24)}, + q8_0, + 0); + CHECK_THROWS_AS(load_gguf(file_path), std::runtime_error); + } + + SUBCASE("tensor without dimensions") { + // gguf_load_quantized indexes the last shape element unconditionally. + std::string file_path = get_temp_file("test_gguf_no_dims.gguf"); + write_raw_gguf_dims(file_path, {}, q8_0, 0); + CHECK_THROWS_AS(load_gguf(file_path), std::runtime_error); + } +} + // Writes a metadata-only GGUF (no tensors) whose metadata KV section is // `kv_section` verbatim, so a caller can encode values whose lengths exceed the // file to exercise check_metadata_value_in_file(). `kv_count` must match the diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 38b29826a2..f74db9bef1 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -9,6 +9,7 @@ #include "mlx/backend/cuda/cuda.h" #include "mlx/mlx.h" +#include "mlx/primitives.h" using namespace mlx::core; @@ -124,8 +125,9 @@ TEST_CASE("test reshape") { CHECK(x.flags().col_contiguous); y = reshape(x, {2, 5, 10}); eval(y); + // Strides (5, 1, 10) are neither row nor col major CHECK(!y.flags().row_contiguous); - CHECK(y.flags().col_contiguous); + CHECK(!y.flags().col_contiguous); y = reshape(x, {2, 50}); eval(y); CHECK(y.flags().row_contiguous); @@ -358,6 +360,22 @@ TEST_CASE("test slice") { out = slice(x, {3, 0}, {-5, 2}, {-1, 1}); eval(out); CHECK_EQ(out.data_size(), 8); + + x = as_strided(square(arange(16, float32)), {3, 2, 2}, {1, 1, 5}, 0); + out = slice(x, {0, 0, 0}, {2, 2, 2}); + eval(out); + CHECK_EQ(out.data_size(), 8); + CHECK_FALSE(out.flags().contiguous); + CHECK_EQ(sum(out).item(), 152.0f); + + x = reshape(arange(6), {2, 3}); + x = slice(x, {1, 0}, {-3, 3}, {-1, 1}); + out = slice(x, {1, 0}, {-3, 3}, {-1, 1}); + eval(out); + CHECK(out.flags().contiguous); + CHECK(out.flags().row_contiguous); + CHECK(array_equal(reshape(transpose(out), {-1}), array({0, 3, 1, 4, 2, 5})) + .item()); } TEST_CASE("test slice update") { @@ -606,6 +624,71 @@ TEST_CASE("test split") { CHECK(array_equal(out[1], array({})).item()); CHECK(array_equal(out[2], array({1})).item()); CHECK(array_equal(out[3], array({2, 3, 4})).item()); + + // data_size is the distance between the first and the last element, so a + // split that leaves holes reports more than the output has elements. + x = ones({4, 4}); + out = split(x, 2, 1); + eval(out); + CHECK_EQ(out[0].data_size(), 14); + CHECK_EQ(out[1].data_size(), 14); + + // Splitting the first axis leaves no holes. + out = split(x, 2, 0); + eval(out); + CHECK_EQ(out[0].data_size(), 8); + CHECK_EQ(out[1].data_size(), 8); + + x = ones({2, 3, 4}); + out = split(x, Shape{2}, 2); + eval(out); + CHECK_EQ(out[0].data_size(), 22); + CHECK_EQ(out[1].data_size(), 22); + + // A split output and the matching slice are the same view. + x = ones({1, 2, 8, 12}); + out = split(x, Shape{8}, 3); + auto sliced = slice(x, {0, 0, 0, 8}, {1, 2, 8, 12}); + eval(out); + eval(sliced); + CHECK_EQ(out[1].data_size(), sliced.data_size()); + CHECK_EQ(out[1].data_size(), 184); + + // (4, 4) array, but slice keeps the strides at (8, 1) + x = slice(reshape(arange(32), {4, 8}), {0, 0}, {4, 4}); + // out[0] and out[1] are (4, 2) + out = split(x, Shape{2}, 1); + // same out out[1] + auto holey = slice(x, {0, 2}, {4, 4}); + eval(out); + eval(holey); + CHECK_EQ(out[0].data_size(), 26); + CHECK_EQ(out[1].data_size(), 26); + CHECK_EQ(out[1].data_size(), holey.data_size()); + CHECK_EQ(out[0].strides(), x.strides()); + CHECK_EQ(out[1].strides(), holey.strides()); + CHECK(array_equal(out[1], holey).item()); + + // A negative stride travels backwards, so it bounds the span from below. + // strides (-4, 1) + x = flip(reshape(arange(24), {6, 4}), 0); + out = split(x, Shape{2}, 0); + eval(out); + // no holes + CHECK_EQ(out[0].data_size(), 8); + CHECK_EQ(out[1].data_size(), 16); + CHECK_EQ(out[0].strides(), x.strides()); + CHECK_EQ(out[1].strides(), x.strides()); + CHECK(array_equal(out[0], slice(x, {0, 0}, {2, 4})).item()); + CHECK(array_equal(out[1], slice(x, {2, 0}, {6, 4})).item()); + + // A zero-length axis empties every output. Splitting at 0 cannot get here, + // split() sends that to slice(). + x = ones({0, 4}); + out = split(x, Shape{2}, 1); + eval(out); + CHECK_EQ(out[0].data_size(), 0); + CHECK_EQ(out[1].data_size(), 0); } TEST_CASE("test flip") { @@ -706,7 +789,7 @@ TEST_CASE("test transpose") { CHECK_EQ(y.shape(), Shape{1}); CHECK_EQ(y.item(), 1); - CHECK_THROWS_AS(transpose(x, {1}), std::invalid_argument); + CHECK_THROWS_AS(transpose(x, {1}), std::out_of_range); CHECK_THROWS_AS(transpose(x, {0, 0}), std::invalid_argument); // Works with empty array @@ -896,6 +979,29 @@ TEST_CASE("test comparison ops") { } } +TEST_CASE("test float16 sigmoid mixed lanes") { + const float values[] = {-12, -4, -1, 0, 1, 4, 12, -2}; + for (int size : {1, 7, 8, 9, 15, 16, 17}) { + for (int offset = 0; offset < 8; ++offset) { + std::vector input(size); + for (int i = 0; i < size; ++i) { + input[i] = values[(i + offset) % 8]; + } + auto result = sigmoid(array(input.begin(), {size}, float16), Device::cpu); + result.eval(); + for (int i = 0; i < size; ++i) { + CAPTURE(size); + CAPTURE(offset); + CAPTURE(i); + auto expected = 1.0 / (1.0 + std::exp(-double(input[i]))); + CHECK_EQ( + static_cast(result.data()[i]), + doctest::Approx(expected).epsilon(0.002)); + } + } + } +} + TEST_CASE("test is nan") { array x(1.0f); CHECK_FALSE(isnan(x).item()); @@ -2003,6 +2109,17 @@ TEST_CASE("test arithmetic binary ops") { y = array(false); CHECK(std::isnan(divide(x, y).item())); + // Integer division by zero gives quotient 0 and remainder a. + if (default_device() == Device::cpu) { + for (auto dt : {int8, int16, int32, int64, uint8, uint16, uint32, uint64}) { + auto num = astype(array({7, 0, 5, -7}, {4}), dt); + auto den = zeros({4}, dt); + auto q = floor_divide(num, den); + CHECK(array_equal(q, zeros({4}, dt)).item()); + CHECK(array_equal(remainder(num, den), num).item()); + } + } + // Check maximum and minimum x = array(1.0f); y = array(0.0f); @@ -2883,11 +3000,66 @@ TEST_CASE("test as_strided op") { CHECK_EQ(y.data_size(), 10); CHECK_FALSE(y.flags().contiguous); + auto xf = square(arange(16, float32)); + y = as_strided(xf, {2, 2, 2}, {1, 1, 5}, 0); + eval(y); + CHECK_EQ(y.data_size(), 8); + CHECK_FALSE(y.flags().contiguous); + CHECK_EQ(sum(y).item(), 152.0f); + x = reshape(x, {2, 5}); // 0 1 2 3 ... x = transpose(x, {1, 0}); // 0 5 1 6 2 7 ... y = as_strided(x, {3, 3}, {2, 1}, 1); expected = array({5, 1, 6, 6, 2, 7, 7, 3, 8}, {3, 3}); CHECK(array_equal(y, expected).item()); + + x = slice(arange(12), {10}, {0}, {-2}); + y = as_strided(x, {2, 2}, {2, 1}, 1); + expected = array({8, 6, 4, 2}, {2, 2}); + CHECK(array_equal(y, expected).item()); + + x = broadcast_to(array({1, 2, 3}), {2, 3}); + y = as_strided(x, {2, 2}, {2, 1}, 1); + expected = array({2, 3, 1, 2}, {2, 2}); + CHECK(array_equal(y, expected).item()); +} + +TEST_CASE("test sort and scan on empty arrays") { + // These must be evaluated, not only shape checked, to reach the kernel. + auto check_empty = [](const array& r, Shape shape, Dtype dt) { + auto out = r; + eval(out); + CHECK_EQ(out.shape(), shape); + CHECK_EQ(out.dtype(), dt); + CHECK_EQ(out.size(), 0); + }; + + for (auto dt : {float32, int32, uint32, bool_}) { + auto x = zeros({0}, dt); + check_empty(sort(x), Shape{0}, dt); + check_empty(argsort(x), Shape{0}, uint32); + check_empty(cumsum(x), Shape{0}, dt == bool_ ? int32 : dt); + check_empty(cumprod(x), Shape{0}, dt); + check_empty(cummax(x), Shape{0}, dt); + check_empty(cummin(x), Shape{0}, dt); + } + + // Empty along the sorted axis, non-empty elsewhere. + auto x = zeros({3, 0}, float32); + check_empty(sort(x, 1), Shape{3, 0}, float32); + check_empty(argsort(x, 1), Shape{3, 0}, uint32); + check_empty(cumsum(x, 1), Shape{3, 0}, float32); + + // Empty on another axis, so the sorted axis itself is non-empty. + x = zeros({0, 3}, float32); + check_empty(sort(x, 1), Shape{0, 3}, float32); + check_empty(argsort(x, 1), Shape{0, 3}, uint32); + check_empty(cumsum(x, 1), Shape{0, 3}, float32); + + // Non-contiguous empty input reaches the strided path. + x = transpose(zeros({4, 0}, float32)); + check_empty(sort(x, 1), Shape{0, 4}, float32); + check_empty(cumsum(x, 1), Shape{0, 4}, float32); } TEST_CASE("test scan op") { @@ -2949,6 +3121,40 @@ TEST_CASE("test scan op") { y = vmap(fun, 1, 1)(x); expected = array({1.0f, 2.0f, 4.0f, 6.0f, 9.0f, 12.0f, 16.0f, 20.0f}, {4, 2}); CHECK(array_equal(y, expected).item()); + + // Scanning an empty axis is a no-op + x = zeros({2, 0}); + y = cumsum(x, 1); + eval(y); + CHECK_EQ(y.shape(), Shape{2, 0}); + y = cummax(x, 1); + eval(y); + CHECK_EQ(y.shape(), Shape{2, 0}); + x = zeros({0, 2}); + y = cumsum(x, 0); + eval(y); + CHECK_EQ(y.shape(), Shape{0, 2}); + y = cummin(x, 0); + eval(y); + CHECK_EQ(y.shape(), Shape{0, 2}); +} + +TEST_CASE("test sort op") { + // Sorting an empty axis is a no-op + auto x = zeros({2, 0}); + auto y = sort(x, 1); + eval(y); + CHECK_EQ(y.shape(), Shape{2, 0}); + y = argsort(x, 1); + eval(y); + CHECK_EQ(y.shape(), Shape{2, 0}); + x = zeros({0, 2}); + y = sort(x, 0); + eval(y); + CHECK_EQ(y.shape(), Shape{0, 2}); + y = argsort(x, 0); + eval(y); + CHECK_EQ(y.shape(), Shape{0, 2}); } TEST_CASE("test pad") { @@ -3549,6 +3755,25 @@ TEST_CASE("inner") { CHECK(array_equal(z, expected).item()); } +TEST_CASE("test floor divide") { + // Signed integers round the quotient towards minus infinity. + auto x = array({4, 5, -1, -6}); + auto y = array({-2, 3, 2, -3}); + CHECK(array_equal(floor_divide(x, y), array({-2, 1, -1, 2})).item()); + + // Unsigned integers use the plain quotient. + auto ux = astype(array({7, 0, 5}, {3}), uint32); + auto uy = astype(array({2, 2, 3}, {3}), uint32); + auto expected = astype(array({3, 0, 1}, {3}), uint32); + CHECK(array_equal(floor_divide(ux, uy), expected).item()); + + // The dtype is kept and the result is one primitive. + auto out = floor_divide(astype(x, int8), astype(array(3), int8)); + CHECK_EQ(out.dtype(), int8); + CHECK_EQ(std::string(out.primitive().name()), "FloorDivide"); + CHECK(out.siblings().empty()); +} + TEST_CASE("test divmod") { auto x = array({1, 2, 3}); auto y = array({1, 1, 1}); @@ -4581,6 +4806,66 @@ TEST_CASE("test conv shape overflow") { Shape{1, 8, 8, 1}); } +TEST_CASE("test pad with an axes subset") { + // edge_pad ignored `axes` and indexed the pad sizes by array axis, so it + // read past the end of those vectors and placed the input on the wrong + // axes. reflect and symmetric indexed by position but did not normalize a + // negative axis. + auto x = reshape(arange(24.0f), {2, 3, 4}); + auto all = {"constant", "edge", "reflect", "symmetric"}; + + // Padding a subset of the axes matches the equivalent all-axes spelling. + for (auto mode : all) { + CHECK(array_equal( + pad(x, {1}, Shape{1}, Shape{2}, array(0.0f), mode), + pad(x, + {0, 1, 2}, + Shape{0, 1, 0}, + Shape{0, 2, 0}, + array(0.0f), + mode)) + .item()); + } + + // A negative axis matches its non-negative spelling. + for (auto mode : all) { + CHECK(array_equal( + pad(x, {-2}, Shape{1}, Shape{2}, array(0.0f), mode), + pad(x, {1}, Shape{1}, Shape{2}, array(0.0f), mode)) + .item()); + } + + // The order of `axes` does not change the result. + auto y = reshape(arange(25.0f), {5, 5}); + for (auto mode : all) { + CHECK(array_equal( + pad(y, {1, 0}, Shape{1, 2}, Shape{1, 2}, array(0.0f), mode), + pad(y, {0, 1}, Shape{2, 1}, Shape{2, 1}, array(0.0f), mode)) + .item()); + } + + // An ndim past SmallVector's inline capacity puts the pad sizes on the heap, + // where the old read ran off the end of the allocation. + std::vector wide_axes(11); + std::iota(wide_axes.begin(), wide_axes.end(), 0); + auto wide = + pad(zeros(Shape(34, 1)), + wide_axes, + Shape(11, 1), + Shape(11, 0), + array(0.0f), + "edge"); + CHECK_EQ(wide.size(), 2048); + + // An axis outside the array is rejected rather than indexed. + for (auto mode : all) { + CHECK_THROWS_AS( + pad(x, {5}, Shape{1}, Shape{1}, array(0.0f), mode), std::out_of_range); + CHECK_THROWS_AS( + pad(x, {-5}, Shape{1}, Shape{1}, array(0.0f), mode), std::out_of_range); + } +} + TEST_CASE("test pad shape overflow") { // A padding sum that overflows int32 is rejected, not wrapped. // https://github.com/ml-explore/mlx/issues/3611 diff --git a/tests/residency_tests.cpp b/tests/residency_tests.cpp index 60cd7c90e4..0edac9b6dc 100644 --- a/tests/residency_tests.cpp +++ b/tests/residency_tests.cpp @@ -66,11 +66,11 @@ TEST_CASE("test residency set wires nothing when the wired limit is zero") { std::vector bufs; for (int i = 0; i < 4; ++i) { - bufs.push_back(allocator::malloc(4 * MB)); + bufs.push_back(allocator::allocator().malloc(4 * MB)); CHECK_EQ(residency().wired_size(), 0); } for (auto buf : bufs) { - allocator::free(buf); + allocator::allocator().free(buf); } CHECK_EQ(residency().wired_size(), 0); } @@ -89,14 +89,14 @@ TEST_CASE("test residency set never wires more than the wired limit") { std::vector bufs; for (int i = 0; i < 8; ++i) { // asks for 32 MB against an 8 MB budget - bufs.push_back(allocator::malloc(4 * MB)); + bufs.push_back(allocator::allocator().malloc(4 * MB)); CHECK_LE(residency().wired_size(), limit); } // Over budget overall, but the budget itself is still used. CHECK_GE(residency().wired_size(), baseline + 4 * MB); for (auto buf : bufs) { - allocator::free(buf); + allocator::allocator().free(buf); } // Everything of ours is unwired again, exactly. CHECK_EQ(residency().wired_size(), baseline); @@ -108,13 +108,13 @@ TEST_CASE("test raising the wired limit wires already-allocated buffers") { } LimitGuard guard(0, 0); - auto buf = allocator::malloc(8 * MB); + auto buf = allocator::allocator().malloc(8 * MB); CHECK_EQ(residency().wired_size(), 0); set_wired_limit(64 * MB); CHECK_GE(residency().wired_size(), 8 * MB); - allocator::free(buf); + allocator::allocator().free(buf); } TEST_CASE("test lowering the wired limit unwires buffers") { @@ -124,7 +124,7 @@ TEST_CASE("test lowering the wired limit unwires buffers") { LimitGuard guard(64 * MB, 0); const size_t baseline_with_budget = residency().wired_size(); - auto buf = allocator::malloc(8 * MB); + auto buf = allocator::allocator().malloc(8 * MB); CHECK_GE(residency().wired_size(), baseline_with_budget + 8 * MB); set_wired_limit(0); @@ -134,7 +134,7 @@ TEST_CASE("test lowering the wired limit unwires buffers") { set_wired_limit(64 * MB); CHECK_GE(residency().wired_size(), baseline_with_budget + 8 * MB); - allocator::free(buf); + allocator::allocator().free(buf); } TEST_CASE("test residency accounting is exact across free/realloc cycles") { @@ -147,9 +147,9 @@ TEST_CASE("test residency accounting is exact across free/realloc cycles") { const size_t baseline = residency().wired_size(); for (int i = 0; i < 32; ++i) { - auto buf = allocator::malloc(8 * MB); + auto buf = allocator::allocator().malloc(8 * MB); CHECK_GE(residency().wired_size(), baseline + 8 * MB); - allocator::free(buf); + allocator::allocator().free(buf); // Exact: erase subtracts the bytes recorded at insert, so repeated // cycles must not drift the running total. CHECK_EQ(residency().wired_size(), baseline); @@ -170,7 +170,7 @@ TEST_CASE("test wired allocations are spread across size-capped sets") { // Each buffer is over half the cap, so no two share a set. std::vector bufs; for (int i = 0; i < 8; ++i) { - bufs.push_back(allocator::malloc(5 * MB)); + bufs.push_back(allocator::allocator().malloc(5 * MB)); } CHECK_EQ(residency().wired_size(), baseline + 8 * 5 * MB); CHECK_GT(residency().num_sets(), baseline_sets); @@ -183,7 +183,7 @@ TEST_CASE("test wired allocations are spread across size-capped sets") { const size_t sets_before = residency().num_sets(); for (auto buf : bufs) { - allocator::free(buf); + allocator::allocator().free(buf); } CHECK_EQ(residency().wired_size(), baseline); @@ -192,11 +192,11 @@ TEST_CASE("test wired allocations are spread across size-capped sets") { for (int cycle = 0; cycle < 4; ++cycle) { std::vector again; for (int i = 0; i < 8; ++i) { - again.push_back(allocator::malloc(5 * MB)); + again.push_back(allocator::allocator().malloc(5 * MB)); } CHECK_EQ(residency().num_sets(), sets_before); for (auto buf : again) { - allocator::free(buf); + allocator::allocator().free(buf); } } CHECK_EQ(residency().wired_size(), baseline); @@ -215,7 +215,7 @@ TEST_CASE("test the set count stays within the command queue limit") { std::vector bufs; for (int i = 0; i < 64; ++i) { - bufs.push_back(allocator::malloc(2 * MB)); + bufs.push_back(allocator::allocator().malloc(2 * MB)); } CHECK_LE(residency().num_sets(), 32); CHECK_EQ(residency().wired_size(), baseline + 64 * 2 * MB); @@ -224,7 +224,7 @@ TEST_CASE("test the set count stays within the command queue limit") { check_gpu_work(); for (auto buf : bufs) { - allocator::free(buf); + allocator::allocator().free(buf); } CHECK_EQ(residency().wired_size(), baseline); } @@ -238,11 +238,11 @@ TEST_CASE("test an allocation larger than the set cap is still wired") { set_wired_limit(128 * MB); const size_t baseline = residency().wired_size(); - auto big = allocator::malloc(32 * MB); + auto big = allocator::allocator().malloc(32 * MB); CHECK_EQ(residency().wired_size(), baseline + 32 * MB); check_gpu_work(); - allocator::free(big); + allocator::allocator().free(big); CHECK_EQ(residency().wired_size(), baseline); } @@ -258,13 +258,13 @@ TEST_CASE("test a set cap of zero keeps everything in one set") { std::vector bufs; for (int i = 0; i < 16; ++i) { - bufs.push_back(allocator::malloc(4 * MB)); + bufs.push_back(allocator::allocator().malloc(4 * MB)); } CHECK_EQ(residency().num_sets(), baseline_sets); CHECK_EQ(residency().wired_size(), baseline + 16 * 4 * MB); for (auto buf : bufs) { - allocator::free(buf); + allocator::allocator().free(buf); } CHECK_EQ(residency().wired_size(), baseline); } @@ -280,17 +280,17 @@ TEST_CASE("test the wired limit is used up to its boundary") { const size_t baseline = residency().wired_size(); set_wired_limit(baseline + 4 * MB); - auto first = allocator::malloc(4 * MB); + auto first = allocator::allocator().malloc(4 * MB); CHECK_EQ(residency().wired_size(), baseline + 4 * MB); // The budget is exactly full: the next allocation is tracked but not wired. - auto second = allocator::malloc(4 * MB); + auto second = allocator::allocator().malloc(4 * MB); CHECK_EQ(residency().wired_size(), baseline + 4 * MB); // Freeing the wired one does not promote the pending one. - allocator::free(first); + allocator::allocator().free(first); CHECK_EQ(residency().wired_size(), baseline); - allocator::free(second); + allocator::allocator().free(second); CHECK_EQ(residency().wired_size(), baseline); } diff --git a/tests/scheduler_tests.cpp b/tests/scheduler_tests.cpp index 3a8f7e86b7..bd9054cc0f 100644 --- a/tests/scheduler_tests.cpp +++ b/tests/scheduler_tests.cpp @@ -1,5 +1,7 @@ // Copyright © 2023 Apple Inc. +#include + #include "doctest/doctest.h" #include "mlx/mlx.h" @@ -114,6 +116,35 @@ TEST_CASE("test thread unsafe stream") { CHECK_EQ(expected, actual); } +TEST_CASE("test eval does not create default stream") { + auto s = new_thread_unsafe_stream(default_device()); + size_t num_streams = get_streams().size(); + + std::thread t([&] { + async_eval(arange(10, s)); + eval(arange(10, s)); + }); + t.join(); + + CHECK_EQ(get_streams().size(), num_streams); +} + +TEST_CASE("test compile does not create default stream") { + auto s = new_thread_unsafe_stream(default_device()); + size_t num_streams = get_streams().size(); + + std::function(const std::vector&)> fun = + [s](const std::vector& inputs) { + return std::vector{abs(inputs[0], s)}; + }; + auto cfun = compile(fun); + + std::thread t([&] { eval(cfun({array({-1, 2})})); }); + t.join(); + + CHECK_EQ(get_streams().size(), num_streams); +} + TEST_CASE("test thread local stream") { auto s = new_thread_local_stream(default_device()); int result = sum(arange(10, s)).item(); @@ -249,3 +280,49 @@ TEST_CASE("test scheduler races") { } eval(a, y); } + +// The fence orders work between two streams. Check that the consumer sees the +// producer result for every combination of producer and consumer device. +TEST_CASE("test cross stream fence ordering") { + if (!gpu::is_available()) { + return; + } + std::vector devices = {Device::cpu, Device::gpu}; + + for (auto pd : devices) { + for (auto cd : devices) { + auto ps = new_stream(pd); + auto cs = new_stream(cd); + + array one = full({1}, 1.0f, float32, ps); + array x = full({64, 64}, 1.0f, float32, ps); + for (int i = 0; i < 20; ++i) { + x = add(x, one, ps); + } + + // The consumer is on the other stream, so eval builds a fence. + array y = sum(x, cs); + CHECK_EQ(y.item(), doctest::Approx(64 * 64 * 21.0f)); + } + } +} + +TEST_CASE("test async_eval does not throw a stored stream error") { + // A failed CPU task stores its error in the stream. Wait for the task + // without synchronize, so the error is still stored when async_eval runs. + auto s = new_stream(Device::cpu); + scheduler::enqueue(s, []() { throw std::runtime_error("task failed"); }); + auto done = std::make_shared>(); + auto finished = done->get_future(); + scheduler::enqueue(s, [done]() { done->set_value(); }); + finished.wait(); + + auto x = add(array(1.0f), array(2.0f), s); + CHECK_NOTHROW(async_eval(x)); + CHECK_THROWS_AS(synchronize(s), std::runtime_error); + + // The error is cleared, so the stream works again. + auto y = add(array(1.0f), array(2.0f), s); + eval(y); + CHECK_EQ(y.item(), 3.0f); +}