From a4832ecac96ea4a3dad63a00db3faf39f8497ce2 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:01:55 +0900 Subject: [PATCH 1/7] update(rocm): add mlxcelverse sync, drift checks and fork PR packages The ROCm overlay had no tooling for its two upstreams, and its pin-bump check (+/- line counts) could not see a core overlay that was already wrong before a bump. scripts/mlxcelverse/rocm_overlay.py rebuilds each core file as "pin + the fork's own change" and diffs the overlay against it; the residual must match the reviewed patches-rocm/CORE_RESIDUAL.diff (4 of 15 files, LOCAL_FIXES items 1 and 24). It also syncs to a new fork commit (sync_from_fork.sh, 3-way merges carrying every local fix), retargets core files to a new pin, and check_api_drift.sh builds a candidate tree and lists compile errors and undefined mlx::core symbols. The offline records check and a synthetic-history test run as make verify-rocm-overlay, in verify and verify-rocm, so a pin bump that skips the ROCm retarget fails on any host. docs/mlxcelverse/ adds the pin-bump and fork-sync procedure and ten PR packages for NripeshN/mlx rocm-support (patch, PR text, reproduction), prepared for manual submission, with a slot for item 27. README backend count is 108; LOCAL_FIXES names the files of items 2, 7, 11 and 20; rope.hip's comment-only drift from the fork is reverted. Refs #1813 --- CONTRIBUTING.md | 4 +- Makefile | 21 +- docs/README.md | 4 + docs/architecture.md | 5 +- docs/mlxcelverse/rocm-overlay.md | 84 ++ ...ntized-matmul-dispatch-for-mxfp4-mxf.patch | 245 ++++ .../01-quantized-matmul-dispatch/pr.md | 39 + .../01-quantized-matmul-dispatch/repro.py | 140 +++ ...gReduce-s-grid-inside-the-per-dimens.patch | 74 ++ .../upstream/02-arg-reduce-grid-limit/pr.md | 36 + .../02-arg-reduce-grid-limit/repro.py | 52 + ...tter-s-size-argument-and-widen-narro.patch | 290 +++++ .../03-scatter-gather-index-types/pr.md | 39 + .../03-scatter-gather-index-types/repro.py | 92 ++ ...ceUpdate-grid-stride-tail-and-source.patch | 198 ++++ .../04-slice-update-tail-and-donation/pr.md | 37 + .../repro.py | 76 ++ ...ent-Hadamard-for-power-of-two-sizes-.patch | 215 ++++ docs/mlxcelverse/upstream/05-hadamard/pr.md | 38 + .../mlxcelverse/upstream/05-hadamard/repro.py | 53 + ...cking-sync-before-the-first-HIP-queu.patch | 221 ++++ .../06-blocking-sync-before-first-queue/pr.md | 36 + .../repro.hip | 46 + ...at-rocm-implement-FFT-through-hipFFT.patch | 639 ++++++++++ docs/mlxcelverse/upstream/07-fft-hipfft/pr.md | 43 + .../upstream/07-fft-hipfft/repro.py | 115 ++ ...-shared-get_2d_grid_dims-and-remove-.patch | 101 ++ .../upstream/08-launch-geometry-helpers/pr.md | 37 + .../08-launch-geometry-helpers/repro.py | 61 + ...-back-from-fused-SDPA-on-CPU-streams.patch | 27 + .../09-sdpa-cpu-stream-fallback/pr.md | 34 + .../09-sdpa-cpu-stream-fallback/repro.py | 36 + ...k-header-dependencies-of-HIP-objects.patch | 77 ++ .../upstream/10-hip-header-dependencies/pr.md | 36 + .../10-hip-header-dependencies/repro.sh | 26 + docs/mlxcelverse/upstream/README.md | 73 ++ scripts/mlxcelverse/check_api_drift.sh | 117 ++ scripts/mlxcelverse/rocm_overlay.py | 1041 +++++++++++++++++ scripts/mlxcelverse/rocm_overlay_test.sh | 240 ++++ scripts/mlxcelverse/sync_from_fork.sh | 32 + .../mlx-cpp/patches-rocm/CORE_RESIDUAL.diff | 199 ++++ src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md | 10 +- src/lib/mlx-cpp/patches-rocm/README.md | 17 +- .../patches-rocm/mlx/backend/rocm/rope.hip | 4 +- 44 files changed, 4994 insertions(+), 16 deletions(-) create mode 100644 docs/mlxcelverse/rocm-overlay.md create mode 100644 docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch create mode 100644 docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/pr.md create mode 100644 docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/repro.py create mode 100644 docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch create mode 100644 docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md create mode 100644 docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/repro.py create mode 100644 docs/mlxcelverse/upstream/03-scatter-gather-index-types/0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch create mode 100644 docs/mlxcelverse/upstream/03-scatter-gather-index-types/pr.md create mode 100644 docs/mlxcelverse/upstream/03-scatter-gather-index-types/repro.py create mode 100644 docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch create mode 100644 docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/pr.md create mode 100644 docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/repro.py create mode 100644 docs/mlxcelverse/upstream/05-hadamard/0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch create mode 100644 docs/mlxcelverse/upstream/05-hadamard/pr.md create mode 100644 docs/mlxcelverse/upstream/05-hadamard/repro.py create mode 100644 docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch create mode 100644 docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md create mode 100644 docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/repro.hip create mode 100644 docs/mlxcelverse/upstream/07-fft-hipfft/0001-feat-rocm-implement-FFT-through-hipFFT.patch create mode 100644 docs/mlxcelverse/upstream/07-fft-hipfft/pr.md create mode 100644 docs/mlxcelverse/upstream/07-fft-hipfft/repro.py create mode 100644 docs/mlxcelverse/upstream/08-launch-geometry-helpers/0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch create mode 100644 docs/mlxcelverse/upstream/08-launch-geometry-helpers/pr.md create mode 100644 docs/mlxcelverse/upstream/08-launch-geometry-helpers/repro.py create mode 100644 docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch create mode 100644 docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md create mode 100644 docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/repro.py create mode 100644 docs/mlxcelverse/upstream/10-hip-header-dependencies/0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch create mode 100644 docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md create mode 100755 docs/mlxcelverse/upstream/10-hip-header-dependencies/repro.sh create mode 100644 docs/mlxcelverse/upstream/README.md create mode 100755 scripts/mlxcelverse/check_api_drift.sh create mode 100755 scripts/mlxcelverse/rocm_overlay.py create mode 100755 scripts/mlxcelverse/rocm_overlay_test.sh create mode 100755 scripts/mlxcelverse/sync_from_fork.sh create mode 100644 src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0c7ac7352..42839ae8e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,7 +49,7 @@ Thank you for your interest in contributing to mlxcel! This document covers the ``` PR-time CI in [`ci.yml`](.github/workflows/ci.yml) runs far more than `cargo fmt`, `cargo deny`, and a crate-version check: a `changes` job path-filters most of the rest by what the PR touches, and `crate-versions`, `kernel-dtype-keys`, `binary-assets`, `cuda-arch-lists`, `license-headers`, `llama-compat-manifest`, and `webui-contract` need no toolchain, run in seconds, and gate every PR unconditionally. `cargo fmt` and `cargo deny` gate on Rust-touching PRs, as before, and so does clippy again: after #21/#23 dropped it for cost, #1285 re-added it as the `clippy` job (`cargo clippy -p mlxcel --lib --tests -- -D warnings`, default features) on the shared self-hosted `GB10` runner, where a persistent target directory keeps a warm run to 27-40 seconds; it fires whenever a Rust file changed, or the PR carries the `ci:full` label. That gated slice is narrower than the full `--workspace --all-targets --features metal,accelerate` command above, and the general unit suite stays unenforced (no PR job runs `cargo test --workspace`), so run both commands above yourself before you push. `GB10` also runs further path-gated jobs, each of which the `ci:full` label forces as well: `xla-compile` on Rust changes, `xla-link` on the IREE link-recipe paths only, `cuda-sm70-compile` and `cuda-blockfloat` on the CUDA-architecture paths (the `src/lib/mlx-cpp/` tree minus its ROCm and Metal subtrees, plus the MLX build scripts) rather than on ordinary Rust changes, and `webui-installed-artifact` on Rust or WebUI changes; the hosted `webui-bundle` job gates on the WebUI path filter alone (which includes the server and CLI sources), and the hosted `mlx-pin` job on the pinned-MLX-commit paths. `rocm-build` is parked on a `rocm-gfx1151` self-hosted runner until that runner is registered and `vars.ROCM_CI_ENABLED` is set; `rocm-ci-status` reports that parked state as an advisory warning, never a failing check. `workflow-lint` (`actionlint`) and the advisory `self-hosted-gate-advisory` both fire on workflow-file changes, the latter noting the path-gated `GB10`/`rocm-gfx1151` jobs above were not re-run unless the PR carries `ci:full`. `cross-repo-refs` runs on every PR but only advises (`STRICT=1` gates it locally). Outside `ci.yml`, [`pipeline-parallel-ci.yml`](.github/workflows/pipeline-parallel-ci.yml) still runs its own path-filtered clippy and a `distributed::`-scoped `cargo test` on pipeline-parallel changes. [`nightly-verify.yml`](.github/workflows/nightly-verify.yml) runs the full `make verify` once a day on `self-hosted-macos-26-arm64` and files an issue when `main` goes red or the run does not finish, a backstop and not a substitute. The exhaustive CUDA and ROCm test suites run in no PR job; `make verify-test-cuda` and `make verify-rocm` remain their only gates, run locally. - `make verify` runs seven prerequisite targets: `verify-versions`, `verify-kernel-dtype-keys`, `verify-kernel-port-dispatch`, `verify-llama-compat`, `verify-fmt`, `verify-clippy`, and `verify-test`. The last three are the fmt, clippy, and test commands above; `cargo deny check`, the fourth command in that block, is not one of them, and PR CI is what gates it. The first four are cheap consistency gates: `verify-versions` asserts every version-tracking workspace crate carries the root `mlxcel` version, `verify-kernel-dtype-keys` asserts every CUDA and HIP JIT kernel launch keys its cache on the input dtypes and that the set of launcher files has not shrunk unnoticed (#1053, #1054, #1875), `verify-kernel-port-dispatch` asserts every fused-kernel launcher chooses its port through `select_kernel_port` (#1801, #1885), and `verify-llama-compat` validates the checked-in llama-server b10621 compatibility manifest under `compat/llama-server/b10621/` structurally, with no network access required (#1443). The nightly invokes those same Makefile targets, so the local gate and CI cannot drift apart. Tests build under `[profile.test-fast]` rather than `--release`: `opt-level = 3` is kept so MLX numerics stay representative, while cross-crate LTO and the single codegen unit that make full `--release` test links expensive are dropped. `make test-fast` / `make test-fast-cuda` are the same profile with `--test-threads=1` and a `FILTER` hook for narrowing the run while you iterate. Reach for `cargo test --release --features metal,accelerate` by hand only when you suspect a defect specific to release codegen. See [`docs/installation.md`](docs/installation.md#fast-iteration-builds) for the measured comparison. + `make verify` runs eight prerequisite targets: `verify-versions`, `verify-kernel-dtype-keys`, `verify-kernel-port-dispatch`, `verify-llama-compat`, `verify-rocm-overlay`, `verify-fmt`, `verify-clippy`, and `verify-test`. The last three are the fmt, clippy, and test commands above; `cargo deny check`, the fourth command in that block, is not one of them, and PR CI is what gates it. The first five are cheap consistency gates: `verify-versions` asserts every version-tracking workspace crate carries the root `mlxcel` version, `verify-kernel-dtype-keys` asserts every CUDA and HIP JIT kernel launch keys its cache on the input dtypes and that the set of launcher files has not shrunk unnoticed (#1053, #1054, #1875), `verify-kernel-port-dispatch` asserts every fused-kernel launcher chooses its port through `select_kernel_port` (#1801, #1885), `verify-llama-compat` validates the checked-in llama-server b10621 compatibility manifest under `compat/llama-server/b10621/` structurally, with no network access required (#1443), and `verify-rocm-overlay` checks, offline, that the ROCm overlay's records agree with the MLX pin and the tree, so a pin bump that skips the ROCm retarget fails on any host (#1813). The nightly invokes those same Makefile targets, so the local gate and CI cannot drift apart. Tests build under `[profile.test-fast]` rather than `--release`: `opt-level = 3` is kept so MLX numerics stay representative, while cross-crate LTO and the single codegen unit that make full `--release` test links expensive are dropped. `make test-fast` / `make test-fast-cuda` are the same profile with `--test-threads=1` and a `FILTER` hook for narrowing the run while you iterate. Reach for `cargo test --release --features metal,accelerate` by hand only when you suspect a defect specific to release codegen. See [`docs/installation.md`](docs/installation.md#fast-iteration-builds) for the measured comparison. The plain `make test`, `make test-verbose`, and `make test-lib` targets stay on Cargo's default `dev` profile and now export `RUST_MIN_STACK=16777216` for you. That stack bump is there for `server::reasoning_effort_tests`: its repeated renders of the pinned 8,952-byte Qwen3.8 chat template can overflow libtest's default 2 MiB per-test thread stack under unoptimized `dev`, even though the same suite passes under `test-fast` and `release`. If you bypass the Makefile and run the `dev`-profile server tests directly, keep the same prefix yourself: `RUST_MIN_STACK=16777216 cargo test --lib --features metal,accelerate server::`. `make verify-test` is intentionally unaffected because it already builds under `[profile.test-fast]`. @@ -147,7 +147,7 @@ After bumping the pin, re-validate the in-tree fused Metal kernel launchers in ` All three should produce output within RMS < 5e-3 of the graph reference on Apple Silicon. -The ROCm overlay in [`src/lib/mlx-cpp/patches-rocm/`](src/lib/mlx-cpp/patches-rocm/README.md) follows the pin too. A bump 3-way merges its 15 MLX core files like any other overlay, then builds with `--features rocm` on an AMD host: upstream API changes surface as compile errors in `mlx/backend/rocm/`, and new primitives without a ROCm kernel surface as undefined `eval_gpu` symbols at link time (give them a `NO_GPU` stub or an implementation). Record each fix in `patches-rocm/LOCAL_FIXES.md` and the new pin in `patches-rocm/UPSTREAM`; `patches-rocm/README.md` has the full procedure. +The ROCm overlay in [`src/lib/mlx-cpp/patches-rocm/`](src/lib/mlx-cpp/patches-rocm/README.md) follows the pin too, and `make verify-rocm-overlay` (part of `make verify`) fails until it does: `patches-rocm/UPSTREAM` must name the new pin. The procedure is [`docs/mlxcelverse/rocm-overlay.md`](docs/mlxcelverse/rocm-overlay.md): `scripts/mlxcelverse/rocm_overlay.py retarget` 3-way merges the overlay's MLX core files onto the new pin; on an AMD host `scripts/mlxcelverse/check_api_drift.sh` lists the backend's compile errors and the primitives left without a ROCm `eval_gpu` (undefined symbols, since `libmlx` is static), which get a fix or a `NO_GPU` stub; `rocm_overlay.py drift` compares each core file line by line with the new pin plus the fork's own change and must match the reviewed `patches-rocm/CORE_RESIDUAL.diff`, which is what catches an overlay that was already wrong before the bump. Record each fix in `patches-rocm/LOCAL_FIXES.md`, run `make verify-rocm` on the AMD host (it includes the generation smoke from #1811), and add the "ROCm overlay" section described in that document to the PR body and to the technical report if there is one. ## Development environment diff --git a/Makefile b/Makefile index c31b66703..f554584d2 100644 --- a/Makefile +++ b/Makefile @@ -804,7 +804,7 @@ verify-rocm-smoke: ## ROCm smoke: build, link and generate on the GPU, asserting # "does a real forward pass still run on this device" answer even while the # suite is red. .PHONY: verify-rocm -verify-rocm: verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt verify-clippy-rocm verify-rocm-smoke verify-test-rocm ## Run the ROCm gate locally on an AMD host (issue #1811) +verify-rocm: verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-rocm-overlay verify-fmt verify-clippy-rocm verify-rocm-smoke verify-test-rocm ## Run the ROCm gate locally on an AMD host (issue #1811) @echo "$(GREEN)[verify-rocm] OK$(RESET)" .PHONY: verify-versions @@ -827,6 +827,23 @@ verify-kernel-port-dispatch: ## Assert every fused-kernel launcher chooses its p @echo "$(CYAN)[verify] kernel port dispatch...$(RESET)" @python3 scripts/ci/check_kernel_port_dispatch.py +# Offline half of the mlxcelverse ROCm overlay checks (issue #1813). It reads +# only files in this repository: patches-rocm/UPSTREAM must name the build's MLX +# pin (so a pin bump that skips the ROCm retarget fails here, on any host, not +# first on an AMD machine), the README counts must be the real ones, +# LOCAL_FIXES.md must be numbered without gaps, and CORE_RESIDUAL.diff must have +# been generated for the current commits and core file contents. It is in both +# `verify` and `verify-rocm` because pin bumps are usually made on a Mac. The +# online checks (`rocm_overlay.py drift`, `sync_from_fork.sh`, +# `check_api_drift.sh`) fetch or build and stay manual; see +# docs/mlxcelverse/rocm-overlay.md. rocm_overlay_test.sh is the tool's own +# negative coverage on a synthetic fork and pin history. +.PHONY: verify-rocm-overlay +verify-rocm-overlay: ## Assert the ROCm overlay records agree with the MLX pin and the tree (issue #1813) + @echo "$(CYAN)[verify] ROCm overlay records...$(RESET)" + @python3 scripts/mlxcelverse/rocm_overlay.py records + @bash scripts/mlxcelverse/rocm_overlay_test.sh + .PHONY: verify-binary-assets verify-binary-assets: ## Assert every tracked binary file is declared with a size budget @echo "$(CYAN)[verify] tracked binary assets...$(RESET)" @@ -972,7 +989,7 @@ bump-version: ## Release: set every version-tracking crate to VERSION and sync C @$(MAKE) --no-print-directory verify-versions .PHONY: verify -verify: verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt verify-clippy verify-test ## Run the full CI-faithful gate locally (recommended before push) +verify: verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-rocm-overlay verify-fmt verify-clippy verify-test ## Run the full CI-faithful gate locally (recommended before push) @echo "$(GREEN)[verify] OK: matches the nightly-verify GitHub Actions job$(RESET)" .PHONY: verify-clean diff --git a/docs/README.md b/docs/README.md index 4bf64d3b4..caf893486 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,6 +38,10 @@ Current GitHub-facing docs: 22. `embeddings.md` - the `/v1/embeddings` and `/v1/rerank` endpoints plus `mlxcel embed` and `mlxcel rerank`: embedding and reranker detection, pooling and scoring, multimodal and late-interaction inputs, request/response schemas, server flags, error codes, and family-registration guidance. 23. `llama-server-compat.md` - the verified llama-server b10621 compatibility boundary: how to read the machine-readable manifest under `compat/llama-server/b10621/`, the compatibility-policy states, the area sharding used by epic #1431, the CI gates, and the deterministic regeneration procedure. +## mlxcelverse maintenance + +`mlxcelverse/rocm-overlay.md` is the procedure for keeping the ROCm overlay in step with the MLX pin and with the NripeshN/mlx fork it is vendored from, including the `scripts/mlxcelverse/` tools and the `make verify-rocm-overlay` gate. `mlxcelverse/upstream/` holds the overlay's fork-side fixes prepared as pull requests for NripeshN/mlx, submitted by hand; its README is the index. + ## Architecture Decision Records `adr/` holds numbered Architecture Decision Records, one significant decision per file, immutable once Accepted. See `adr/README.md` for the index. diff --git a/docs/architecture.md b/docs/architecture.md index 8d7ae7c87..40ac7ec63 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -89,7 +89,10 @@ The ROCm overlay is vendored from the `rocm-support` branch of NripeshN/mlx (MIT), the head of the upstream draft ml-explore/mlx#2300. `patches-rocm/UPSTREAM` records the source commit and the MLX pin it was retargeted to, and `patches-rocm/LOCAL_FIXES.md` lists every change mlxcel -carries on top of it. Reorganizing the whole tree under an `mlxcelverse` +carries on top of it. `docs/mlxcelverse/rocm-overlay.md` is the procedure for +following both upstreams (pin bumps, fork syncs, and the `scripts/mlxcelverse/` +tools), and `docs/mlxcelverse/upstream/` holds the fixes prepared as pull +requests for the fork. Reorganizing the whole tree under an `mlxcelverse` directory name, with no change to build output, is tracked in lablup/mlxcel#1816. diff --git a/docs/mlxcelverse/rocm-overlay.md b/docs/mlxcelverse/rocm-overlay.md new file mode 100644 index 000000000..352260209 --- /dev/null +++ b/docs/mlxcelverse/rocm-overlay.md @@ -0,0 +1,84 @@ +# Maintaining the ROCm overlay + +The ROCm part of mlxcelverse (`src/lib/mlx-cpp/patches-rocm/`, described in its [README](../../src/lib/mlx-cpp/patches-rocm/README.md)) has two moving upstreams: the MLX pin (ml-explore/mlx, bumped regularly) and the fork its backend is vendored from (NripeshN/mlx `rocm-support`). This page is the procedure for following both, the tools that support it, and how fixes go back to the fork. Tooling and procedure come from lablup/mlxcel#1813. + +## The records + +Four files next to the overlay are records, never copied into MLX: + +| File | What it holds | +|---|---| +| `UPSTREAM` | The fork commit (`commit`), the fork's merge base with upstream MLX (`fork_upstream_merge_base`), and the MLX pin the core files were retargeted to (`retargeted_to_mlx_pin`). Every tool starts from these three commits. | +| `LOCAL_FIXES.md` | Every change the overlay carries relative to the fork commit, numbered, with the reason. Each backend file that differs from the fork must be named in an entry (the drift check enforces it). | +| `CORE_RESIDUAL.diff` | Generated. For each of the MLX core files, what the overlay carries beyond "MLX pin + the fork's own change to that file", with a note naming the LOCAL_FIXES item that explains it. | +| `README.md` | Layout, file counts, provenance. | + +The overlay itself is `CMakeLists.txt` plus `mlx/`: the backend under `mlx/backend/rocm/` and the MLX core files it hooks. + +## The tools + +All under `scripts/mlxcelverse/`. The engine is `rocm_overlay.py`; `sync_from_fork.sh` and `check_api_drift.sh` are the entry points the issue named. + +| Command | Network | What it does | Where it runs | +|---|---|---|---| +| `rocm_overlay.py records` | no | Checks the records against each other and the tree: `UPSTREAM` is well formed and names the build's MLX pin, the README counts are the real ones, `LOCAL_FIXES.md` is numbered without gaps, `CORE_RESIDUAL.diff` was generated for the current commits and current core-file contents and every entry has a note. | `make verify-rocm-overlay`, part of `make verify` and `make verify-rocm` | +| `rocm_overlay_test.sh` | no | The tool's own coverage on a synthetic fork and pin history, including the negative cases. | same target | +| `rocm_overlay.py drift` | fetches once | Rebuilds each core file as "pin + fork delta" and diffs the overlay against it; the result must match `CORE_RESIDUAL.diff`. Also requires every backend file that differs from the fork, and every fork hook outside the overlay, to be named in `LOCAL_FIXES.md`. `--write` rewrites the record, keeping its notes. | manual, after any core-file change, pin bump or fork sync | +| `rocm_overlay.py retarget [--to ]` | fetches once | 3-way merges each core file from the old pin to the new one (`git merge-file overlay old-pin new-pin`) and updates `retargeted_to_mlx_pin`. Default target: the build's pin. | manual, pin bump | +| `sync_from_fork.sh [] [--check \| --out DIR]` | fetches once | Moves the overlay to a new fork commit (details below) and updates `UPSTREAM`. `--check` syncs into a scratch copy and requires it to equal the committed overlay byte for byte. | manual, fork sync | +| `check_api_drift.sh [--mlx-commit ] [--rocm-from overlay\|fork:]` | fetches, builds | Builds MLX at a candidate commit with the ROCm files over it, `make -k`, and lists every compile error and every `mlx::core` symbol that is referenced but defined nowhere (a primitive without a ROCm `eval_gpu` only shows up that way, because libmlx is a static archive). | manual, AMD host with ROCm | + +Git objects come from a cache repository, `~/.cache/mlxcel/mlxcelverse/mlx.git` by default (`--git-dir` or `MLXCELVERSE_GIT_DIR` to use another clone; `--no-fetch` to stay offline). It holds both remotes and is filled on first use (a full MLX history, under 100 MB). The tools only fetch. + +Only `records` and the test are in the Makefile gates, because only they are offline and fast (about two seconds). `records` is in `make verify` as well as `make verify-rocm` because pin bumps are usually made on a Mac: a bump that skips the ROCm retarget now fails there, on any host. + +### Why a residual record rather than line counts + +The overlay's core files are whole-file copies: upstream at the pin with the fork's hooks merged in. The earlier bump check compared each overlay's +/- line counts against the old and the new upstream base. That confirms upstream's changes came in and ours stayed, but it cannot see an overlay that was already wrong before the bump; a Metal overlay once carried half of an upstream fix for months until a reviewer compared it line by line (TECHNICAL_REPORTS/1772, section 3). + +`drift` makes the line-by-line comparison mechanical. It rebuilds the file the overlay should be, the pin with the fork's own change to that file merged in (a 3-way merge with the fork's merge base as the base, conflict markers kept), and diffs the overlay against it. What is left is exactly what the overlay adds on its own: conflict resolutions and local fixes. At `81ba1c6a`/`75915908` that is 4 of the 15 core files, all explained by LOCAL_FIXES items 1 and 24; the other 11 reproduce byte for byte. A half-applied upstream change shows up as a new hunk that deletes the upstream line, and it has to be reviewed and noted before `records` passes again. + +## Bumping the MLX pin: the ROCm part + +The general procedure is "Bumping the MLX upstream pin" in `CONTRIBUTING.md`. For the ROCm overlay: + +1. Edit `GIT_TAG` as described there. From this point `make verify-rocm-overlay` fails until the overlay is retargeted. +2. `python3 scripts/mlxcelverse/rocm_overlay.py retarget`. It 3-way merges each core file onto the new pin and records the new pin in `UPSTREAM`. Resolve any conflicts it reports (they are left in the files with markers). +3. On an AMD host: `scripts/mlxcelverse/check_api_drift.sh`. Upstream API changes show up as compile errors in `mlx/backend/rocm/`, new primitives as undefined `eval_gpu` symbols; give those a `NO_GPU` stub in `mlx/backend/rocm/primitives.cpp` or an implementation. Re-run until the report is empty. A plain `cargo build --features rocm` finds the same things one error at a time. +4. `python3 scripts/mlxcelverse/rocm_overlay.py drift`. Review every hunk of the residual change it prints. A hunk that only moved is fine; a hunk that drops or alters an upstream line needs a reason. Then `drift --write`, and add or update the `# note` lines in `CORE_RESIDUAL.diff`. +5. Record every fix in `LOCAL_FIXES.md` (retarget fixes under "Retarget onto the MLX pin"), naming the files touched. +6. `make verify-rocm` on the AMD host: it runs `verify-rocm-overlay`, clippy, the `verify-rocm-smoke` generation smoke (lablup/mlxcel#1811) and the ROCm test gate. +7. In the PR body, add a "ROCm overlay" section (below). If the bump gets a technical report, give it the same section. + +## Syncing to a newer fork commit + +1. See what moved on the fork since the `UPSTREAM` commit, on GitHub or in the cache (`git -C ~/.cache/mlxcel/mlxcelverse/mlx.git log --oneline ..fork/rocm-support` once a run without a commit argument has fetched the branch). +2. `scripts/mlxcelverse/sync_from_fork.sh --out /tmp/rocm-sync` for a dry run, then without `--out` to sync in place. What it does: + - Backend files (`mlx/backend/rocm/`): 3-way merge of old fork commit, overlay and new fork commit. The difference between the overlay and the old fork commit is exactly the local fix list, so every LOCAL_FIXES entry is carried without replaying it by hand. Local-only files (`hadamard.hip`, `fft.hip`) are kept; new fork files are added; a file the fork deleted is deleted only if the overlay never changed it. + - Core files: 3-way merge from "pin + old fork delta" to "pin + new fork delta". The fork's diff against its own merge base is applied on the pin, so upstream changes the fork picked up by merging MLX are not mistaken for fork changes. + - It refuses when the new fork commit has merged MLX newer than the pin (retarget first, or pass `--allow-fork-ahead`), reports fork changes to MLX files the overlay does not carry, and updates `commit` and `fork_upstream_merge_base` in `UPSTREAM`. + - Conflicts are left in the files with markers and make the exit status 1. +3. Resolve conflicts. Where the fork changed code a local fix also changed, decide whether the fork now fixes the problem (then drop the LOCAL_FIXES entry and its upstream package) or the fix still applies. +4. `check_api_drift.sh` (or a `--features rocm` build), then `drift`, review, `drift --write`. +5. Update `LOCAL_FIXES.md` (its title names the fork commit) and `docs/mlxcelverse/upstream/README.md`. +6. `make verify-rocm`, and the same "ROCm overlay" section in the PR body. + +`sync_from_fork.sh --check` against the recorded commit reproduces the committed overlay byte for byte; if it does not, the overlay has changed outside the procedure. + +## The "ROCm overlay" section of a bump or sync PR + +Put this in the PR body, and in the technical report when there is one (as section 3 of `TECHNICAL_REPORTS/1772-mlx-pin-mxfp8-round-up-20260911.en.md` does for the Metal and CUDA overlays): + +```markdown +## ROCm overlay + +- Pin: -> (retarget) / Fork: -> (sync) +- Core files merged: of 15, conflicts in +- Residual (`CORE_RESIDUAL.diff`): unchanged / changed: +- API drift (`check_api_drift.sh`): +- `make verify-rocm` on : +``` + +## Sending fixes back to the fork + +Fixes that apply to the fork itself (LOCAL_FIXES entries marked "Applies to the fork") are prepared as PR packages under [`docs/mlxcelverse/upstream/`](upstream/README.md): a `git format-patch` against the fork head, a PR title and body, and a reproduction. They are submitted by hand by the maintainer; no tool here pushes to, forks, or opens anything on NripeshN/mlx or ml-explore/mlx. The index there lists each package, its LOCAL_FIXES items, whether it applies cleanly, and its link once submitted, and summarizes the fork's contribution rules and ml-explore/mlx's AI usage policy. diff --git a/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch new file mode 100644 index 000000000..75a4d005f --- /dev/null +++ b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch @@ -0,0 +1,245 @@ +From a6efedd7b612b3bc001cc2055ffba89f2a590940 Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): fix quantized matmul dispatch for mxfp4/mxfp8, f32 + and f16 + +Four fixes in quantized/qmm.hip, found running mxfp4, mxfp8 and f16 checkpoints on gfx1151. + +QuantizedMatmul (qmv) dispatched every mode with the activation dtype as the scale type, but mxfp4 and mxfp8 store one E8M0 byte per group. The kernels read the scales at 2 to 4 times their real stride, which gave NaN and out-of-bounds reads (a GPU memory fault in qmv_warp_shared_kernel). Non-affine modes now dispatch with uint8_t scales. + +GatherQMM: when a non-affine mode missed the affine-only fast paths, the generic dispatch instantiated gather_qmv_kernel with AFFINE=true and a T-typed scale pointer, so fp weights were dequantized with the affine formula (relative error 1.0 to 1e34 for mxfp8). Non-affine modes now launch gather_qmv_kernel; other fp group sizes throw instead of returning wrong values. + +QuantizedMatmul (tiled qmv) entered its branch for any activation dtype, launched qmv_tiled_kernel only for bf16 and f16, and then returned, so f32 activations produced no kernel launch and the output kept whatever the allocation held. The branch is now entered only for bf16/f16 with group size 32, 64 or 128; everything else takes the generic qmv dispatch. + +GatherQMM sent only bf16 activations to gather_qmv_warp_shared_kernel, which is already templated on the element type. f16 fell through to the generic gather_qmv_kernel, about 205 ms per call at a Mixtral-8x7B expert shape against 1.44 ms for the warp-shared kernel. f16 now takes the same kernel. +--- + mlx/backend/rocm/quantized/qmm.hip | 129 ++++++++++++++++++++++++----- + 1 file changed, 108 insertions(+), 21 deletions(-) + +diff --git a/mlx/backend/rocm/quantized/qmm.hip b/mlx/backend/rocm/quantized/qmm.hip +index a725ee7a..e10fc534 100644 +--- a/mlx/backend/rocm/quantized/qmm.hip ++++ b/mlx/backend/rocm/quantized/qmm.hip +@@ -3835,9 +3835,15 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { + // Restrict to 4/8-bit; 2/5/6-bit fall through to the warp-shared QMV kernel. + bool tiled_bits_supported = (bits_ == 4 || bits_ == 8); + // tile_n can be 4 on low-CU gfx1152 — still a valid tiled path. ++ // The launches below cover only bf16/f16 and group sizes ++ // 32/64/128, but the branch returns unconditionally, so any other input ++ // (f32 activations in particular) left the output unwritten and returned ++ // whatever the allocation held. Only enter when a kernel will launch. + if (use_tiled && tiled_bits_supported && use_fast_qmv && + !can_use_batched_qmv && tile_n >= 4 && +- mode_ == QuantizationMode::Affine) { ++ mode_ == QuantizationMode::Affine && ++ (x.dtype() == bfloat16 || x.dtype() == float16) && ++ (group_size_ == 32 || group_size_ == 64 || group_size_ == 128)) { + { + dim3 tiled_block(host_warp, tile_n); + const int n_tiles = (N + tile_n - 1) / tile_n; +@@ -4264,8 +4270,11 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { + using gs64 = std::integral_constant; + using gs128 = std::integral_constant; + ++ // mxfp4/mxfp8 store one E8M0 byte per group, not a T-typed scale. ++ using u8_id = local_type_identity; ++ + // Helper macro to dispatch group_size +-#define DISPATCH_GROUP_SIZE(type_tag, scale_tag, bits_tag) \ ++#define DISPATCH_GROUP_SIZE_IMPL(type_tag, scale_tag, bits_tag) \ + do { \ + switch (group_size_) { \ + case 32: \ +@@ -4283,6 +4292,14 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { + std::to_string(group_size_)); \ + } \ + } while (0) ++#define DISPATCH_GROUP_SIZE(type_tag, scale_tag, bits_tag) \ ++ do { \ ++ if (mode_ == QuantizationMode::Affine) { \ ++ DISPATCH_GROUP_SIZE_IMPL(type_tag, scale_tag, bits_tag); \ ++ } else { \ ++ DISPATCH_GROUP_SIZE_IMPL(type_tag, u8_id{}, bits_tag); \ ++ } \ ++ } while (0) + + if (x.dtype() == float32) { + if (bits_ == 8) +@@ -4334,6 +4351,7 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { + } + + #undef DISPATCH_GROUP_SIZE ++#undef DISPATCH_GROUP_SIZE_IMPL + } + } + +@@ -6242,16 +6260,20 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { + return; + } + ++ // f16 takes the same warp-shared kernel as bf16. It was gated ++ // to bf16 only, so f16 checkpoints fell through to ++ // the generic gather_qmv_kernel at about 200 ms per call. + if (use_fast_gather_qmv && mode_ == QuantizationMode::Affine && +- x.dtype() == bfloat16 && group_size_ == 64 && ++ (x.dtype() == bfloat16 || x.dtype() == float16) && group_size_ == 64 && + (bits_ == 4 || bits_ == 6 || bits_ == 8)) { +- auto launch_fast_kernel = [&](auto bits_tag) { ++ auto launch_fast_kernel = [&](auto type_tag, auto bits_tag) { ++ using T = typename decltype(type_tag)::type; + constexpr int BITS = decltype(bits_tag)::value; + if (fast_threads_per_col == 16) { + enc.add_kernel_node( + &rocm::gather_qmv_warp_shared_kernel< +- hip_bfloat16, +- hip_bfloat16, ++ T, ++ T, + BITS, + 64, + true, +@@ -6259,17 +6281,17 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { + fast_grid, + fast_block, + 0u, +- (const hip_bfloat16*)x_ptr, ++ (const T*)x_ptr, + (const uint8_t*)w_ptr, +- (const hip_bfloat16*)scales_ptr, +- (const hip_bfloat16*)biases_ptr, ++ (const T*)scales_ptr, ++ (const T*)biases_ptr, + li_ptr, + ri_ptr, + batch_shape_param, + lhs_idx_strides_param, + rhs_idx_strides_param, + batch_ndim, +- (hip_bfloat16*)out_ptr, ++ (T*)out_ptr, + B, + M, + N, +@@ -6281,8 +6303,8 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { + } else { + enc.add_kernel_node( + &rocm::gather_qmv_warp_shared_kernel< +- hip_bfloat16, +- hip_bfloat16, ++ T, ++ T, + BITS, + 64, + true, +@@ -6290,17 +6312,17 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { + fast_grid, + fast_block, + 0u, +- (const hip_bfloat16*)x_ptr, ++ (const T*)x_ptr, + (const uint8_t*)w_ptr, +- (const hip_bfloat16*)scales_ptr, +- (const hip_bfloat16*)biases_ptr, ++ (const T*)scales_ptr, ++ (const T*)biases_ptr, + li_ptr, + ri_ptr, + batch_shape_param, + lhs_idx_strides_param, + rhs_idx_strides_param, + batch_ndim, +- (hip_bfloat16*)out_ptr, ++ (T*)out_ptr, + B, + M, + N, +@@ -6312,18 +6334,83 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { + } + }; + +- if (bits_ == 4) { +- launch_fast_kernel(std::integral_constant{}); +- } else if (bits_ == 6) { +- launch_fast_kernel(std::integral_constant{}); ++ auto launch_fast_bits = [&](auto type_tag) { ++ if (bits_ == 4) { ++ launch_fast_kernel(type_tag, std::integral_constant{}); ++ } else if (bits_ == 6) { ++ launch_fast_kernel(type_tag, std::integral_constant{}); ++ } else { ++ launch_fast_kernel(type_tag, std::integral_constant{}); ++ } ++ }; ++ if (x.dtype() == float16) { ++ launch_fast_bits(local_type_identity<__half>{}); + } else { +- launch_fast_kernel(std::integral_constant{}); ++ launch_fast_bits(local_type_identity{}); + } + return; + } + + #define has_bias has_bias, use_sorted_rhs_schedule, implicit_x_batch_stride + ++ // mxfp4/mxfp8 store one E8M0 byte per group and no biases, ++ // but every launch below instantiates the kernel with AFFINE=true and a ++ // T-typed scale pointer, which dequantizes fp weights with the affine ++ // formula. Route non-affine modes to the AFFINE=false instantiation with ++ // uint8_t scales instead. ++ if (mode_ != QuantizationMode::Affine) { ++ if (group_size_ != 32 || (bits_ != 4 && bits_ != 8)) { ++ throw std::runtime_error( ++ "[GatherQMM::eval_gpu] ROCm supports mxfp4/mxfp8 only (group_size " ++ "32, bits 4 or 8); got bits=" + ++ std::to_string(bits_) + " group_size=" + std::to_string(group_size_)); ++ } ++ auto launch_fp = [&](auto type_tag, auto bits_tag) { ++ using T = typename decltype(type_tag)::type; ++ constexpr int BITS = decltype(bits_tag)::value; ++ enc.add_kernel_node( ++ &rocm::gather_qmv_kernel, ++ grid, ++ dim3(block_size), ++ 0u, ++ (const T*)x_ptr, ++ (const uint8_t*)w_ptr, ++ (const uint8_t*)scales_ptr, ++ (const uint8_t*)biases_ptr, ++ li_ptr, ++ ri_ptr, ++ batch_shape_param, ++ lhs_idx_strides_param, ++ rhs_idx_strides_param, ++ batch_ndim, ++ (T*)out_ptr, ++ B, ++ M, ++ N, ++ K, ++ E, ++ has_bias); ++ }; ++ auto launch_fp_bits = [&](auto type_tag) { ++ if (bits_ == 8) { ++ launch_fp(type_tag, std::integral_constant{}); ++ } else { ++ launch_fp(type_tag, std::integral_constant{}); ++ } ++ }; ++ if (x.dtype() == float32) { ++ launch_fp_bits(local_type_identity{}); ++ } else if (x.dtype() == float16) { ++ launch_fp_bits(local_type_identity<__half>{}); ++ } else if (x.dtype() == bfloat16) { ++ launch_fp_bits(local_type_identity{}); ++ } else { ++ throw std::runtime_error( ++ "[GatherQMM::eval_gpu] unsupported activation dtype for mxfp"); ++ } ++ return; ++ } ++ + if (x.dtype() == float32) { + if (bits_ == 8 && group_size_ == 32) { + enc.add_kernel_node( diff --git a/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/pr.md b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/pr.md new file mode 100644 index 000000000..ef65c9048 --- /dev/null +++ b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/pr.md @@ -0,0 +1,39 @@ +# fix(rocm): fix quantized matmul dispatch for mxfp4/mxfp8, f32 + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch`](0001-fix-rocm-fix-quantized-matmul-dispatch-for-mxfp4-mxf.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 8, 10, 12, 13 | +| Reproduction | `repro.py` (correctness; `--bench` adds the f16/bf16 gather_qmm timing) | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +Four fixes to the quantized matmul dispatch in `mlx/backend/rocm/quantized/qmm.hip`. Three are wrong results or GPU faults, one is a performance cliff. + +1. **mxfp4/mxfp8 scales in `QuantizedMatmul` (qmv).** Every mode was dispatched with the activation dtype as the scale type, but mxfp4 and mxfp8 store one E8M0 byte per group. The kernels read the scales at 2 to 4 times their real stride, which gives NaN and out-of-bounds reads; on gfx1151 it is a GPU memory fault in `qmv_warp_shared_kernel`. Non-affine modes now dispatch with `uint8_t` scales. +2. **mxfp4/mxfp8 in `GatherQMM`.** When a non-affine mode missed the affine-only fast paths, the generic dispatch instantiated `gather_qmv_kernel` with `AFFINE=true` and a `T`-typed scale pointer, so fp weights were dequantized with the affine formula (relative error 1.0 to 1e34 for mxfp8). Non-affine modes now launch `gather_qmv_kernel`; other fp group sizes throw instead of returning wrong values. After the fix mxfp8 and mxfp4 `gather_qmm` match a dequantized float32 reference (relative error about 3e-3 for bfloat16) with sorted and unsorted indices. +3. **float32 activations in the tiled qmv path.** The branch was entered for any activation dtype, launched `qmv_tiled_kernel` only for bfloat16 and float16, and then returned. float32 activations therefore produced no kernel launch, and the output was whatever the fresh allocation held (relative error from 1.0 up to 1e35 at every shape tried). The branch is now entered only for bfloat16/float16 with group size 32, 64 or 128; everything else takes the generic qmv dispatch, which matches a dequantized float32 reference (relative error about 1e-7). +4. **float16 in the fast `GatherQMM` path.** Only bfloat16 was sent to `gather_qmv_warp_shared_kernel`, which is already templated on the element type. float16 fell through to the generic `gather_qmv_kernel` at about 205 ms per call for a decode-shaped call at the Mixtral-8x7B expert shape (99.7% of GPU time in rocprofv3 while decoding `mlx-community/Mixtral-8x7B-Instruct-v0.1-4bit` at about 0.1 tok/s). The same call takes 1.44 ms on the warp-shared kernel and matches a dequantized float32 reference. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. + +## Reproduction + +`repro.py` compares GPU `quantized_matmul` and `gather_qmm` for affine 4-bit, mxfp4 and mxfp8 weights with float32, float16 and bfloat16 activations against a float32 reference from the CPU dequantization, each case in a child process with a timeout (the unfixed mxfp4/mxfp8 qmv can fault the GPU queue). `python repro.py --bench` also times float16 against bfloat16 `gather_qmm` at the Mixtral expert shape. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/repro.py b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/repro.py new file mode 100644 index 000000000..f5714dfb9 --- /dev/null +++ b/docs/mlxcelverse/upstream/01-quantized-matmul-dispatch/repro.py @@ -0,0 +1,140 @@ +"""Reproduction for "fix(rocm): fix quantized matmul dispatch for mxfp4/mxfp8, +f32 and f16". + +Compares GPU quantized_matmul and gather_qmm against a float32 reference built +from the CPU dequantization. Each case runs in a child process with a timeout, +because on rocm-support without the fix the mxfp4/mxfp8 quantized_matmul cases +can fault the GPU queue, which leaves the process spinning instead of failing. +Expected without the fix: mxfp4/mxfp8 quantized_matmul NaN or a fault, +mxfp4/mxfp8 gather_qmm relative error of 1 or more, float32 affine +quantized_matmul garbage. With the fix every case passes. + + python repro.py # correctness + python repro.py --bench # also time float16 against bfloat16 gather_qmm +""" + +import argparse +import subprocess +import sys +import time + +import mlx.core as mx + +TOL = {"float32": 1e-3, "float16": 1e-2, "bfloat16": 3e-2} +MODES = [("affine", 4, 64), ("mxfp4", 4, 32), ("mxfp8", 8, 32)] +DTYPES = ["float32", "float16", "bfloat16"] + + +def quantize(w, mode, bits, group_size, dtype=mx.float32): + """Quantize on the CPU. Affine scales and biases are cast to the activation + dtype, as a checkpoint stores them; otherwise MLX would promote the + activations to float32 and the half-precision kernels would never run.""" + out = mx.quantize(w, group_size=group_size, bits=bits, mode=mode, stream=mx.cpu) + wq, s, b = out[0], out[1], (out[2] if len(out) > 2 else None) + if mode == "affine": + s, b = s.astype(dtype), b.astype(dtype) + return wq, s, b + + +def rel_err(y, ref): + y = y.astype(mx.float32) + return (mx.abs(y - ref).max() / mx.maximum(mx.abs(ref).max(), 1e-6)).item() + + +def case_qmm(mode, bits, gs, dtype, m): + mx.random.seed(0) + n, k = 1024, 1024 + w = mx.random.normal((n, k)) * 0.05 + wq, s, b = quantize(w, mode, bits, gs, getattr(mx, dtype)) + wd = mx.dequantize(wq, s, b, group_size=gs, bits=bits, mode=mode, dtype=mx.float32, stream=mx.cpu) + x = mx.random.normal((m, k)).astype(getattr(mx, dtype)) + ref = mx.matmul(x.astype(mx.float32), wd.T, stream=mx.cpu) + y = mx.quantized_matmul( + x, wq, s, b, transpose=True, group_size=gs, bits=bits, mode=mode, stream=mx.gpu + ) + return rel_err(y, ref) + + +def case_gather(mode, bits, gs, dtype, sorted_indices): + mx.random.seed(1) + e, n, k, tokens = 4, 512, 1024, 8 + w = mx.random.normal((e, n, k)) * 0.05 + wq, s, b = quantize(w, mode, bits, gs, getattr(mx, dtype)) + wd = mx.dequantize(wq, s, b, group_size=gs, bits=bits, mode=mode, dtype=mx.float32, stream=mx.cpu) + x = mx.random.normal((tokens, 1, k)).astype(getattr(mx, dtype)) + idx = mx.array([3, 0, 2, 2, 1, 3, 0, 1], dtype=mx.uint32) + if sorted_indices: + idx = mx.sort(idx, stream=mx.cpu) + ref = mx.stack( + [mx.matmul(x[t].astype(mx.float32), wd[idx[t].item()].T, stream=mx.cpu) for t in range(tokens)] + ) + y = mx.gather_qmm( + x, wq, s, b, rhs_indices=idx, transpose=True, group_size=gs, bits=bits, + mode=mode, sorted_indices=sorted_indices, stream=mx.gpu, + ) + return rel_err(y, ref) + + +def cases(): + for mode, bits, gs in MODES: + for dtype in DTYPES: + for m in (1, 4): + yield f"qmm:{mode}:{bits}:{gs}:{dtype}:{m}" + for srt in (0, 1): + yield f"gather:{mode}:{bits}:{gs}:{dtype}:{srt}" + + +def run_case(name): + kind, mode, bits, gs, dtype, extra = name.split(":") + bits, gs, extra = int(bits), int(gs), int(extra) + if kind == "qmm": + err = case_qmm(mode, bits, gs, dtype, extra) + else: + err = case_gather(mode, bits, gs, dtype, bool(extra)) + ok = err <= TOL[dtype] # False for NaN + print(f"{'PASS' if ok else 'FAIL'} {name} rel_err={err:.3g}") + return 0 if ok else 1 + + +def bench(): + # Mixtral-8x7B expert shape, 4-bit affine, two tokens routed to two experts. + e, n, k = 8, 14336, 4096 + w = mx.random.normal((e, n, k)) * 0.02 + idx = mx.array([2, 5], dtype=mx.uint32) + for dtype in ("bfloat16", "float16"): + wq, s, b = quantize(w, "affine", 4, 64, getattr(mx, dtype)) + x = mx.random.normal((2, 1, k)).astype(getattr(mx, dtype)) + run = lambda: mx.eval(mx.gather_qmm(x, wq, s, b, rhs_indices=idx, group_size=64, bits=4, stream=mx.gpu)) + for _ in range(3): + run() + t0 = time.perf_counter() + for _ in range(20): + run() + print(f"gather_qmm {dtype}: {(time.perf_counter() - t0) / 20 * 1e3:.2f} ms per call") + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--case") + p.add_argument("--bench", action="store_true") + a = p.parse_args() + if a.case: + return run_case(a.case) + failed = 0 + for name in cases(): + try: + r = subprocess.run([sys.executable, __file__, "--case", name], timeout=120, + capture_output=True, text=True) + sys.stdout.write(r.stdout or f"FAIL {name} exit={r.returncode} {r.stderr.strip()[-200:]}\n") + failed += r.returncode != 0 + except subprocess.TimeoutExpired: + print(f"FAIL {name} timed out (GPU fault or hang)") + failed += 1 + if a.bench: + bench() + print(f"{failed} failing case(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch new file mode 100644 index 000000000..3895719ba --- /dev/null +++ b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch @@ -0,0 +1,74 @@ +From 5c4c2f9a9d9788c7e322e34fb7b713125360df4a Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): keep ArgReduce's grid inside the per-dimension + limit + +For short reduction axes ArgReduce::eval_gpu launched one 1024-thread block per output over a 1-D grid. AMD limits each grid dimension to 2^32 - 1 threads (gridDim * blockDim), so the launch failed with "invalid configuration argument" past about 4.2M outputs; mxfp4 quantize of a 4096x4096 matrix (an argmin over 16.7M groups) hits it. + +Axes of at most 64 elements now use a 64-thread block (whole wavefronts on wave32 and wave64), and the grid spills into y so each dimension stays under the limit. The kernel already indexes blockIdx.x + blockIdx.y * gridDim.x with a bounds check. GPU mxfp4 quantize is then bit-identical to the CPU at 4096x4096. +--- + mlx/backend/rocm/arg_reduce.hip | 44 ++++++++++++++++++++++++--------- + 1 file changed, 32 insertions(+), 12 deletions(-) + +diff --git a/mlx/backend/rocm/arg_reduce.hip b/mlx/backend/rocm/arg_reduce.hip +index 069d89ae..22d012e4 100644 +--- a/mlx/backend/rocm/arg_reduce.hip ++++ b/mlx/backend/rocm/arg_reduce.hip +@@ -1,5 +1,7 @@ + // Copyright © 2025 Apple Inc. + ++#include ++#include + #include "mlx/backend/common/utils.h" + #include "mlx/backend/rocm/device.h" + #include "mlx/backend/rocm/device/config.h" +@@ -287,18 +289,36 @@ void ArgReduce::eval_gpu(const std::vector& inputs, array& out) { + if (blocks_per_row > 64) blocks_per_row = 64; + + if (blocks_per_row <= 1) { +- constexpr int BLOCK_DIM = 1024; +- dim3 num_blocks = get_2d_grid_dims(out.shape(), out.strides()); +- dispatch_op([&](auto tt, auto opp) { +- using T = decltype(tt); +- using Op = decltype(opp); +- encoder.add_kernel_node( +- &rocm::arg_reduce_general, +- num_blocks, dim3(BLOCK_DIM), 0, +- gpu_ptr(in), gpu_ptr(out), out_size, +- shape_param, in_strides_param, out_strides_param, +- ndim, axis_stride, axis_size); +- }); ++ // One block per output element. AMD caps every grid ++ // dimension at 2^32 - 1 threads (gridDim * blockDim), so 1024-thread ++ // blocks over a 1-D grid failed to launch past about 4.2M outputs (the ++ // mxfp4 quantize argmin over 16.7M elements hit it). Short axes use a ++ // 64-thread block (whole wavefronts on both wave32 and wave64), and the ++ // grid spills into y so each dimension stays under the cap. The kernel ++ // already indexes blockIdx.x + blockIdx.y * gridDim.x with a bounds check. ++ auto launch_general = [&](auto block_tag) { ++ constexpr int BLOCK_DIM = decltype(block_tag)::value; ++ constexpr size_t kMaxBlocksX = static_cast(UINT32_MAX) / BLOCK_DIM; ++ size_t grid_x = std::min(out_size, kMaxBlocksX); ++ size_t grid_y = (out_size + grid_x - 1) / grid_x; ++ dim3 num_blocks( ++ static_cast(grid_x), static_cast(grid_y), 1); ++ dispatch_op([&](auto tt, auto opp) { ++ using T = decltype(tt); ++ using Op = decltype(opp); ++ encoder.add_kernel_node( ++ &rocm::arg_reduce_general, ++ num_blocks, dim3(BLOCK_DIM), 0, ++ gpu_ptr(in), gpu_ptr(out), out_size, ++ shape_param, in_strides_param, out_strides_param, ++ ndim, axis_stride, axis_size); ++ }); ++ }; ++ if (axis_size <= 64) { ++ launch_general(std::integral_constant{}); ++ } else { ++ launch_general(std::integral_constant{}); ++ } + return; + } + diff --git a/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md new file mode 100644 index 000000000..1f7a9522c --- /dev/null +++ b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md @@ -0,0 +1,36 @@ +# fix(rocm): keep ArgReduce's grid inside the per-dimension + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch`](0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 11 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +For short reduction axes `ArgReduce::eval_gpu` (`mlx/backend/rocm/arg_reduce.hip`) launched one 1024-thread block per output over a 1-D grid. AMD limits each grid dimension to 2^32 - 1 threads (gridDim times blockDim), so the launch failed with "invalid configuration argument" once there were more than about 4.2M outputs. mxfp4 `quantize` of a 4096x4096 matrix, an argmin over 16.7M groups, hits it. + +Axes of at most 64 elements now use a 64-thread block (whole wavefronts on both wave32 and wave64), and the grid spills into y so each dimension stays under the limit. `arg_reduce_general` already indexes `blockIdx.x + blockIdx.y * gridDim.x` with a bounds check, so the kernel is unchanged. Longer axes keep the 1024-thread block and get the same spill. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. With the change, GPU mxfp4 `quantize` is bit-identical to the CPU at 4096x4096. + +## Reproduction + +`repro.py` runs an argmin over 5M rows of 16 elements and an mxfp4 `quantize` of a 4096x4096 matrix on the GPU and compares both with the CPU stream exactly. Without the fix both raise. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/repro.py b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/repro.py new file mode 100644 index 000000000..1141fc80f --- /dev/null +++ b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/repro.py @@ -0,0 +1,52 @@ +"""Reproduction for "fix(rocm): keep ArgReduce's grid inside the per-dimension +limit". + +An argmin over a short last axis with more than about 4.2M outputs launched one +1024-thread block per output on a 1-D grid, past AMD's 2^32 - 1 threads per +grid dimension, and failed with "invalid configuration argument". mxfp4 +quantize of a 4096x4096 matrix reaches it through its per-group argmin. +Without the fix both cases raise; with it the GPU matches the CPU exactly. + + python repro.py +""" + +import sys + +import mlx.core as mx + + +def check(name, gpu, cpu): + ok = mx.array_equal(gpu, cpu).item() + print(f"{'PASS' if ok else 'FAIL'} {name}") + return ok + + +def main(): + failed = 0 + mx.random.seed(0) + x = mx.random.normal((5_000_000, 16)) + try: + failed += not check( + "argmin over 5M rows of 16", + mx.argmin(x, axis=-1, stream=mx.gpu), + mx.argmin(x, axis=-1, stream=mx.cpu), + ) + except Exception as e: # the unfixed launch raises + print(f"FAIL argmin over 5M rows of 16: {e}") + failed += 1 + + w = mx.random.normal((4096, 4096)) * 0.02 + try: + g = mx.quantize(w, group_size=32, bits=4, mode="mxfp4", stream=mx.gpu) + c = mx.quantize(w, group_size=32, bits=4, mode="mxfp4", stream=mx.cpu) + failed += not check("mxfp4 quantize 4096x4096 (weights)", g[0], c[0]) + failed += not check("mxfp4 quantize 4096x4096 (scales)", g[1], c[1]) + except Exception as e: + print(f"FAIL mxfp4 quantize 4096x4096: {e}") + failed += 1 + print(f"{failed} failing case(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/03-scatter-gather-index-types/0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch new file mode 100644 index 000000000..9245b838a --- /dev/null +++ b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch @@ -0,0 +1,290 @@ +From b38237da630973c64cd9fc7dad90599ba6fc724f Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): fix Scatter's size argument and widen narrow index + dtypes + +Scatter::eval_gpu passed upd_post_idx_size as int32_t while scatter_general_kernel declares it int64_t. add_kernel_node hands HIP the address of each argument, so the kernel read eight bytes from a four-byte value, got a huge divisor and computed index element 0 for every update: x[idx] = v, x.at[idx].add(v) and everything built on scatter (eye, identity, tri, diag) applied a single update. The argument is now int64_t, and add_kernel_node statically asserts that every argument has the size of its kernel parameter, so this class of mismatch fails to compile. + +Five dispatch sites in indexing.hip chose the kernel's index type with int32_t for int32/uint32 and int64_t for everything else, so int8, uint8, int16, uint16 and bool index arrays reached a kernel that reads eight bytes per element from a one or two byte buffer. On ROCm that is an HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION; the queue aborts and the process spins. Narrow index arrays are now widened to int32 once before the dispatch. Instantiating the kernels for all eight integer dtypes is also correct but took this translation unit from 26 s to 348 s to compile, because the index type multiplies the existing product of value dtypes and index-count branches; CUDA and Metal avoid that cost by compiling these kernels at runtime. +--- + mlx/backend/rocm/device.h | 28 ++++++++ + mlx/backend/rocm/indexing.hip | 122 +++++++++++++++++++++++++++++----- + 2 files changed, 134 insertions(+), 16 deletions(-) + +diff --git a/mlx/backend/rocm/device.h b/mlx/backend/rocm/device.h +index fad1f176..0943a691 100644 +--- a/mlx/backend/rocm/device.h ++++ b/mlx/backend/rocm/device.h +@@ -45,6 +45,25 @@ extern std::atomic g_inline_launches_; + void set_current_prim(const char* name); + void record_inline_launch(); + ++// add_kernel_node hands HIP the address of every argument, so ++// each argument must have the same size as the kernel parameter it lands in. ++// A narrower argument is read with garbage high bytes (Scatter once passed an ++// int32_t for an int64_t parameter and every update collapsed onto the first ++// index), so the sizes are checked at compile time. ++template ++struct kernel_param_types; ++template ++struct kernel_param_types { ++ using type = std::tuple; ++}; ++template ++constexpr bool kernel_arg_sizes_match(std::index_sequence) { ++ return ( ++ (sizeof(std::tuple_element_t) == ++ sizeof(std::decay_t>)) && ++ ...); ++} ++ + class CommandEncoder { + public: + explicit CommandEncoder(Device& d); +@@ -77,6 +96,15 @@ class CommandEncoder { + uint32_t smem_bytes, + Params&&... params) { + constexpr size_t num = sizeof...(Params); ++ using KernelArgs = typename kernel_param_types::type; ++ static_assert( ++ std::tuple_size_v == num, ++ "add_kernel_node: argument count differs from the kernel's parameters"); ++ static_assert( ++ kernel_arg_sizes_match>( ++ std::index_sequence_for{}), ++ "add_kernel_node: an argument's size differs from its kernel " ++ "parameter; pass the parameter's exact type"); + if (!use_hip_graphs()) { + // Immediate launch: kernelParams are consumed synchronously, so + // addresses of the caller's locals are fine. +diff --git a/mlx/backend/rocm/indexing.hip b/mlx/backend/rocm/indexing.hip +index d117d439..6bdbcaed 100644 +--- a/mlx/backend/rocm/indexing.hip ++++ b/mlx/backend/rocm/indexing.hip +@@ -22,6 +22,43 @@ + + namespace mlx::core { + ++namespace { ++ ++// Widen a narrow index array to int32. ++// ++// The dispatch sites below pick the kernel's index type with a two-way branch, ++// int32_t for int32 and uint32 and int64_t for everything else. That sent ++// int8, uint8, int16, uint16 and bool index arrays to a kernel that reads ++// eight bytes per element out of a one or two byte buffer, which on ROCm is an ++// HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION: the GPU queue aborts and the ++// process spins. MLX accepts any integer dtype for indices, so a `take` with a ++// uint8 index array (a 4-bit codebook lookup, for example) reaches it. ++// ++// Widening once here rather than instantiating every kernel for every integer ++// dtype is a deliberate trade. Measured on this backend, giving each of the ++// eight integer dtypes its own instantiation took the compile time of this ++// translation unit from 26 s to 348 s, because the index type multiplies an ++// existing product of twelve value dtypes and five to six index-count ++// branches. Widening keeps the two instantiations and costs one copy pass over ++// the index array, and only on the paths that are broken today. ++bool index_dtype_needs_widening(Dtype dt) { ++ return dt == int8 || dt == uint8 || dt == int16 || dt == uint16 || ++ dt == bool_; ++} ++ ++array widen_index_to_int32( ++ const array& idx, ++ rocm::CommandEncoder& encoder, ++ const Stream& s) { ++ array wide(idx.shape(), int32, nullptr, {}); ++ copy_gpu(idx, wide, CopyType::General, s); ++ encoder.add_temporary(wide); ++ return wide; ++} ++ ++} // namespace ++ ++ + namespace rocm { + + // General gather kernel - handles arbitrary indexing +@@ -605,6 +642,22 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { + int nidx = inputs.size() - 1; + int32_t idx_ndim = nidx > 0 ? inputs[1].ndim() : 0; + ++ // Widen narrow index dtypes once, so the ++ // two-way index-type dispatch below cannot read a one or two byte buffer as ++ // int64_t. Reserved so the references handed out below stay valid. ++ std::vector widened_idx; ++ widened_idx.reserve(nidx); ++ std::vector idx_arrays(std::max(nidx, 1), nullptr); ++ for (int i = 0; i < nidx; ++i) { ++ const array& given = inputs[i + 1]; ++ if (index_dtype_needs_widening(given.dtype())) { ++ widened_idx.push_back(widen_index_to_int32(given, encoder, s)); ++ idx_arrays[i] = &widened_idx.back(); ++ } else { ++ idx_arrays[i] = &given; ++ } ++ } ++ + uint32_t slice_size = std::accumulate( + slice_sizes_.begin(), slice_sizes_.end(), 1, std::multiplies()); + +@@ -620,16 +673,20 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { + std::vector h_indices_strides(std::max(nidx, 1) * std::max(idx_ndim, 1)); + + for (int i = 0; i < nidx; ++i) { +- h_indices[i] = gpu_ptr(inputs[i + 1]); ++ const array& idx_in = *idx_arrays[i]; ++ h_indices[i] = gpu_ptr(idx_in); + for (int j = 0; j < idx_ndim; ++j) { +- h_indices_shape[i * idx_ndim + j] = inputs[i + 1].shape(j); +- h_indices_strides[i * idx_ndim + j] = inputs[i + 1].strides(j); ++ h_indices_shape[i * idx_ndim + j] = idx_in.shape(j); ++ h_indices_strides[i * idx_ndim + j] = idx_in.strides(j); + } + } + + for (const auto& in : inputs) { + encoder.set_input_array(in); + } ++ for (const auto& widened : widened_idx) { ++ encoder.set_input_array(widened); ++ } + encoder.set_output_array(out); + + int64_t total = out.size(); +@@ -640,7 +697,7 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { + // contiguous (flattened) index -> coalesced per-row copy (gather_rows_kernel). + bool fast_rows = (nidx == 1) && (axes_.size() == 1) && (axes_[0] == 0) && + src.ndim() >= 2 && src.flags().row_contiguous && +- inputs[1].flags().contiguous && ++ idx_arrays[0]->flags().contiguous && + ((int)slice_sizes_.size() == (int)src.ndim()) && (slice_sizes_[0] == 1); + if (fast_rows) { + for (int d = 1; d < (int)src.ndim(); ++d) { +@@ -668,7 +725,7 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { + int64_t n_rows = total / (int64_t)slice_size; + dim3 grid((unsigned int)n_rows); + dim3 blk(256); +- Dtype it = inputs[1].dtype(); ++ Dtype it = idx_arrays[0]->dtype(); + int32_t src_dim0 = (int32_t)src.shape(0); + #define LAUNCH_ROWS(T, IdxT) \ + encoder.add_kernel_node((&rocm::gather_rows_kernel), grid, blk, 0, \ +@@ -725,7 +782,7 @@ void Gather::eval_gpu(const std::vector& inputs, array& out) { + default: LAUNCH_GATHER(T, IdxT, 8); break; \ + } + +- Dtype idx_dtype = nidx > 0 ? inputs[1].dtype() : int32; ++ Dtype idx_dtype = nidx > 0 ? idx_arrays[0]->dtype() : int32; + + if (idx_dtype == int32 || idx_dtype == uint32) { + switch (out.dtype()) { +@@ -793,11 +850,31 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { + int nidx = axes_.size(); + int32_t idx_ndim = nidx > 0 ? inputs[1].ndim() : 0; + +- int32_t upd_post_idx_size = std::accumulate( ++ // Widen narrow index dtypes once, so the ++ // two-way index-type dispatch below cannot read a one or two byte buffer as ++ // int64_t. Reserved so the references handed out below stay valid. ++ std::vector widened_idx; ++ widened_idx.reserve(nidx); ++ std::vector idx_arrays(std::max(nidx, 1), nullptr); ++ for (int i = 0; i < nidx; ++i) { ++ const array& given = inputs[i + 1]; ++ if (index_dtype_needs_widening(given.dtype())) { ++ widened_idx.push_back(widen_index_to_int32(given, encoder, s)); ++ idx_arrays[i] = &widened_idx.back(); ++ } else { ++ idx_arrays[i] = &given; ++ } ++ } ++ ++ // int64_t to match scatter_general_kernel's parameter. ++ // add_kernel_node passes argument addresses straight to HIP, so an int32_t ++ // here was read as an 8-byte value with garbage high bytes; every index ++ // element then collapsed onto the first index (only one update landed). ++ int64_t upd_post_idx_size = std::accumulate( + upd.shape().begin() + idx_ndim, + upd.shape().end(), +- 1, +- std::multiplies()); ++ int64_t{1}, ++ std::multiplies()); + + // Prepare host data for parameters + std::vector h_upd_shape(upd.shape().begin(), upd.shape().end()); +@@ -812,16 +889,20 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { + std::vector h_indices_strides(std::max(nidx, 1) * std::max(idx_ndim, 1)); + + for (int i = 0; i < nidx; ++i) { +- h_indices[i] = gpu_ptr(inputs[i + 1]); ++ const array& idx_in = *idx_arrays[i]; ++ h_indices[i] = gpu_ptr(idx_in); + for (int j = 0; j < idx_ndim; ++j) { +- h_indices_shape[i * idx_ndim + j] = inputs[i + 1].shape(j); +- h_indices_strides[i * idx_ndim + j] = inputs[i + 1].strides(j); ++ h_indices_shape[i * idx_ndim + j] = idx_in.shape(j); ++ h_indices_strides[i * idx_ndim + j] = idx_in.strides(j); + } + } + + for (const auto& in : inputs) { + encoder.set_input_array(in); + } ++ for (const auto& widened : widened_idx) { ++ encoder.set_input_array(widened); ++ } + encoder.set_output_array(out); + + int64_t total = upd.size(); +@@ -887,7 +968,7 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { + default: DISPATCH_REDUCE(T, IdxT, 4); break; \ + } + +- Dtype idx_dtype = nidx > 0 ? inputs[1].dtype() : int32; ++ Dtype idx_dtype = nidx > 0 ? idx_arrays[0]->dtype() : int32; + + if (idx_dtype == int32 || idx_dtype == uint32) { + switch (out.dtype()) { +@@ -934,11 +1015,16 @@ void Scatter::eval_gpu(const std::vector& inputs, array& out) { + void GatherAxis::eval_gpu(const std::vector& inputs, array& out) { + assert(inputs.size() > 1); + const auto& src = inputs[0]; +- const auto& idx = inputs[1]; + + auto& s = stream(); + auto& encoder = rocm::get_command_encoder(s); + ++ // See index_dtype_needs_widening. An array ++ // is a handle, so binding by value here costs nothing when no widening runs. ++ array idx = index_dtype_needs_widening(inputs[1].dtype()) ++ ? widen_index_to_int32(inputs[1], encoder, s) ++ : inputs[1]; ++ + out.set_data(mlx::core::rocm::malloc_async(out.nbytes(), encoder)); + if (out.size() == 0) { + return; +@@ -1064,7 +1150,6 @@ void GatherAxis::eval_gpu(const std::vector& inputs, array& out) { + void ScatterAxis::eval_gpu(const std::vector& inputs, array& out) { + assert(inputs.size() > 2); + const auto& src = inputs[0]; +- const auto& idx = inputs[1]; + const auto& upd = inputs[2]; + + // Copy src into out +@@ -1084,7 +1169,12 @@ void ScatterAxis::eval_gpu(const std::vector& inputs, array& out) { + + auto& s = stream(); + auto& encoder = rocm::get_command_encoder(s); +- ++ ++ // See index_dtype_needs_widening. ++ array idx = index_dtype_needs_widening(inputs[1].dtype()) ++ ? widen_index_to_int32(inputs[1], encoder, s) ++ : inputs[1]; ++ + encoder.set_input_array(upd); + encoder.set_input_array(idx); + encoder.set_output_array(out); diff --git a/docs/mlxcelverse/upstream/03-scatter-gather-index-types/pr.md b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/pr.md new file mode 100644 index 000000000..b19345759 --- /dev/null +++ b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/pr.md @@ -0,0 +1,39 @@ +# fix(rocm): fix Scatter's size argument and widen narrow index + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch`](0001-fix-rocm-fix-Scatter-s-size-argument-and-widen-narro.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 14, 17 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +Two indexing fixes in `mlx/backend/rocm/indexing.hip`, plus a compile-time guard in `mlx/backend/rocm/device.h`. + +1. **Scatter applied every update to the first index.** `Scatter::eval_gpu` passed `upd_post_idx_size` as `int32_t` while `scatter_general_kernel` declares it `int64_t`. `CommandEncoder::add_kernel_node` hands HIP the address of each argument, so the kernel read eight bytes from a four-byte value, got a huge divisor, and computed index element 0 for every update. `x[idx] = v`, `x.at[idx].add(v)` and everything built on scatter (`eye`, `identity`, `tri`, `diag`) applied a single update. The argument is now `int64_t`, and `add_kernel_node` statically asserts that every argument has the size of its kernel parameter, so this class of mismatch fails to compile (checked by reintroducing the `int32_t`). +2. **Narrow index dtypes in Gather and Scatter.** Five dispatch sites picked the kernel's index type with `int32_t` for int32/uint32 and `int64_t` for everything else, so int8, uint8, int16, uint16 and bool index arrays reached a kernel that reads eight bytes per element from a one or two byte buffer. On ROCm that is an `HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION`: the queue aborts and the process spins instead of failing. A `take` with uint8 indices, as in a 4-bit codebook lookup, is enough to hit it. Narrow index arrays are now widened to int32 once, before the dispatch. + +Why widening rather than one instantiation per index dtype: that alternative was implemented and measured first. It is also correct, but it takes `indexing.hip` from 26 s to 348 s to compile, because the index type multiplies the existing product of twelve value dtypes and five to six index-count branches. The Metal and CUDA backends do instantiate per index dtype, but they compile these kernels at runtime and cache them, so the combinations cost nothing at build time; this backend compiles `indexing.hip` ahead of time. Upstream already uses the same move for the offset type (int32 or int64 by size). The cost here is one copy pass over the index array, only for narrow dtypes. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. Verified against the CPU stream for int8, uint8, int16, uint16, int32, uint32, int64 and uint64 indices at four index shapes. + +## Reproduction + +`repro.py` compares scatter (`.at[].add`, item assignment, `eye`, `tri`) and gather/scatter with every integer index dtype against the CPU stream, each case in a child process with a timeout because the unfixed narrow-dtype cases fault the GPU queue. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/03-scatter-gather-index-types/repro.py b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/repro.py new file mode 100644 index 000000000..b151e7d0f --- /dev/null +++ b/docs/mlxcelverse/upstream/03-scatter-gather-index-types/repro.py @@ -0,0 +1,92 @@ +"""Reproduction for "fix(rocm): fix Scatter's size argument and widen narrow +index dtypes". + +Scatter: every update landed on the first index, so x.at[idx].add(v), eye(), +tri() and friends were wrong on the GPU. Narrow index dtypes: a gather or +scatter with int8, uint8, int16, uint16 or bool indices read eight bytes per +index and faulted the GPU queue (the process then spins instead of failing), so +every case runs in a child process with a timeout. With the fix every case +matches the CPU stream exactly. + + python repro.py +""" + +import argparse +import subprocess +import sys + +import mlx.core as mx + +INDEX_DTYPES = ["int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64"] + + +def on(stream, fn): + with mx.stream(stream): + out = fn() + mx.eval(out) + return out + + +def scatter_cases(): + idx = mx.array([1, 4, 7]) + upd = mx.array([1.0, 2.0, 3.0]) + return { + "scatter add": lambda: mx.zeros((10,)).at[idx].add(upd), + "scatter set": lambda: _set(idx, upd), + "eye": lambda: mx.eye(5), + "tri": lambda: mx.tri(5, 7, k=1), + } + + +def _set(idx, upd): + a = mx.zeros((10,)) + a[idx] = upd + return a + + +def index_case(dtype, kind): + dt = getattr(mx, dtype) + src = mx.arange(300, dtype=mx.float32).reshape(30, 10) + idx = mx.array([0, 5, 17, 29, 5], dtype=dt) + if kind == "take": + return lambda: mx.take(src, idx, axis=0) + if kind == "getitem": + return lambda: src[idx] + return lambda: mx.zeros((30, 10)).at[idx].add(1.0) + + +def run_case(name): + if name.startswith("index:"): + _, dtype, kind = name.split(":") + fn = index_case(dtype, kind) + else: + fn = scatter_cases()[name] + ok = mx.array_equal(on(mx.gpu, fn), on(mx.cpu, fn)).item() + print(f"{'PASS' if ok else 'FAIL'} {name}") + return 0 if ok else 1 + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--case") + a = p.parse_args() + if a.case: + return run_case(a.case) + names = list(scatter_cases()) + names += [f"index:{d}:{k}" for d in INDEX_DTYPES for k in ("take", "getitem", "scatter")] + failed = 0 + for name in names: + try: + r = subprocess.run([sys.executable, __file__, "--case", name], timeout=60, + capture_output=True, text=True) + sys.stdout.write(r.stdout or f"FAIL {name} exit={r.returncode} {r.stderr.strip()[-200:]}\n") + failed += r.returncode != 0 + except subprocess.TimeoutExpired: + print(f"FAIL {name} timed out (GPU fault or hang)") + failed += 1 + print(f"{failed} failing case(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch new file mode 100644 index 000000000..fc848cd21 --- /dev/null +++ b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch @@ -0,0 +1,198 @@ +From a7f221302c69d4430d42c3b16362b13522c8162f Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): fix SliceUpdate grid-stride tail and source + donation + +SliceUpdate::eval_gpu's reduce path (Sum, Prod, Max, Min, as built by slice_update_add/prod/max/min and x.at[a:b].add(...)) clamps its grid at 65535 blocks of 256 threads, but slice_update_op_kernel handled one NWORK-element chunk per thread and never read gridDim. Every element past 65535 * 256 * NWORK (16,776,960 for NWORK=1) kept the input value, with no error. The kernel now loops over chunks with a stride of gridDim.x * blockDim.x * NWORK and recomputes the output and update indices for each chunk; a chunk starts at a multiple of NWORK, which divides the innermost dimension, so it never crosses a row. + +SliceUpdate::eval_gpu and DynamicSliceUpdate::eval_gpu gave the source's buffer to the output whenever the buffer had one owner, without checking whether the source array itself was still referenced. A second handle to the array, or an unevaluated node that reads it, holds the array but not its buffer, so the update was written into an array that could still be read. Both now go through copy_gpu, which donates only when is_donatable(in, out) holds, as upstream CUDA's SliceUpdate and the upstream DynamicSliceUpdate do. DynamicSliceUpdate also forced donation whenever rocm::graph_active() was set; that override is removed because it donated buffers other arrays shared, and it could not fire while use_hip_graphs() returns false. If HIP graphs are turned back on, accumulation under capture has to be handled in the capture. +--- + mlx/backend/gpu/primitives.cpp | 36 +++---------- + mlx/backend/rocm/indexing.hip | 96 +++++++++++++++++++--------------- + 2 files changed, 61 insertions(+), 71 deletions(-) + +diff --git a/mlx/backend/gpu/primitives.cpp b/mlx/backend/gpu/primitives.cpp +index 65df8579..e2a37bba 100644 +--- a/mlx/backend/gpu/primitives.cpp ++++ b/mlx/backend/gpu/primitives.cpp +@@ -18,13 +18,6 @@ + #define MLX_PROFILER_RANGE(message) + #endif + +-#if defined(MLX_USE_ROCM) +-namespace mlx::core::rocm { +-// True from HIP-graph capture start until the captured graph is destroyed. +-bool graph_active(); +-} // namespace mlx::core::rocm +-#endif +- + namespace mlx::core { + + void AsStrided::eval_gpu(const std::vector& inputs, array& out) { +@@ -142,29 +135,14 @@ void DynamicSliceUpdate::eval_gpu( + return; + } + +- // Donate the input buffer when uniquely owned, else copy. During HIP-graph +- // capture the async pipeline inflates the buffer's use_count, forcing a full +- // copy into a FRESH buffer — the captured graph then reconstructs +- // (frozen capture input + current row) every replay and loses accumulation +- // (e.g. a growing KV cache → frozen/repeated tokens). For a contiguous, +- // fully-materialized buffer the in-place donation is the intended semantics, +- // so force it while a graph is being captured. ++ // Copy or donate the input to the output. copy_gpu donates only when ++ // is_donatable(in, out) holds, which requires the source array itself, not ++ // just its data buffer, to have no other reference. + auto s = stream(); +- bool can_donate = in.data_shared_ptr() != nullptr && in.flags().contiguous && +- in.data_size() == in.size() && +- (in.data_shared_ptr().use_count() == 1 +-#if defined(MLX_USE_ROCM) +- || mlx::core::rocm::graph_active() +-#endif +- ); +- if (can_donate) { +- out.copy_shared_buffer(in); +- } else { +- auto ctype = in.flags().contiguous && in.size() == in.data_size() +- ? CopyType::Vector +- : CopyType::General; +- copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, s); +- } ++ auto ctype = in.flags().contiguous && in.size() == in.data_size() ++ ? CopyType::Vector ++ : CopyType::General; ++ copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, s); + + auto out_offset = + compute_dynamic_offset(start_indices, out.strides(), axes_, s); +diff --git a/mlx/backend/rocm/indexing.hip b/mlx/backend/rocm/indexing.hip +index d117d439..74d43787 100644 +--- a/mlx/backend/rocm/indexing.hip ++++ b/mlx/backend/rocm/indexing.hip +@@ -466,44 +466,57 @@ __global__ void slice_update_op_kernel( + int64_t output_offset) { + Op op; + +- IdxT idx = (IdxT(blockIdx.x) * IdxT(blockDim.x) + IdxT(threadIdx.x)) * NWORK; +- IdxT out_idx; +- IdxT update_idx; +- +- if constexpr (OUT_ROW_CONTIG) { +- out_idx = idx; +- } else { +- out_idx = elem_to_loc( +- idx, update_shape.data_, output_strides.data_, update_ndim); +- } +- +- if constexpr (!UPD_SCALAR) { +- if constexpr (UPD_ROW_CONTIG) { +- update_idx = idx; +- } else { +- update_idx = elem_to_loc( +- idx, update_shape.data_, update_strides.data_, update_ndim); +- } +- } else { +- update_idx = 0; +- } +- + out += output_offset; + +- for (int j = 0; j < NWORK && idx < update_size; j++) { +- out[out_idx] = op(out[out_idx], updates[update_idx]); +- idx++; ++ // Grid-stride over NWORK-element chunks: the launch site caps the grid at ++ // 65535 blocks, so a one-chunk-per-thread kernel would silently leave the ++ // tail of a large update unapplied. Each chunk starts at a multiple of ++ // NWORK and the launch site only picks NWORK when it divides the innermost ++ // dimension, so a chunk never crosses an innermost row and the per-element ++ // stride increments below stay valid. ++ const IdxT chunk_stride = ++ IdxT(gridDim.x) * IdxT(blockDim.x) * IdxT(NWORK); ++ for (IdxT base = ++ (IdxT(blockIdx.x) * IdxT(blockDim.x) + IdxT(threadIdx.x)) * NWORK; ++ base < update_size; ++ base += chunk_stride) { ++ IdxT idx = base; ++ IdxT out_idx; ++ IdxT update_idx; + + if constexpr (OUT_ROW_CONTIG) { + out_idx = idx; + } else { +- out_idx += output_strides[update_ndim - 1]; ++ out_idx = elem_to_loc( ++ idx, update_shape.data_, output_strides.data_, update_ndim); ++ } ++ ++ if constexpr (!UPD_SCALAR) { ++ if constexpr (UPD_ROW_CONTIG) { ++ update_idx = idx; ++ } else { ++ update_idx = elem_to_loc( ++ idx, update_shape.data_, update_strides.data_, update_ndim); ++ } ++ } else { ++ update_idx = 0; + } + +- if constexpr (UPD_ROW_CONTIG) { +- update_idx = idx; +- } else if constexpr (!UPD_SCALAR) { +- update_idx += update_strides[update_ndim - 1]; ++ for (int j = 0; j < NWORK && idx < update_size; j++) { ++ out[out_idx] = op(out[out_idx], updates[update_idx]); ++ idx++; ++ ++ if constexpr (OUT_ROW_CONTIG) { ++ out_idx = idx; ++ } else { ++ out_idx += output_strides[update_ndim - 1]; ++ } ++ ++ if constexpr (UPD_ROW_CONTIG) { ++ update_idx = idx; ++ } else if constexpr (!UPD_SCALAR) { ++ update_idx += update_strides[update_ndim - 1]; ++ } + } + } + } +@@ -1236,18 +1249,14 @@ void SliceUpdate::eval_gpu(const std::vector& inputs, array& out) { + return; + } + +- // Donate the input buffer when uniquely owned, else copy. +- bool can_donate = in.data_shared_ptr() != nullptr && +- in.data_shared_ptr().use_count() == 1 && in.flags().contiguous && +- in.data_size() == in.size(); +- if (can_donate) { +- out.copy_shared_buffer(in); +- } else { +- auto ctype = in.flags().contiguous && in.size() == in.data_size() +- ? CopyType::Vector +- : CopyType::General; +- copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, stream()); +- } ++ // Copy or donate the input to the output. copy_gpu donates only when ++ // is_donatable(in, out) holds, which requires the source array itself, not ++ // just its data buffer, to have no other reference: a caller still holding ++ // the source must not see the update. ++ auto ctype = in.flags().contiguous && in.size() == in.data_size() ++ ? CopyType::Vector ++ : CopyType::General; ++ copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, stream()); + + // Calculate out strides, initial offset + auto [data_offset, out_strides] = +@@ -1298,6 +1307,9 @@ void SliceUpdate::eval_gpu(const std::vector& inputs, array& out) { + int64_t update_size = upd.size(); + int block_size = 256; + int64_t adjusted_size = (update_size + nwork - 1) / nwork; ++ // The 65535-block clamp is safe only because slice_update_op_kernel is ++ // grid-stride: threads past the clamped grid's reach pick up the remaining ++ // NWORK-element chunks in later iterations. + int num_blocks = static_cast( + std::min((adjusted_size + block_size - 1) / block_size, (int64_t)65535)); + diff --git a/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/pr.md b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/pr.md new file mode 100644 index 000000000..9acceba9e --- /dev/null +++ b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/pr.md @@ -0,0 +1,37 @@ +# fix(rocm): fix SliceUpdate grid-stride tail and source + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch`](0001-fix-rocm-fix-SliceUpdate-grid-stride-tail-and-source.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 21, 24 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +Two `SliceUpdate` fixes, in `mlx/backend/rocm/indexing.hip` and `mlx/backend/gpu/primitives.cpp`. + +1. **Reductions left the tail of large updates unapplied.** The reduce path of `SliceUpdate::eval_gpu` (Sum, Prod, Max, Min, as built by `x.at[a:b].add(...)` and the other `.at` slice reductions, and by `SliceUpdate::vjp` for Prod) clamps its grid at 65535 blocks of 256 threads, but `slice_update_op_kernel` handled one `NWORK`-element chunk per thread and never read `gridDim`. `NWORK` is 4, 2 or 1 by what divides the innermost dimension, so every element past 65535 x 256 x `NWORK` (16,776,960, 33,553,920 or 67,107,840) kept its input value, with no error. The kernel now loops over chunks with a stride of `gridDim.x * blockDim.x * NWORK`, recomputing the output and update indices for each chunk (through `elem_to_loc` on the non-contiguous branches, as the old prologue did). A chunk starts at a multiple of `NWORK`, which divides the innermost dimension, so it never crosses a row. The clamp stays, as in the other grid-stride kernels. Measured before the fix: contiguous Sum updates of 16,777,217, 33,554,434 and 67,108,868 elements left exactly the last 257, 514 and 1028 elements unapplied, and a Max through a [4099, 4097] update into columns 1..4098 of a [4099, 4099] output left 16,643; with the fix every case matches the CPU stream. +2. **A still-referenced source was donated.** `SliceUpdate::eval_gpu` and `DynamicSliceUpdate::eval_gpu` gave the source's buffer to the output whenever the buffer had one owner (`in.data_shared_ptr().use_count() == 1`), without checking whether the source array itself was still referenced. A second handle to the same array, or an unevaluated node that reads it, holds the array but not its buffer, so the update was written into an array that could still be read. Upstream's `array::is_donatable()` requires both counts to be one, and Metal and CUDA reach it through `copy_gpu`. Both primitives now call `copy_gpu` exactly as the CUDA `SliceUpdate::eval_gpu` and the upstream `DynamicSliceUpdate::eval_gpu` do. `DynamicSliceUpdate` also forced donation whenever `rocm::graph_active()` was set, for KV cache accumulation under HIP graph capture; that override is removed because it donated even a buffer other arrays shared, and it could not fire: `graph_active()` is set only when `use_hip_graphs()` is true, and `use_hip_graphs()` returns a constant `false`; the decode capture path (`decode_capture_begin`) sets `g_decode_capturing`, not `graph_active()`. If HIP graphs are turned back on, accumulation under capture has to be solved in the capture. A source dropped before evaluation is still donated, which is the usual `cache = slice_update(cache, ...)` pattern; decode throughput on gfx1151 was unchanged within run-to-run spread (under 1%) on Qwen3-0.6B-4bit and Llama-3.1-8B-Instruct-4bit. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. + +## Reproduction + +`repro.py` runs a contiguous Sum over 16,777,217 int32 elements and a strided Max above the clamp against the CPU stream, then holds a source array through GPU `.at[].add`, `.at[].maximum` and `mx.slice_update` with an array start and checks that the source is unchanged. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/repro.py b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/repro.py new file mode 100644 index 000000000..3d3cd0bc2 --- /dev/null +++ b/docs/mlxcelverse/upstream/04-slice-update-tail-and-donation/repro.py @@ -0,0 +1,76 @@ +"""Reproduction for "fix(rocm): fix SliceUpdate grid-stride tail and source +donation". + +Tail: x.at[a:b].add(u) and the other slice reductions left every element past +65535 * 256 * NWORK unapplied (the last 257 of 16,777,217 for a contiguous +int32 update with an odd innermost size). Donation: a source array the caller +still holds was overwritten by a GPU slice update when its buffer had a single +owner. Without the fix the tail cases report mismatching elements and the +donation cases report a modified source; with it everything matches the CPU. + + python repro.py +""" + +import sys + +import mlx.core as mx + + +def compare(name, fn): + with mx.stream(mx.gpu): + g = fn() + mx.eval(g) + with mx.stream(mx.cpu): + c = fn() + mx.eval(c) + bad = mx.sum(g != c).item() + print(f"{'PASS' if bad == 0 else 'FAIL'} {name}: {bad} mismatching element(s)") + return bad == 0 + + +def tail_cases(): + n = 16_777_217 # odd, so NWORK = 1 and the clamp covers 16,776,960 + ok = compare( + "contiguous Sum, 16,777,217 elements", + lambda: mx.zeros((n + 3,), dtype=mx.int32).at[1 : n + 1].add(mx.ones((n,), dtype=mx.int32)), + ) + m = 4099 + ok &= compare( + "strided Max, [4099, 4097] into [4099, 4099]", + lambda: mx.zeros((m, m), dtype=mx.int32).at[:, 1 : m - 1].maximum( + mx.arange(m * (m - 2), dtype=mx.int32).reshape(m, m - 2) + ), + ) + return ok + + +def held_source(name, update): + with mx.stream(mx.gpu): + src = mx.arange(8, dtype=mx.int32) + mx.eval(src) + out = update(src) + mx.eval(out) + ok = mx.array_equal(src, mx.arange(8, dtype=mx.int32)).item() + print(f"{'PASS' if ok else 'FAIL'} {name}: held source {'unchanged' if ok else 'was overwritten'}") + return ok + + +def donation_cases(): + ones = mx.ones((2,), dtype=mx.int32) + ok = held_source("SliceUpdate Sum", lambda s: s.at[2:4].add(ones)) + ok &= held_source("SliceUpdate Max", lambda s: s.at[2:4].maximum(ones * 100)) + ok &= held_source( + "DynamicSliceUpdate", + lambda s: mx.slice_update(s, ones * 100, mx.array([2]), axes=[0]), + ) + return ok + + +def main(): + ok = tail_cases() + ok &= donation_cases() + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/05-hadamard/0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch b/docs/mlxcelverse/upstream/05-hadamard/0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch new file mode 100644 index 000000000..f3e0b44a4 --- /dev/null +++ b/docs/mlxcelverse/upstream/05-hadamard/0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch @@ -0,0 +1,215 @@ +From 90edcab36a61ab33bf12ed3a4329774af48990c2 Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] feat(rocm): implement Hadamard for power-of-two sizes up to + 8192 + +Hadamard was a NO_GPU stub. hadamard.hip adds a single-stage radix-2 butterfly in shared memory for m == 1 and a power-of-two last axis up to 8192, which covers the head dimensions (64, 128, 256) of Hadamard-rotated KV caches. Larger n and the m in {12, 20, 28} families throw a message naming the limit rather than returning a wrong answer; the CUDA backend covers them by generating a radix-m codelet through NVRTC. The scale is the primitive's scale_ (MLX defaults it to 1/sqrt(n)), accumulation is in float for every element type, and like the CUDA kernel the grid is clamped at 65535 blocks with a grid-stride loop. + +Checked against the Metal backend on an M1 Ultra: norm ratio 1.000000 within 1e-5 at n = 64, 128 and 256; float16 relative RMS about 2.0e-4 (Metal 3.8e-4 to 5.0e-4, because this kernel keeps the butterfly in float and rounds once); float32 relative RMS about 1e-7. +--- + mlx/backend/rocm/CMakeLists.txt | 1 + + mlx/backend/rocm/hadamard.hip | 169 ++++++++++++++++++++++++++++++++ + mlx/backend/rocm/primitives.cpp | 1 - + 3 files changed, 170 insertions(+), 1 deletion(-) + create mode 100644 mlx/backend/rocm/hadamard.hip + +diff --git a/mlx/backend/rocm/CMakeLists.txt b/mlx/backend/rocm/CMakeLists.txt +index f1854457..f7eeeb8e 100644 +--- a/mlx/backend/rocm/CMakeLists.txt ++++ b/mlx/backend/rocm/CMakeLists.txt +@@ -148,6 +148,7 @@ set(HIP_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_general_input.hip + ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_general_dynamic.hip + ${CMAKE_CURRENT_SOURCE_DIR}/distributed.hip ++ ${CMAKE_CURRENT_SOURCE_DIR}/hadamard.hip + ${CMAKE_CURRENT_SOURCE_DIR}/indexing.hip + ${CMAKE_CURRENT_SOURCE_DIR}/layer_norm.hip + ${CMAKE_CURRENT_SOURCE_DIR}/logsumexp.hip +diff --git a/mlx/backend/rocm/hadamard.hip b/mlx/backend/rocm/hadamard.hip +new file mode 100644 +index 00000000..61631994 +--- /dev/null ++++ b/mlx/backend/rocm/hadamard.hip +@@ -0,0 +1,169 @@ ++// Copyright © 2025 Apple Inc. ++ ++// Hadamard transform for the ROCm backend. ++// ++// The CUDA backend builds this kernel through NVRTC with a generated codelet ++// for the radix-m matrix, which lets it cover every size MLX accepts, that is ++// n = m * 2^k for m in {1, 12, 20, 28}. This port is compiled ahead of time and ++// covers m == 1 with n a power of two up to 8192, which includes the head ++// dimensions (64, 128, 256) that Hadamard-rotated KV caches use. The n > 8192 ++// case is where the CUDA path splits the transform into two stages; this file ++// throws for it, and for m != 1, rather than returning a wrong answer. ++// ++// The scale comes from the primitive, not from this file. MLX defaults it to ++// 1/sqrt(n), the orthonormal scaling that makes the transform an involution: ++// hadamard_transform(hadamard_transform(x)) returns x. A kernel that hardcoded ++// a different scale would pass a round-trip test that only checks shape or ++// finiteness while silently corrupting values. ++// ++// The involution is a property of that one scale, not of the transform. For the ++// unscaled sign matrix H, H * H = n * I, so applying scale s twice gives ++// s^2 * n * I: the round trip is the identity only at s = 1/sqrt(n). At any ++// other scale the inverse scale is 1/(s * n) and the forward norm ratio is ++// s * sqrt(n). ++ ++#include "mlx/backend/rocm/device.h" ++#include "mlx/backend/rocm/allocator.h" ++#include "mlx/backend/rocm/kernel_utils.hpp" ++#include "mlx/backend/common/hadamard.h" ++#include "mlx/backend/gpu/copy.h" ++#include "mlx/dtype_utils.h" ++#include "mlx/primitives.h" ++ ++#include ++ ++#include ++#include ++#include ++#include ++ ++namespace mlx::core { ++ ++namespace rocm { ++ ++// Largest transform this single-stage kernel accepts. It is bounded by shared ++// memory: the buffer holds `n` floats, so 8192 needs 32 KiB of the 64 KiB a ++// gfx11 workgroup has. It is also the size at which the CUDA path switches to ++// its two-stage decomposition, so the two backends agree on where the simple ++// path ends. ++constexpr int MAX_HADAMARD_N = 8192; ++constexpr int HADAMARD_BLOCK_THREADS = 256; ++ ++// One block per transform, grid-stride over transforms so a capped grid still ++// covers every row. Accumulation is in float regardless of the element type, ++// which matches what the CUDA kernel does and keeps the fp16 round-trip inside ++// a single rounding of the input. ++template ++__global__ void hadamard_pow2_kernel( ++ const T* in, ++ T* out, ++ float scale, ++ int n, ++ int64_t num_transforms) { ++ extern __shared__ float buf[]; ++ ++ for (int64_t transform = blockIdx.x; transform < num_transforms; ++ transform += gridDim.x) { ++ const int64_t base = transform * static_cast(n); ++ ++ for (int idx = threadIdx.x; idx < n; idx += blockDim.x) { ++ buf[idx] = static_cast(in[base + idx]); ++ } ++ __syncthreads(); ++ ++ // Iterative radix-2 butterfly. At stage `h` the pair (j, j + h) is ++ // combined, where j skips the elements already paired at this stage. ++ for (int h = 1; h < n; h <<= 1) { ++ for (int i = threadIdx.x; i < n / 2; i += blockDim.x) { ++ const int k = i & (h - 1); ++ const int j = ((i - k) << 1) + k; ++ const float a = buf[j]; ++ const float b = buf[j + h]; ++ buf[j] = a + b; ++ buf[j + h] = a - b; ++ } ++ __syncthreads(); ++ } ++ ++ for (int idx = threadIdx.x; idx < n; idx += blockDim.x) { ++ out[base + idx] = static_cast(buf[idx] * scale); ++ } ++ __syncthreads(); ++ } ++} ++ ++} // namespace rocm ++ ++namespace { ++ ++void hadamard_pow2_contiguous( ++ const array& x, ++ array& y, ++ int n, ++ float scale, ++ const Stream& s) { ++ auto& encoder = rocm::get_command_encoder(s); ++ ++ const int64_t num_transforms = x.size() / n; ++ // Clamp like the CUDA backend does; the kernel is grid-stride, so the two ++ // together cover the whole input. ++ const int num_blocks = ++ static_cast(std::min(num_transforms, 65535)); ++ const int block_threads = std::min(rocm::HADAMARD_BLOCK_THREADS, n / 2); ++ const size_t shared_bytes = static_cast(n) * sizeof(float); ++ ++ encoder.set_input_array(x); ++ encoder.set_output_array(y); ++ ++ dispatch_float_types(x.dtype(), "[hadamard]", [&](auto type_tag) { ++ using T = hip_type_t; ++ encoder.add_kernel_node( ++ &rocm::hadamard_pow2_kernel, ++ dim3(num_blocks), ++ dim3(block_threads), ++ shared_bytes, ++ gpu_ptr(x), ++ gpu_ptr(y), ++ scale, ++ n, ++ num_transforms); ++ }); ++} ++ ++} // namespace ++ ++void Hadamard::eval_gpu(const std::vector& inputs, array& out) { ++ assert(inputs.size() == 1); ++ ++ auto& in = inputs[0]; ++ if (in.dtype() != float16 && in.dtype() != bfloat16 && ++ in.dtype() != float32) { ++ throw std::invalid_argument("[hadamard] Unsupported type."); ++ } ++ ++ // n = m * 2^k where m is in {1, 12, 20, 28}. ++ auto [n, m] = decompose_hadamard(in.shape().back()); ++ if (m != 1 || n > rocm::MAX_HADAMARD_N) { ++ std::ostringstream msg; ++ msg << "[hadamard] ROCm supports a power-of-two last axis up to " ++ << rocm::MAX_HADAMARD_N << "; got " << in.shape().back() ++ << " (m=" << m << ", n=" << n << ")."; ++ throw std::invalid_argument(msg.str()); ++ } ++ ++ auto& s = stream(); ++ auto& encoder = rocm::get_command_encoder(s); ++ if (in.flags().row_contiguous) { ++ if (in.is_donatable()) { ++ out.copy_shared_buffer(in); ++ } else { ++ out.set_data(mlx::core::rocm::malloc_async(out.nbytes(), encoder)); ++ } ++ hadamard_pow2_contiguous(in, out, n, scale_, s); ++ } else { ++ copy_gpu(in, out, CopyType::General, s); ++ hadamard_pow2_contiguous(out, out, n, scale_, s); ++ } ++} ++ ++} // namespace mlx::core +diff --git a/mlx/backend/rocm/primitives.cpp b/mlx/backend/rocm/primitives.cpp +index 0815bdb2..6ec2764e 100644 +--- a/mlx/backend/rocm/primitives.cpp ++++ b/mlx/backend/rocm/primitives.cpp +@@ -30,7 +30,6 @@ namespace mlx::core { + + NO_GPU(BlockMaskedMM) + NO_GPU(FFT) +-NO_GPU(Hadamard) + NO_GPU_MULTI(LUF) + NO_GPU_MULTI(QRF) + NO_GPU(QQMatmul) diff --git a/docs/mlxcelverse/upstream/05-hadamard/pr.md b/docs/mlxcelverse/upstream/05-hadamard/pr.md new file mode 100644 index 000000000..6d73f9baf --- /dev/null +++ b/docs/mlxcelverse/upstream/05-hadamard/pr.md @@ -0,0 +1,38 @@ +# feat(rocm): implement Hadamard for power-of-two sizes up to + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch`](0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none (conflicts only textually with the FFT PR in `CMakeLists.txt` and `primitives.cpp`, adjacent lines) | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 16 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +`Hadamard` is a `NO_GPU` stub on this backend, so `mx.hadamard_transform` raises on the GPU. This adds `mlx/backend/rocm/hadamard.hip`: a single-stage radix-2 butterfly in shared memory for `m == 1` and a power-of-two last axis up to 8192, which covers the head dimensions (64, 128, 256) that Hadamard-rotated KV caches use. + +- Larger `n` and the `m` in {12, 20, 28} families throw an error naming the limit rather than returning a wrong answer. The CUDA backend covers them by generating a radix-m codelet through NVRTC, which has no ahead-of-time equivalent here. +- The scale is the primitive's `scale_`, which MLX defaults to `1/sqrt(n)`, so the default transform stays an involution. Accumulation is in float regardless of the element type. +- Like the CUDA kernel, the grid is clamped at 65535 blocks and the kernel is grid-stride. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. Against the Metal backend on an M1 Ultra: norm ratio 1.000000 within 1e-5 at n = 64, 128 and 256; float16 relative RMS about 2.0e-4 (Metal 3.8e-4 to 5.0e-4), float32 about 1e-7 (matching Metal). The float16 figure is lower than Metal's because this kernel keeps the butterfly in float in shared memory and rounds once on the way out, where Metal rounds between stages. + +## Reproduction + +`repro.py` compares the GPU with the CPU stream for n = 64 to 8192 in float32, float16 and bfloat16, checks the round trip, and checks that n = 16384 and n = 768 (m = 12) raise. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/05-hadamard/repro.py b/docs/mlxcelverse/upstream/05-hadamard/repro.py new file mode 100644 index 000000000..0ade616c3 --- /dev/null +++ b/docs/mlxcelverse/upstream/05-hadamard/repro.py @@ -0,0 +1,53 @@ +"""Reproduction for "feat(rocm): implement Hadamard for power-of-two sizes up +to 8192". + +Without the change mx.hadamard_transform raises on the GPU (NO_GPU stub). With +it the GPU matches the CPU stream for power-of-two sizes up to 8192, the +default-scale transform is its own inverse, and unsupported sizes raise a +message naming the limit instead of returning a wrong answer. + + python repro.py +""" + +import sys + +import mlx.core as mx + +TOL = {"float32": 1e-5, "float16": 2e-3, "bfloat16": 2e-2} + + +def rel_rms(a, b): + a, b = a.astype(mx.float32), b.astype(mx.float32) + return (mx.sqrt(mx.mean((a - b) ** 2)) / mx.sqrt(mx.mean(b**2))).item() + + +def main(): + failed = 0 + mx.random.seed(0) + for n in (64, 128, 256, 1024, 8192): + for dtype in ("float32", "float16", "bfloat16"): + x = mx.random.normal((3, 5, n)).astype(getattr(mx, dtype)) + try: + g = mx.hadamard_transform(x, stream=mx.gpu) + c = mx.hadamard_transform(x, stream=mx.cpu) + back = mx.hadamard_transform(g, stream=mx.gpu) + e1, e2 = rel_rms(g, c), rel_rms(back, x) + ok = e1 <= TOL[dtype] and e2 <= 2 * TOL[dtype] + print(f"{'PASS' if ok else 'FAIL'} n={n} {dtype}: vs CPU {e1:.2e}, round trip {e2:.2e}") + except Exception as e: + ok = False + print(f"FAIL n={n} {dtype}: {e}") + failed += not ok + for n in (16384, 12 * 64): + try: + mx.eval(mx.hadamard_transform(mx.ones((1, n)), stream=mx.gpu)) + print(f"FAIL n={n}: expected an error naming the limit") + failed += 1 + except Exception as e: + print(f"PASS n={n} raises: {e}") + print(f"{failed} failing case(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch new file mode 100644 index 000000000..98ec70f3e --- /dev/null +++ b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch @@ -0,0 +1,221 @@ +From ab584361d1861610250b1bb13e404a05389dce5b Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): set blocking-sync before the first HIP queue is + created + +rocm::device() set hipSetDeviceFlags(hipDeviceScheduleBlockingSync), but the allocator runs first: the first unified allocation's host read calls hipStreamQuery(nullptr) in allocator::Buffer::raw_ptr(), which creates the null stream's queue while active wait is still on, and CLR gives that queue non-interrupt completion signals. After the flag flips, CLR (HwQueueTracker::ActiveSignal in rocvirtual.cpp) no longer swaps such a signal for an interrupt one when a command needs a completion handler, and ROCr rejects async handlers on non-interrupt signals (hsa_amd_signal_async_handler() failed to set the handler! under AMD_LOG_LEVEL=4). The marker a device-wide sync enqueues on the null stream then never signals its waiter, and hipFree hangs in Device::SyncAllStreams. hipFFT's plan destroy was the first thing to hit it, but any hipFree or device-wide sync with pending null-stream work can. + +rocm::ensure_device_flags() sets the flag once per device index, thread-safe and touching only that device, and runs before every path that can create a queue ahead of rocm::device(): unified_malloc, both branches of raw_ptr(), the async-pool free streams in the RocmAllocator constructor, gpu::init() and staged_write's device sync. rocm::device() uses it too. If hipSetDevice fails the device is not recorded, so a later call retries; if hipSetDeviceFlags fails one line goes to stderr, so a hang of this kind is not silent. + +Measured on gfx1151 with HIP 7.15.26333: with the fix, hipSetDeviceFlags precedes the first "Created SWq" line in the AMD_LOG_LEVEL=3 log. A standalone HIP program without MLX (null-stream query, then the flag, then hipMalloc, a synchronous hipMemcpy, a null-stream kernel and hipFree in a loop) hangs at its first hipFree and completes without the early query. +--- + mlx/backend/rocm/allocator.cpp | 12 +++++ + mlx/backend/rocm/device.cpp | 85 +++++++++++++++++++++++++++++---- + mlx/backend/rocm/device.h | 14 ++++++ + mlx/backend/rocm/eval.cpp | 2 + + mlx/backend/rocm/host_stage.cpp | 4 ++ + 5 files changed, 108 insertions(+), 9 deletions(-) + +diff --git a/mlx/backend/rocm/allocator.cpp b/mlx/backend/rocm/allocator.cpp +index 4489295f..bf49ba4b 100644 +--- a/mlx/backend/rocm/allocator.cpp ++++ b/mlx/backend/rocm/allocator.cpp +@@ -130,6 +130,9 @@ inline void* unified_malloc(size_t size, bool& is_managed) { + void* data = nullptr; + hipError_t err; + ensure_mlx_device_current(); ++ // Often the first HIP work in the process, ahead of rocm::device(): put the ++ // device in blocking-sync mode before any queue exists on it. ++ ensure_current_device_flags(); + + if (use_finegrained()) { + err = hipExtMallocWithFlags(&data, size, hipDeviceMallocFinegrained); +@@ -326,6 +329,9 @@ RocmAllocator::RocmAllocator() + } + } + (void)hipSetDevice(i); ++ // The free stream below is a queue on device i; flag the device first. ++ // This loop already switches to every pooled device. ++ ensure_device_flags(i); + hipMemPool_t pool = nullptr; + if (hipDeviceGetDefaultMemPool(&pool, i) == hipSuccess) { + mem_pools_[i] = pool; +@@ -925,11 +931,17 @@ void* Buffer::raw_ptr() { + auto& cbuf = *static_cast(ptr_); + + if (cbuf.device == -1) { ++ // The null-stream query creates the null stream's queue on first use, and ++ // a host read can come before rocm::device() ever runs. Flag the device ++ // the query is about to touch first, or that queue keeps completion ++ // signals a later hipFree waits on forever. ++ rocm::ensure_current_device_flags(); + if (hipStreamQuery(nullptr) != hipSuccess) { + (void)hipStreamSynchronize(nullptr); + } + } else { + // Discrete: host shadow (CUDA: move_to_unified_memory). ++ rocm::ensure_current_device_flags(); + (void)hipDeviceSynchronize(); + rocm::allocator().ensure_host_shadow(cbuf); + return cbuf.host_shadow; +diff --git a/mlx/backend/rocm/device.cpp b/mlx/backend/rocm/device.cpp +index f71cd702..25c294d7 100644 +--- a/mlx/backend/rocm/device.cpp ++++ b/mlx/backend/rocm/device.cpp +@@ -1182,19 +1182,86 @@ std::unordered_map& get_devices() { + return devices; + } + ++void ensure_device_flags(int device_index) { ++ if (device_index < 0) { ++ return; ++ } ++ // Lock-free fast path for the common indices: this runs on every unified ++ // allocation and every host read of a unified buffer. ++ static std::atomic flagged_low{0}; ++ const bool low = device_index < 64; ++ const uint64_t bit = low ? (uint64_t{1} << device_index) : 0; ++ if (low && (flagged_low.load(std::memory_order_acquire) & bit)) { ++ return; ++ } ++ static std::mutex mu; ++ static std::vector flagged_high; ++ std::lock_guard lock(mu); ++ if (low ? (flagged_low.load(std::memory_order_relaxed) & bit) != 0 ++ : std::find(flagged_high.begin(), flagged_high.end(), device_index) != ++ flagged_high.end()) { ++ return; ++ } ++ // Per index, not one process-wide bool: if device 0 were flagged first a ++ // global gate would leave device 1 unflagged. hipSetDeviceFlags applies to ++ // the current device, so switch only when the caller is on another one and ++ // switch back after. Never iterate every device: creating a context or queue ++ // on the other GPU of a multi-GPU host is what wedges the discrete GPU's ++ // queue over a TB5 link, so touch only this device. ++ int prev = -1; ++ const bool have_prev = hipGetDevice(&prev) == hipSuccess; ++ const bool switched = !have_prev || prev != device_index; ++ if (switched && hipSetDevice(device_index) != hipSuccess) { ++ // Could not bind the device, so the flags cannot be applied to it. Clear ++ // the error and do not record the device as flagged, so a later call can ++ // try again. ++ (void)hipGetLastError(); ++ return; ++ } ++ const hipError_t flags_err = hipSetDeviceFlags(hipDeviceScheduleBlockingSync); ++ if (flags_err != hipSuccess) { ++ // Not fatal (the device then keeps its default wait mode, as it would ++ // have before this helper existed); clear the error so it does not ++ // surface from an unrelated later call. Recorded as done either way so a ++ // failing device is not retried on every allocation. Say so once on ++ // stderr: without blocking-sync a hang in hipFree would otherwise be ++ // silent. ++ (void)hipGetLastError(); ++ std::fprintf( ++ stderr, ++ "[ROCm] hipSetDeviceFlags(hipDeviceScheduleBlockingSync) failed " ++ "for device %d: %s\n", ++ device_index, ++ hipGetErrorString(flags_err)); ++ } ++ if (switched && have_prev) { ++ (void)hipSetDevice(prev); ++ } ++ if (low) { ++ flagged_low.fetch_or(bit, std::memory_order_release); ++ } else { ++ flagged_high.push_back(device_index); ++ } ++} ++ ++void ensure_current_device_flags() { ++ int current = -1; ++ if (hipGetDevice(¤t) == hipSuccess) { ++ ensure_device_flags(current); ++ } ++} ++ + Device& device(mlx::core::Device device) { + auto& devices = get_devices(); + auto it = devices.find(device.index); + if (it == devices.end()) { +- // Set blocking sync flags on THIS device (per index, not a single global +- // bool: if device 0 were touched first the global gate would leave device 1 +- // unflagged). Must happen while this device is current and before its +- // context is created — i.e. before the Device is constructed. Iterating +- // every device would create a context/queue on the other GPU too; on a +- // multi-GPU host that cross-device coexistence is what wedges the discrete +- // GPU's queue over a TB5 link, so touch only this device. +- hipSetDevice(device.index); +- hipSetDeviceFlags(hipDeviceScheduleBlockingSync); ++ // Bind this device (callers rely on it being current afterwards) and make ++ // sure it is in blocking-sync mode before the Device and its streams are ++ // constructed. The first unified allocation usually got there first, since ++ // the allocator runs before the first stream exists; see ++ // ensure_device_flags() for why the order matters. ++ (void)hipSetDevice(device.index); ++ ensure_device_flags(device.index); + it = devices.try_emplace(device.index, device.index).first; + } + return it->second; +diff --git a/mlx/backend/rocm/device.h b/mlx/backend/rocm/device.h +index fad1f176..94293b36 100644 +--- a/mlx/backend/rocm/device.h ++++ b/mlx/backend/rocm/device.h +@@ -398,6 +398,20 @@ class Device { + std::mutex encoders_mtx_; + }; + ++// Put `device_index` in blocking-sync wait mode (hipDeviceScheduleBlockingSync) ++// once per process, before MLX creates the first HIP queue on it. Thread-safe; ++// touches only that device, and leaves the calling thread's current device as ++// it found it. Call it before any HIP call that can create a queue on a device ++// (a null-stream query, sync, copy or launch, or a stream creation) on a path ++// that can run before rocm::device(): the order is what matters. CLR types a ++// queue's completion signals by the wait mode in force when the queue is ++// created and never re-types them, so a queue created before the flag keeps ++// signals that cannot carry the completion handlers a later hipFree or device ++// sync attaches, and that wait never returns. ++void ensure_device_flags(int device_index); ++// ensure_device_flags() for the calling thread's current HIP device. ++void ensure_current_device_flags(); ++ + Device& device(mlx::core::Device device); + CommandEncoder& get_command_encoder(Stream s); + void clear_all_encoders(); +diff --git a/mlx/backend/rocm/eval.cpp b/mlx/backend/rocm/eval.cpp +index 0bb032b1..a0988394 100644 +--- a/mlx/backend/rocm/eval.cpp ++++ b/mlx/backend/rocm/eval.cpp +@@ -24,6 +24,8 @@ void init() { + auto d = mlx::core::default_device(); + if (d.type == mlx::core::Device::gpu) { + (void)hipSetDevice(d.index); ++ // Before the hipFree below or anything else can create a queue. ++ rocm::ensure_device_flags(d.index); + } + hipFree(nullptr); + } +diff --git a/mlx/backend/rocm/host_stage.cpp b/mlx/backend/rocm/host_stage.cpp +index f0b555aa..96d6e89f 100644 +--- a/mlx/backend/rocm/host_stage.cpp ++++ b/mlx/backend/rocm/host_stage.cpp +@@ -8,6 +8,7 @@ + #include + + #include "mlx/array.h" ++#include "mlx/backend/rocm/device.h" + #include "mlx/io/load.h" + + namespace mlx::core::rocm { +@@ -80,6 +81,9 @@ bool staged_write(io::Writer& out, const array& a) { + // stream is drained. Sync the device so the DMA cannot observe a half-written + // buffer: MLX ROCm streams are hipStreamNonBlocking, so a plain hipMemcpy on + // the NULL stream does NOT order against them. ++ // A checkpoint save can be the first sync on this thread's device; flag it ++ // before the sync touches the null stream. ++ rocm::ensure_current_device_flags(); + if (hipDeviceSynchronize() != hipSuccess) { + (void)hipGetLastError(); + return false; diff --git a/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md new file mode 100644 index 000000000..a1cb3f49b --- /dev/null +++ b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md @@ -0,0 +1,36 @@ +# fix(rocm): set blocking-sync before the first HIP queue is + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch`](0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none (the FFT PR depends on this one) | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 20 | +| Reproduction | `repro.hip` (standalone HIP program, no MLX) | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +`rocm::device()` calls `hipSetDeviceFlags(hipDeviceScheduleBlockingSync)`, but the allocator runs before it. The first unified allocation's host read calls `hipStreamQuery(nullptr)` in `allocator::Buffer::raw_ptr()`, which creates the null stream's queue while active wait is still on, and CLR gives that queue non-interrupt completion signals. After the flag flips, CLR (`HwQueueTracker::ActiveSignal` in `rocvirtual.cpp`) no longer swaps such a signal for an interrupt one when a command needs a completion handler, and ROCr rejects async handlers on non-interrupt signals (`hsa_amd_signal_async_handler() failed to set the handler!` under `AMD_LOG_LEVEL=4`). The marker a device-wide sync enqueues on the null stream then never signals its waiter: `hipFree` hangs in `std::condition_variable::wait` below `Device::SyncAllStreams`. rocFFT's plan destroy was the first code to hit it (a hipFFT plan cache hung at its first eviction), but any `hipFree` or device-wide sync with pending null-stream work can. + +`rocm::ensure_device_flags()` in `device.cpp` sets the flag once per device index. It is thread-safe, touches only that device, and restores the caller's current device. It runs before every path that can create a queue ahead of `rocm::device()`: `unified_malloc`, both branches of `raw_ptr()` and the async-pool free streams in the `RocmAllocator` constructor (`allocator.cpp`), `gpu::init()` (`eval.cpp`) and the device sync in `staged_write` (`host_stage.cpp`); `rocm::device()` uses it too. If `hipSetDevice` fails the device is not recorded, so a later call retries; if `hipSetDeviceFlags` fails, one line goes to stderr naming the device and the HIP error, so a return of this hang is not silent. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. With the change, `hipSetDeviceFlags` precedes the first `Created SWq` line in the `AMD_LOG_LEVEL=3` log (before it came after the null stream's queue), and a hipFFT workload that hung at the first plan eviction with a 16- or 32-entry plan cache completes. Only gfx1151 with HIP 7.15.26333 and rocFFT 1.0.39 was checked. + +## Reproduction + +`repro.hip` shows the runtime behavior without MLX: `timeout 30 ./repro 1 200` (null stream touched before the flag) hangs at its first `hipFree`, and `./repro 0 200` (flag first) prints `done`. It may be worth a CLR report on its own; none has been filed. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/repro.hip b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/repro.hip new file mode 100644 index 000000000..ff79b6172 --- /dev/null +++ b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/repro.hip @@ -0,0 +1,46 @@ +// Reproduction for "fix(rocm): set blocking-sync before the first HIP queue +// is created". No MLX and no hipFFT: this is the HIP runtime behavior the +// backend ran into. +// +// hipcc --offload-arch=gfx1151 -O2 repro.hip -o repro +// timeout 30 ./repro 1 200 # null stream touched before the flag: hangs +// # at the first hipFree (last line "iter 7") +// ./repro 0 200 # flag first: prints "done" +// +// Seen on gfx1151 with HIP 7.15.26333. With AMD_LOG_LEVEL=4 the hanging run +// logs "hsa_amd_signal_async_handler() failed to set the handler!". +#include + +#include +#include +#include + +__global__ void k(float* p, int n) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) p[i] += 1.0f; +} + +int main(int argc, char** argv) { + bool early_touch = argc > 1 && argv[1][0] == '1'; + int iters = argc > 2 ? atoi(argv[2]) : 200; + if (early_touch) (void)hipStreamQuery(nullptr); // creates the null-stream queue now + (void)hipSetDeviceFlags(hipDeviceScheduleBlockingSync); // turns active wait off + hipStream_t s; + (void)hipStreamCreateWithFlags(&s, hipStreamNonBlocking); + std::vector h(1024, 1.0f); + std::vector live; + for (int i = 0; i < iters; ++i) { + float* p; + (void)hipMalloc(&p, 4096); + (void)hipMemcpy(p, h.data(), 4096, hipMemcpyHostToDevice); + hipLaunchKernelGGL(k, dim3(4), dim3(256), 0, nullptr, p, 1024); + live.push_back(p); + if (live.size() > 8) { + (void)hipFree(live.front()); + live.erase(live.begin()); + } + printf("iter %d\n", i); + fflush(stdout); + } + printf("done\n"); +} diff --git a/docs/mlxcelverse/upstream/07-fft-hipfft/0001-feat-rocm-implement-FFT-through-hipFFT.patch b/docs/mlxcelverse/upstream/07-fft-hipfft/0001-feat-rocm-implement-FFT-through-hipFFT.patch new file mode 100644 index 000000000..f5b6dde6e --- /dev/null +++ b/docs/mlxcelverse/upstream/07-fft-hipfft/0001-feat-rocm-implement-FFT-through-hipFFT.patch @@ -0,0 +1,639 @@ +From 69d95330b94ba9bf7a6dbe9e9f2d47f8d5b35471 Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] feat(rocm): implement FFT through hipFFT + +FFT was a NO_GPU stub. fft.hip ports mlx/backend/cuda/fft.cu, keeping its axis walk, the packing of the transform axis to the back and the inverse scaling, with two differences. hipFFT has no hipfftXtMakePlanMany or hipfftXtExec, so the typed API is used instead: one hipfftType (C2C, R2C or C2R) per plan and one exec function per transform, which is enough because MLX only asks for float32 and complex64 here. And hipFFT work cannot be a HIP graph kernel node, so execution goes through CommandEncoder::launch_kernel, the path the rocBLAS and hipBLASLt GEMMs take. hipfft joins the link list, with a configure-time error when it is missing. + +The plan cache holds 128 entries, as in the CUDA file. It depends on the blocking-sync flag being set before the first HIP queue exists ("fix(rocm): set blocking-sync before the first HIP queue is created", which has to land first): without that, the first plan eviction past about 16 live plans hangs inside hipfftDestroy. + +MLX_ROCM_FFT_CACHE_SIZE overrides the capacity. The LRU cache read it with an unchecked std::stoul: "0" was accepted and the first put() then popped an empty list (undefined behavior), "-1" became SIZE_MAX, "8abc" became 8, and anything else threw a bare "stoul" out of a static initializer, so every later FFT threw again. capacity_from_env() now takes a whole decimal integer from 1 to INT_MAX; anything else prints one line to stderr and uses the default. LRUCache and LRUBytesKeyCache throw for a capacity of 0, as the CUDA LRUCache does. + +Verified against the CPU stream for rfft, irfft, round trips and complex fft at lengths 2, 8, 400, 512, 1024, 1200 and 2048 and batches up to 512, all within 1e-5 relative. +--- + mlx/backend/rocm/CMakeLists.txt | 15 +- + mlx/backend/rocm/fft.hip | 480 ++++++++++++++++++++++++++++++++ + mlx/backend/rocm/lru_cache.h | 47 +++- + mlx/backend/rocm/primitives.cpp | 1 - + 4 files changed, 536 insertions(+), 7 deletions(-) + create mode 100644 mlx/backend/rocm/fft.hip + +diff --git a/mlx/backend/rocm/CMakeLists.txt b/mlx/backend/rocm/CMakeLists.txt +index f7eeeb8e..69042e0a 100644 +--- a/mlx/backend/rocm/CMakeLists.txt ++++ b/mlx/backend/rocm/CMakeLists.txt +@@ -148,6 +148,7 @@ set(HIP_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_general_input.hip + ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_general_dynamic.hip + ${CMAKE_CURRENT_SOURCE_DIR}/distributed.hip ++ ${CMAKE_CURRENT_SOURCE_DIR}/fft.hip + ${CMAKE_CURRENT_SOURCE_DIR}/hadamard.hip + ${CMAKE_CURRENT_SOURCE_DIR}/indexing.hip + ${CMAKE_CURRENT_SOURCE_DIR}/layer_norm.hip +@@ -379,9 +380,19 @@ find_library(HIPRTC_LIB hiprtc PATHS ${ROCM_PATH}/lib /opt/rocm/lib + find_library(HIPBLASLT_LIB hipblaslt PATHS ${ROCM_PATH}/lib /opt/rocm/lib + /opt/rocm-6.0.0/lib) + ++# Find hipFFT, used by the FFT primitive ++find_library(HIPFFT_LIB hipfft PATHS ${ROCM_PATH}/lib /opt/rocm/lib ++ /opt/rocm-6.0.0/lib) ++if(NOT HIPFFT_LIB) ++ message( ++ FATAL_ERROR ++ "hipfft not found. Install the ROCm hipFFT runtime (package rocm-hip-libraries or hipfft), or set ROCM_PATH to a root that provides lib/libhipfft.so." ++ ) ++endif() ++ + message( + STATUS +- "ROCm libraries: rocblas=${ROCBLAS_LIB}, hiprand=${HIPRAND_LIB}, amdhip64=${AMDHIP64_LIB}, hiprtc=${HIPRTC_LIB}, hipblaslt=${HIPBLASLT_LIB}" ++ "ROCm libraries: rocblas=${ROCBLAS_LIB}, hiprand=${HIPRAND_LIB}, amdhip64=${AMDHIP64_LIB}, hiprtc=${HIPRTC_LIB}, hipblaslt=${HIPBLASLT_LIB}, hipfft=${HIPFFT_LIB}" + ) + + # Link the static library and ROCm libraries to mlx We link directly to the .so +@@ -389,7 +400,7 @@ message( + # -x hip + target_link_libraries( + mlx PRIVATE ${HIP_STATIC_LIB} ${AMDHIP64_LIB} ${ROCBLAS_LIB} ${HIPRAND_LIB} +- ${HIPRTC_LIB} ${HIPBLASLT_LIB}) ++ ${HIPRTC_LIB} ${HIPBLASLT_LIB} ${HIPFFT_LIB}) + + # Include ROCm headers for mlx C++ files Get the HIP include directory from the + # hip package +diff --git a/mlx/backend/rocm/fft.hip b/mlx/backend/rocm/fft.hip +new file mode 100644 +index 00000000..f80dd7c3 +--- /dev/null ++++ b/mlx/backend/rocm/fft.hip +@@ -0,0 +1,480 @@ ++// Copyright © 2025 Apple Inc. ++ ++// FFT for the ROCm backend, through hipFFT. ++// ++// Ported from mlx/backend/cuda/fft.cu. Two differences are worth knowing before ++// reading it against the CUDA original. ++// ++// This hipFFT has no `hipfftXtMakePlanMany` or `hipfftXtExec`, the generic ++// entry points the CUDA file uses to pass input, output and execution types ++// separately. It has the typed API instead: `hipfftMakePlanMany64` takes one ++// `hipfftType` (C2C, R2C or C2R) and each transform has its own exec function. ++// MLX only ever asks for float32 and complex64 here, so the typed API covers ++// the same ground and the type-selection helpers the CUDA file needs disappear. ++// ++// hipFFT work is not a HIP graph kernel node, so it goes through ++// `CommandEncoder::launch_kernel`, which splits the accumulated graph, runs the ++// call on the same stream ordered after it, and starts the next graph fresh. ++// That is the same path the rocBLAS and hipBLASLt GEMMs take in matmul.cpp. ++ ++#include "mlx/backend/rocm/device.h" ++#include "mlx/backend/rocm/allocator.h" ++#include "mlx/backend/rocm/kernel_utils.hpp" ++#include "mlx/backend/rocm/lru_cache.h" ++#include "mlx/backend/rocm/utils.h" ++#include "mlx/backend/common/utils.h" ++#include "mlx/backend/gpu/copy.h" ++#include "mlx/primitives.h" ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace mlx::core { ++ ++namespace rocm { ++ ++// Scales an FFT result in place. hipFFT, like cuFFT, leaves the 1/n of an ++// inverse transform to the caller. ++template ++__global__ void scale_fft_output(T* out, T scale, size_t size) { ++ size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; ++ size_t stride = static_cast(gridDim.x) * blockDim.x; ++ for (size_t i = index; i < size; i += stride) { ++ out[i] = out[i] * scale; ++ } ++} ++ ++} // namespace rocm ++ ++namespace { ++ ++void check_hipfft_error(const char* name, hipfftResult err) { ++ if (err != HIPFFT_SUCCESS) { ++ throw std::runtime_error( ++ std::string(name) + ++ " failed with code: " + std::to_string(static_cast(err)) + "."); ++ } ++} ++ ++#define CHECK_HIPFFT_ERROR(cmd) check_hipfft_error(#cmd, (cmd)) ++ ++enum class FFTTransformType : uint8_t { ++ C2C = 0, ++ R2C = 1, ++ C2R = 2, ++}; ++ ++hipfftType hipfft_type(FFTTransformType transform_type) { ++ switch (transform_type) { ++ case FFTTransformType::C2C: ++ return HIPFFT_C2C; ++ case FFTTransformType::R2C: ++ return HIPFFT_R2C; ++ case FFTTransformType::C2R: ++ return HIPFFT_C2R; ++ } ++ throw std::runtime_error("[FFT] Unsupported hipFFT transform type."); ++} ++ ++// The backend's LRU cache is an unordered_map keyed by the type itself, so it ++// needs std::hash. A string key avoids specializing std::hash for a type in an ++// anonymous namespace; plan lookups happen once per shape, so its cost does not ++// matter. ++std::string make_plan_key( ++ int device_id, ++ FFTTransformType transform_type, ++ int64_t n, ++ int64_t batch) { ++ return std::to_string(device_id) + ":" + ++ std::to_string(static_cast(transform_type)) + ":" + ++ std::to_string(n) + ":" + std::to_string(batch); ++} ++ ++struct HipFFTPlan { ++ HipFFTPlan(int device_id, hipfftHandle handle, size_t workspace_size) ++ : device_id(device_id), handle(handle), workspace_size(workspace_size) {} ++ ++ ~HipFFTPlan() { ++ if (handle != 0) { ++ try { ++ hipfftDestroy(handle); ++ } catch (...) { ++ } ++ } ++ } ++ ++ HipFFTPlan(const HipFFTPlan&) = delete; ++ HipFFTPlan& operator=(const HipFFTPlan&) = delete; ++ ++ int device_id; ++ hipfftHandle handle; ++ size_t workspace_size; ++}; ++ ++struct OrderedArray { ++ array arr; ++ std::vector order; ++}; ++ ++// Same capacity as the CUDA file. It relies on rocm::ensure_device_flags() ++// running before the first HIP queue exists: with the null stream's queue ++// created before hipSetDeviceFlags(hipDeviceScheduleBlockingSync), the first ++// plan eviction past about 16 live plans hung inside hipfftDestroy, whose ++// hipFree never returned. MLX_ROCM_FFT_CACHE_SIZE overrides the capacity: a ++// positive integer up to INT_MAX; any other value warns once and keeps the ++// default (capacity_from_env in lru_cache.h). ++auto& fft_plan_cache() { ++ static rocm::LRUBytesKeyCache> cache( ++ "MLX_ROCM_FFT_CACHE_SIZE", ++ /* default_capacity */ 128); ++ return cache; ++} ++ ++std::mutex& fft_plan_cache_mutex() { ++ static std::mutex m; ++ return m; ++} ++ ++int64_t input_embed(FFTTransformType transform_type, int64_t n) { ++ return transform_type == FFTTransformType::C2R ? (n / 2 + 1) : n; ++} ++ ++int64_t output_embed(FFTTransformType transform_type, int64_t n) { ++ return transform_type == FFTTransformType::R2C ? (n / 2 + 1) : n; ++} ++ ++std::shared_ptr get_fft_plan( ++ rocm::CommandEncoder& encoder, ++ FFTTransformType transform_type, ++ int64_t n, ++ int64_t batch) { ++ auto key = ++ make_plan_key(encoder.device().hip_device(), transform_type, n, batch); ++ ++ auto& cache = fft_plan_cache(); ++ // The cache is shared, and building a plan is not idempotent in cost, so the ++ // check-build-insert runs under one lock. ++ std::lock_guard cache_lock(fft_plan_cache_mutex()); ++ if (auto entry = cache.get(key); entry.has_value()) { ++ return *entry; ++ } ++ ++ encoder.device().make_current(); ++ ++ hipfftHandle handle = 0; ++ size_t workspace_size = 0; ++ try { ++ CHECK_HIPFFT_ERROR(hipfftCreate(&handle)); ++ // The work area is allocated per execution from MLX's pool rather than by ++ // hipFFT, so a cached plan holds no device memory of its own. ++ CHECK_HIPFFT_ERROR(hipfftSetAutoAllocation(handle, 0)); ++ ++ long long plan_n[1] = {n}; ++ long long inembed[1] = {input_embed(transform_type, n)}; ++ long long onembed[1] = {output_embed(transform_type, n)}; ++ CHECK_HIPFFT_ERROR(hipfftMakePlanMany64( ++ handle, ++ /* rank = */ 1, ++ plan_n, ++ inembed, ++ /* istride = */ 1, ++ /* idist = */ input_embed(transform_type, n), ++ onembed, ++ /* ostride = */ 1, ++ /* odist = */ output_embed(transform_type, n), ++ hipfft_type(transform_type), ++ batch, ++ &workspace_size)); ++ } catch (...) { ++ if (handle != 0) { ++ hipfftDestroy(handle); ++ } ++ throw; ++ } ++ ++ auto plan = std::make_shared( ++ encoder.device().hip_device(), handle, workspace_size); ++ cache.put(key, plan); ++ return plan; ++} ++ ++std::vector make_identity_order(int ndim) { ++ std::vector order(ndim); ++ std::iota(order.begin(), order.end(), 0); ++ return order; ++} ++ ++std::vector move_axis_to_back_permutation(int ndim, int axis_pos) { ++ std::vector perm; ++ perm.reserve(ndim); ++ for (int i = 0; i < ndim; ++i) { ++ if (i != axis_pos) { ++ perm.push_back(i); ++ } ++ } ++ perm.push_back(axis_pos); ++ return perm; ++} ++ ++std::vector apply_permutation( ++ const std::vector& values, ++ const std::vector& perm) { ++ std::vector out(perm.size()); ++ for (size_t i = 0; i < perm.size(); ++i) { ++ out[i] = values[perm[i]]; ++ } ++ return out; ++} ++ ++int find_axis_position(const std::vector& order, int axis) { ++ auto it = std::find(order.begin(), order.end(), axis); ++ if (it == order.end()) { ++ throw std::runtime_error("[FFT] Internal axis tracking mismatch."); ++ } ++ return static_cast(it - order.begin()); ++} ++ ++OrderedArray prepare_input( ++ const OrderedArray& current, ++ int axis, ++ bool allow_direct, ++ rocm::CommandEncoder& encoder, ++ Stream s) { ++ int axis_pos = find_axis_position(current.order, axis); ++ bool axis_last = axis_pos == static_cast(current.order.size()) - 1; ++ bool direct = allow_direct && axis_last && current.arr.flags().row_contiguous; ++ ++ if (direct) { ++ return current; ++ } ++ ++ array view = current.arr; ++ std::vector order = current.order; ++ if (!axis_last) { ++ auto perm = move_axis_to_back_permutation(current.arr.ndim(), axis_pos); ++ view = transpose_in_eval(current.arr, perm); ++ order = apply_permutation(current.order, perm); ++ } ++ ++ array packed = contiguous_copy_gpu(view, s); ++ encoder.add_temporary(packed); ++ return {std::move(packed), std::move(order)}; ++} ++ ++void execute_fft( ++ const array& in, ++ array& out, ++ FFTTransformType transform_type, ++ bool inverse, ++ rocm::CommandEncoder& encoder) { ++ if (!in.flags().row_contiguous || in.strides(-1) != 1) { ++ throw std::runtime_error("[FFT] Expected packed row-contiguous FFT input."); ++ } ++ ++ int64_t n = ++ transform_type == FFTTransformType::C2R ? out.shape(-1) : in.shape(-1); ++ int64_t batch = in.shape().empty() ? 1 : in.size() / in.shape(-1); ++ auto plan = get_fft_plan(encoder, transform_type, n, batch); ++ ++ encoder.set_input_array(in); ++ out.set_data(mlx::core::rocm::malloc_async(out.nbytes(), encoder)); ++ encoder.set_output_array(out); ++ ++ // The work area comes from the same async pool as every other buffer on this ++ // encoder. A synchronous allocator::malloc here deadlocks: it waits on the ++ // pool while the encoder still holds outstanding async frees. ++ size_t ws_bytes = std::max(plan->workspace_size, 1); ++ array workspace({static_cast(ws_bytes)}, uint8, nullptr, {}); ++ workspace.set_data(mlx::core::rocm::malloc_async(ws_bytes, encoder)); ++ encoder.add_temporary(workspace); ++ ++ void* in_ptr = const_cast(gpu_ptr(in)); ++ void* out_ptr = gpu_ptr(out); ++ void* ws_ptr = gpu_ptr(workspace); ++ int direction = inverse ? HIPFFT_BACKWARD : HIPFFT_FORWARD; ++ hipfftHandle handle = plan->handle; ++ ++ // hipFFT is not a graph kernel node; launch_kernel splits the graph and runs ++ // this on the encoder stream, ordered after what came before. launch_kernel ++ // calls the lambda synchronously and drops it on return, so the captured ++ // plan lives only as long as the enqueue, not the asynchronous execution. ++ // An eviction later is still safe for that execution: hipfftDestroy frees ++ // the plan's device memory through hipFree, which synchronizes the device ++ // first. That argument covers the eager launch; the opt-in ++ // MLX_GRAPH_PREFILL_REPLAY=1 path, which records the call into a graph that ++ // launches later, was not examined. ++ encoder.launch_kernel([handle, ++ plan, ++ in_ptr, ++ out_ptr, ++ ws_ptr, ++ direction, ++ transform_type](hipStream_t stream) { ++ CHECK_HIPFFT_ERROR(hipfftSetStream(handle, stream)); ++ CHECK_HIPFFT_ERROR(hipfftSetWorkArea(handle, ws_ptr)); ++ switch (transform_type) { ++ case FFTTransformType::C2C: ++ CHECK_HIPFFT_ERROR(hipfftExecC2C( ++ handle, ++ static_cast(in_ptr), ++ static_cast(out_ptr), ++ direction)); ++ break; ++ case FFTTransformType::R2C: ++ CHECK_HIPFFT_ERROR(hipfftExecR2C( ++ handle, ++ static_cast(in_ptr), ++ static_cast(out_ptr))); ++ break; ++ case FFTTransformType::C2R: ++ CHECK_HIPFFT_ERROR(hipfftExecC2R( ++ handle, ++ static_cast(in_ptr), ++ static_cast(out_ptr))); ++ break; ++ } ++ }); ++} ++ ++void restore_output_layout(const OrderedArray& current, array& out) { ++ Strides out_strides(out.ndim()); ++ for (size_t i = 0; i < current.order.size(); ++i) { ++ out_strides[current.order[i]] = current.arr.strides(i); ++ } ++ ++ auto [data_size, row_contiguous, col_contiguous] = ++ check_contiguity(out.shape(), out_strides); ++ bool contiguous = ++ current.arr.flags().contiguous && data_size == current.arr.data_size(); ++ ++ out.copy_shared_buffer( ++ current.arr, ++ out_strides, ++ {contiguous, row_contiguous, col_contiguous}, ++ current.arr.data_size()); ++} ++ ++void apply_inverse_scale( ++ array& arr, ++ const std::vector& axes, ++ const array& out, ++ rocm::CommandEncoder& encoder) { ++ if (axes.empty()) { ++ return; ++ } ++ ++ double scale = 1.0; ++ for (auto axis : axes) { ++ scale /= out.shape(axis); ++ } ++ ++ size_t size = arr.data_size(); ++ constexpr int block_size = 256; ++ int num_blocks = static_cast(std::min( ++ (size + block_size - 1) / block_size, 65535)); ++ ++ encoder.set_input_array(arr); ++ encoder.set_output_array(arr); ++ ++ if (arr.dtype() == float32) { ++ float scale_f = static_cast(scale); ++ encoder.add_kernel_node( ++ &rocm::scale_fft_output, ++ dim3(num_blocks), ++ dim3(block_size), ++ 0, ++ gpu_ptr(arr), ++ scale_f, ++ size); ++ } else if (arr.dtype() == complex64) { ++ hipFloatComplex scale_f = ++ make_hipFloatComplex(static_cast(scale), 0.0f); ++ encoder.add_kernel_node( ++ &rocm::scale_fft_output, ++ dim3(num_blocks), ++ dim3(block_size), ++ 0, ++ gpu_ptr(arr), ++ scale_f, ++ size); ++ } else { ++ throw std::runtime_error("[FFT] Unsupported dtype for inverse scaling."); ++ } ++} ++ ++} // namespace ++ ++void FFT::eval_gpu(const std::vector& inputs, array& out) { ++ auto& s = stream(); ++ auto& encoder = rocm::get_command_encoder(s); ++ auto& in = inputs[0]; ++ ++ if (out.size() == 0) { ++ return; ++ } ++ ++ auto order = make_identity_order(in.ndim()); ++ OrderedArray current{in, std::move(order)}; ++ ++ std::vector axis_sequence; ++ axis_sequence.reserve(axes_.size()); ++ if (inverse_) { ++ for (auto axis : axes_) { ++ axis_sequence.push_back(static_cast(axis)); ++ } ++ } else { ++ for (int i = static_cast(axes_.size()) - 1; i >= 0; --i) { ++ axis_sequence.push_back(static_cast(axes_[i])); ++ } ++ } ++ ++ int real_axis = axes_.empty() ? -1 : static_cast(axes_.back()); ++ ++ for (size_t i = 0; i < axis_sequence.size(); ++i) { ++ int axis = axis_sequence[i]; ++ bool step_real = real_ && axis == real_axis; ++ auto transform_type = step_real ++ ? (inverse_ ? FFTTransformType::C2R : FFTTransformType::R2C) ++ : FFTTransformType::C2C; ++ ++ // hipFFT, like cuFFT, may overwrite its input for C2R, so the original ++ // input is only used directly when it is donatable to the output. ++ auto prepared = prepare_input( ++ current, ++ axis, ++ /* allow_direct = */ transform_type != FFTTransformType::C2R || ++ is_donatable(in, out), ++ encoder, ++ s); ++ ++ Shape step_shape = prepared.arr.shape(); ++ if (step_real) { ++ step_shape.back() = out.shape(axis); ++ } ++ ++ Dtype step_dtype = ++ transform_type == FFTTransformType::C2R ? float32 : complex64; ++ array step_out(std::move(step_shape), step_dtype, nullptr, {}); ++ execute_fft(prepared.arr, step_out, transform_type, inverse_, encoder); ++ encoder.add_temporary(step_out); ++ ++ current = {std::move(step_out), std::move(prepared.order)}; ++ } ++ ++ if (inverse_) { ++ apply_inverse_scale(current.arr, axes_, out, encoder); ++ } ++ ++ restore_output_layout(current, out); ++} ++ ++} // namespace mlx::core +diff --git a/mlx/backend/rocm/lru_cache.h b/mlx/backend/rocm/lru_cache.h +index b78d89dc..1b97c35b 100644 +--- a/mlx/backend/rocm/lru_cache.h ++++ b/mlx/backend/rocm/lru_cache.h +@@ -2,23 +2,58 @@ + + #pragma once + ++#include ++#include + #include ++#include + #include + #include + #include ++#include + #include + #include + + namespace mlx::core::rocm { + ++// Cache capacity from an environment variable. Unset gives the default with no ++// output. The value must be a whole decimal integer from 1 to INT_MAX, parsed ++// with std::strtol; ++// anything else (empty, trailing junk such as "8abc", overflow, zero or a ++// negative value) prints one line to stderr naming the variable and the ++// default, and the default is used. std::stoul used to take "-1" as SIZE_MAX ++// and "8abc" as 8, accept "0" (whose first put() then popped an empty list), ++// and throw a bare "stoul" for anything else. ++inline size_t capacity_from_env(const char* env_var, size_t default_capacity) { ++ const char* env = std::getenv(env_var); ++ if (!env) { ++ return default_capacity; ++ } ++ char* end = nullptr; ++ errno = 0; ++ long v = std::strtol(env, &end, 10); ++ if (end == env || *end != '\0' || errno == ERANGE || v <= 0 || ++ v > std::numeric_limits::max()) { ++ std::fprintf( ++ stderr, ++ "[ROCm] ignoring invalid %s=\"%s\" (expected a positive integer); " ++ "using the default %zu\n", ++ env_var, ++ env, ++ default_capacity); ++ return default_capacity; ++ } ++ return static_cast(v); ++} ++ + // LRU cache with byte-based keys + template + class LRUBytesKeyCache { + public: + LRUBytesKeyCache(const char* env_var, size_t default_capacity) +- : capacity_(default_capacity) { +- if (const char* env = std::getenv(env_var)) { +- capacity_ = std::stoul(env); ++ : capacity_(capacity_from_env(env_var, default_capacity)) { ++ // put() evicts while size() >= capacity_, which pops an empty list at 0. ++ if (capacity_ == 0) { ++ throw std::runtime_error("LRUCache requires capacity > 0."); + } + } + +@@ -78,7 +113,11 @@ class LRUBytesKeyCache { + template + class LRUCache { + public: +- explicit LRUCache(size_t capacity) : capacity_(capacity) {} ++ explicit LRUCache(size_t capacity) : capacity_(capacity) { ++ if (capacity_ == 0) { ++ throw std::runtime_error("LRUCache requires capacity > 0."); ++ } ++ } + + std::optional get(size_t key) { + std::lock_guard lock(mutex_); +diff --git a/mlx/backend/rocm/primitives.cpp b/mlx/backend/rocm/primitives.cpp +index 6ec2764e..c6c669d2 100644 +--- a/mlx/backend/rocm/primitives.cpp ++++ b/mlx/backend/rocm/primitives.cpp +@@ -29,7 +29,6 @@ namespace mlx::core { + // Note: GatherQMM is now implemented in quantized/qmm.hip + + NO_GPU(BlockMaskedMM) +-NO_GPU(FFT) + NO_GPU_MULTI(LUF) + NO_GPU_MULTI(QRF) + NO_GPU(QQMatmul) diff --git a/docs/mlxcelverse/upstream/07-fft-hipfft/pr.md b/docs/mlxcelverse/upstream/07-fft-hipfft/pr.md new file mode 100644 index 000000000..728a02e59 --- /dev/null +++ b/docs/mlxcelverse/upstream/07-fft-hipfft/pr.md @@ -0,0 +1,43 @@ +# feat(rocm): implement FFT through hipFFT + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-feat-rocm-implement-FFT-through-hipFFT.patch`](0001-feat-rocm-implement-FFT-through-hipFFT.patch), apply with `git am` | +| Applies cleanly | no: apply after the blocking-sync PR (06) and the Hadamard PR (05); on `75915908` alone it conflicts in `CMakeLists.txt` and `primitives.cpp` (adjacent lines) | +| Depends on | 06 at runtime (plan eviction hangs without it); 05 for a clean apply | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 18, 25 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +`FFT` is a `NO_GPU` stub on this backend. This adds `mlx/backend/rocm/fft.hip`, a port of `mlx/backend/cuda/fft.cu` that keeps its axis walk, its packing of the transform axis to the back, and its inverse scaling, with two differences: + +- This hipFFT has no `hipfftXtMakePlanMany` or `hipfftXtExec`, the generic entry points the CUDA file uses to pass input, output and execution types separately. The typed API takes their place: one `hipfftType` (C2C, R2C or C2R) per plan and one exec function per transform, which covers the same ground because MLX only asks for float32 and complex64 here. +- hipFFT work cannot be a HIP graph kernel node, so execution goes through `CommandEncoder::launch_kernel`, the path the rocBLAS and hipBLASLt GEMMs already take. + +`hipfft` joins the link list, with a configure-time error naming the package when it is missing. + +The plan cache holds 128 entries, as in the CUDA file. This depends on the blocking-sync fix (the "set blocking-sync before the first HIP queue is created" PR), which has to land first: without it the first plan eviction past about 16 live plans hangs inside `hipfftDestroy`, whose `hipFree` never returns. + +`MLX_ROCM_FFT_CACHE_SIZE` overrides the capacity, and its parsing in `lru_cache.h` is fixed. `LRUBytesKeyCache` read it with an unchecked `std::stoul`: `0` was accepted and the first `put()` then called `back()` and `pop_back()` on an empty list (undefined behavior; `std::bad_alloc` on gfx1151); `abc`, an empty value or an overflow threw a bare `stoul` out of the static's initializer in `FFT::eval_gpu`, so every later FFT threw again; `-1` became `SIZE_MAX` and `8abc` became 8. `capacity_from_env()` now takes a whole decimal integer from 1 to `INT_MAX`; anything else prints one line to stderr and uses the default. `LRUCache` and `LRUBytesKeyCache` throw for a capacity of 0, as the CUDA `LRUCache` does. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. Verified against the CPU stream for rfft, irfft, round trips and complex fft at lengths 2, 8, 400, 512, 1024, 1200 and 2048 and batches up to 512, all within 1e-5 relative, and at plan-cache capacities 16, 32 and 128 with 40 distinct plans. + +## Reproduction + +`repro.py` checks FFT correctness against the CPU stream, runs 48 distinct transform lengths with `MLX_ROCM_FFT_CACHE_SIZE=16` in a child process with a timeout (plan eviction), and checks the variable's validation for valid and invalid values. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/07-fft-hipfft/repro.py b/docs/mlxcelverse/upstream/07-fft-hipfft/repro.py new file mode 100644 index 000000000..410a69340 --- /dev/null +++ b/docs/mlxcelverse/upstream/07-fft-hipfft/repro.py @@ -0,0 +1,115 @@ +"""Reproduction for "feat(rocm): implement FFT through hipFFT". + +Needs the blocking-sync fix ("fix(rocm): set blocking-sync before the first HIP +queue is created") applied first. + +1. Correctness: rfft, irfft, round trips and complex fft against the CPU stream + at several lengths and batches, within 1e-5 relative. +2. Plan-cache pressure: a child process with MLX_ROCM_FFT_CACHE_SIZE=16 runs 48 + round trips at distinct lengths, so plans are evicted. Without the + blocking-sync fix this hangs inside hipfftDestroy at the first eviction. +3. MLX_ROCM_FFT_CACHE_SIZE validation: invalid values ("0", "-1", "abc", + "8abc", "") print one warning and fall back to the default; valid ones are + used silently. Before the change "0" was undefined behavior and "abc" left + every FFT throwing "stoul". + + python repro.py +""" + +import os +import subprocess +import sys + +import mlx.core as mx + + +def rel(a, b): + return (mx.abs(a - b).max() / mx.maximum(mx.abs(b).max(), 1e-12)).item() + + +def correctness(): + failed = 0 + mx.random.seed(0) + for n in (2, 8, 400, 512, 1024, 1200, 2048): + for batch in (1, 3, 512): + x = mx.random.normal((batch, n)) + z = x + 1j * mx.random.normal((batch, n)) + checks = { + "rfft": (mx.fft.rfft(x, stream=mx.gpu), mx.fft.rfft(x, stream=mx.cpu)), + "irfft": ( + mx.fft.irfft(mx.fft.rfft(x, stream=mx.cpu), n=n, stream=mx.gpu), + mx.fft.irfft(mx.fft.rfft(x, stream=mx.cpu), n=n, stream=mx.cpu), + ), + "round trip": (mx.fft.irfft(mx.fft.rfft(x, stream=mx.gpu), n=n, stream=mx.gpu), x), + "fft": (mx.fft.fft(z, stream=mx.gpu), mx.fft.fft(z, stream=mx.cpu)), + } + for name, (g, c) in checks.items(): + e = rel(g, c) + if not e <= 1e-5: + print(f"FAIL {name} n={n} batch={batch}: {e:.2e}") + failed += 1 + print(f"{'PASS' if not failed else 'FAIL'} correctness ({failed} failing)") + return failed + + +CHILD_PRESSURE = """ +import mlx.core as mx +for i, n in enumerate(range(100, 100 + 48 * 7, 7)): + x = mx.random.normal((4, n)) + y = mx.fft.irfft(mx.fft.rfft(x, stream=mx.gpu), n=n, stream=mx.gpu) + mx.eval(y) + assert (mx.abs(y - x).max() < 1e-4).item(), n +print("ok") +""" + +CHILD_ENV = """ +import mlx.core as mx +x = mx.random.normal((2, 64)) +g = mx.fft.rfft(x, stream=mx.gpu) +c = mx.fft.rfft(x, stream=mx.cpu) +assert (mx.abs(g - c).max() < 1e-4).item() +print("ok") +""" + + +def child(code, env_value, timeout): + env = dict(os.environ) + if env_value is None: + env.pop("MLX_ROCM_FFT_CACHE_SIZE", None) + else: + env["MLX_ROCM_FFT_CACHE_SIZE"] = env_value + return subprocess.run([sys.executable, "-c", code], env=env, timeout=timeout, + capture_output=True, text=True) + + +def pressure(): + try: + r = child(CHILD_PRESSURE, "16", 120) + ok = r.returncode == 0 and "ok" in r.stdout + print(f"{'PASS' if ok else 'FAIL'} 48 distinct plans with a 16-entry cache {r.stderr.strip()[-200:]}") + except subprocess.TimeoutExpired: + ok = False + print("FAIL 48 distinct plans with a 16-entry cache: timed out (hang at plan eviction)") + return 0 if ok else 1 + + +def env_validation(): + failed = 0 + for value, warns in (("0", True), ("-1", True), ("abc", True), ("8abc", True), ("", True), + ("16", False), ("1", False), (None, False)): + r = child(CHILD_ENV, value, 60) + warned = "MLX_ROCM_FFT_CACHE_SIZE" in r.stderr + ok = r.returncode == 0 and "ok" in r.stdout and warned == warns + print(f"{'PASS' if ok else 'FAIL'} MLX_ROCM_FFT_CACHE_SIZE={value!r}: exit {r.returncode}, warned={warned}") + failed += not ok + return failed + + +def main(): + failed = correctness() + pressure() + env_validation() + print(f"{failed} failing check(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/08-launch-geometry-helpers/0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch new file mode 100644 index 000000000..214ad26d9 --- /dev/null +++ b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch @@ -0,0 +1,101 @@ +From eede8b3fb337945c30577630b993452a1d8adddc Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): use the shared get_2d_grid_dims and remove + get_launch_args + +kernel_utils.hpp carried its own body for get_2d_grid_dims(shape, strides, divisor), an older form that removed a dimension from the divisor only when the whole dimension divided it and never divided the grid by the remainder. Scan::eval_gpu sizes the strided_scan grid with it, so for [1, 48, 24, 24] scanned along axis 2 it returned 576 blocks where 48 cover the array, and every extra block read and wrote axis_size * stride elements past the end (an HSA_STATUS_ERROR_MEMORY_FAULT in strided_scan at that shape, which is the segsum of a 48-head Mamba2 layer over a 24-token chunk; silent out-of-bounds writes where the overshoot stays in mapped memory). The overload now delegates to get_2d_grid_dims_common, as the non-divisor overload beside it and the CUDA backend do. + +get_launch_args fixed the block at 256 threads, ignored shape, strides and large, and capped the grid at 65535 blocks, with nothing saying the kernel had to be grid-stride; a one-index-per-thread kernel launched with it leaves every element past 65535 * 256 unwritten. Upstream CUDA's helper of the same name does not cap x, so a kernel ported from mlx/backend/cuda with its call intact would compile here and inherit the truncation. Nothing calls it, so it is replaced by a deleted template with a comment, and a ported call fails to compile at the explanation. +--- + mlx/backend/rocm/kernel_utils.hpp | 68 ++++++++++--------------------- + 1 file changed, 21 insertions(+), 47 deletions(-) + +diff --git a/mlx/backend/rocm/kernel_utils.hpp b/mlx/backend/rocm/kernel_utils.hpp +index a6bfd48e..4ab4e834 100644 +--- a/mlx/backend/rocm/kernel_utils.hpp ++++ b/mlx/backend/rocm/kernel_utils.hpp +@@ -182,36 +182,17 @@ inline dim3 get_2d_grid_dims(const Shape& shape, const Strides& strides) { + return dim3(std::get<0>(dims), std::get<1>(dims), std::get<2>(dims)); + } + ++// Delegates to the shared helper, as the CUDA backend does ++// (`mlx/backend/cuda/kernel_utils.cu`). The local copy this replaces removed a dimension from the divisor only when the whole dimension ++// divided it and never divided the product by what was left, so a shape such ++// as [1, 48, 24, 24] with divisor 24 * 24 returned 576 blocks instead of 48. ++// `strided_scan` then launched twelve times the blocks it needed, and every ++// extra block read and wrote past the end of the array (a GPU memory fault at ++// [1, 48, 24, 24], silent out-of-bounds writes at smaller overshoots). + inline dim3 + get_2d_grid_dims(const Shape& shape, const Strides& strides, size_t divisor) { +- // Compute the 2d grid dimensions such that the total size of the grid is +- // divided by divisor. +- size_t grid_x = 1; +- size_t grid_y = 1; +- for (size_t i = 0; i < shape.size(); ++i) { +- if (strides[i] == 0) { +- continue; +- } +- +- // No need to add this shape we can just remove it from the divisor. +- if (divisor % shape[i] == 0) { +- divisor /= shape[i]; +- continue; +- } +- +- if (grid_x * shape[i] < UINT32_MAX) { +- grid_x *= shape[i]; +- } else { +- grid_y *= shape[i]; +- } +- } +- if (grid_y > UINT32_MAX || grid_x > UINT32_MAX) { +- throw std::runtime_error("Unable to safely factor shape."); +- } +- if (grid_y > grid_x) { +- std::swap(grid_x, grid_y); +- } +- return dim3(static_cast(grid_x), static_cast(grid_y), 1); ++ Dims dims = get_2d_grid_dims_common(shape, strides, divisor); ++ return dim3(std::get<0>(dims), std::get<1>(dims), std::get<2>(dims)); + } + + inline std::pair get_grid_and_block(int dim0, int dim1, int dim2) { +@@ -223,25 +204,18 @@ inline std::pair get_grid_and_block(int dim0, int dim1, int dim2) { + return {grid_dims, block_dims}; + } + +-// Get the num_blocks and block_dims for a kernel +-inline std::tuple get_launch_args( +- size_t size, +- const Shape& shape, +- const Strides& strides, +- bool large, +- int work_per_thread = 1) { +- size_t adjusted_size = (size + work_per_thread - 1) / work_per_thread; +- int block_size = 256; +- int num_blocks = (adjusted_size + block_size - 1) / block_size; +- num_blocks = std::min(num_blocks, 65535); +- return {dim3(num_blocks), block_size}; +-} +- +-inline std::tuple +-get_launch_args(const array& arr, bool large, int work_per_thread = 1) { +- return get_launch_args( +- arr.size(), arr.shape(), arr.strides(), large, work_per_thread); +-} ++// get_launch_args is deliberately unavailable in this backend. The version ++// that was here capped the grid at ++// 65535 blocks of 256 threads and returned it with no sign that the kernel had ++// to be grid-stride, so a one-index-per-thread kernel launched with it left ++// every element past 65535 * 256 unwritten. It had no caller. Upstream CUDA's ++// helper of the same name does not cap x, so a kernel ported from ++// mlx/backend/cuda that calls it would inherit the truncation silently. No ++// kernel here used it; launch sites compute their geometry themselves, and a ++// grid clamped at a launch site is only correct if that kernel is grid-stride ++// (see binary.hip, unary.hip). Any call to this name fails to compile. ++template ++void get_launch_args(Args&&...) = delete; + + // Ceil division utility + template diff --git a/docs/mlxcelverse/upstream/08-launch-geometry-helpers/pr.md b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/pr.md new file mode 100644 index 000000000..4e068b9a8 --- /dev/null +++ b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/pr.md @@ -0,0 +1,37 @@ +# fix(rocm): use the shared get_2d_grid_dims and remove + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch`](0001-fix-rocm-use-the-shared-get_2d_grid_dims-and-remove-.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 19, 22 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +Two launch-geometry helpers in `mlx/backend/rocm/kernel_utils.hpp`. + +1. **`get_2d_grid_dims(shape, strides, divisor)` sized strided scans too large.** This backend carried its own body for the divisor overload, an older form of upstream's that removed a dimension from the divisor only when the whole dimension divided it and never divided the grid by what was left. Upstream's `get_2d_grid_dims_common(shape, strides, divisor)` in `mlx/backend/common/utils.cpp` takes the gcd of each dimension and divides the grid by the remainder, and the CUDA backend delegates to it. `Scan::eval_gpu` sizes the `strided_scan` grid (a scan along any axis but the last) with this overload, so for `[1, 48, 24, 24]` scanned along axis 2 it returned 576 blocks where 48 cover the array, and each extra block read and wrote `axis_size * stride` elements past the end. That shape is the segsum of a 48-head Mamba2 layer over a 24-token chunk, and it is an `HSA_STATUS_ERROR_MEMORY_FAULT` in `strided_scan`; an overshoot that stays inside mapped memory corrupts silently instead. Whether a shape is hit depends on how the dimensions share factors with the divisor. The overload now delegates to `get_2d_grid_dims_common`, as the non-divisor overload beside it already did. +2. **`get_launch_args` removed.** It fixed the block at 256 threads, ignored `shape`, `strides` and `large`, and capped the grid at 65535 blocks, with nothing in its name or comment saying the kernel had to be grid-stride. A kernel written one index per thread would leave every element past 65535 x 256 unwritten. Upstream CUDA's helper of the same name does not cap x, so a kernel ported from `mlx/backend/cuda` with its call intact would compile here and inherit the truncation. Nothing calls it; launch sites compute their own geometry. It is replaced by `template void get_launch_args(Args&&...) = delete;` with a comment giving the reason, so a ported call fails to compile at the explanation rather than as an undeclared name someone might fix by restoring the helper. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. With the fix, `cumsum` on the GPU matches the CPU stream exactly (small integers stored as float32) for `[1, 48, 24, 24]` along axis 2, for `[64, 96, 32, 32]` (6144 blocks needed, 98304 launched by the old body), and for shapes the old body already sized correctly. + +## Reproduction + +`repro.py` runs those `cumsum` cases against the CPU stream, each in a child process with a timeout because the unfixed `[1, 48, 24, 24]` case faults the GPU queue. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/08-launch-geometry-helpers/repro.py b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/repro.py new file mode 100644 index 000000000..ede9a9c13 --- /dev/null +++ b/docs/mlxcelverse/upstream/08-launch-geometry-helpers/repro.py @@ -0,0 +1,61 @@ +"""Reproduction for "fix(rocm): use the shared get_2d_grid_dims and remove +get_launch_args". + +cumsum along a non-last axis goes through strided_scan, whose grid is sized by +get_2d_grid_dims(shape, strides, divisor). The old local body launched 576 +blocks where 48 cover a [1, 48, 24, 24] array scanned along axis 2, and the +extra blocks read and wrote past its end: an HSA_STATUS_ERROR_MEMORY_FAULT at +that shape (so each case runs in a child process with a timeout), silent +corruption where the overshoot stays in mapped memory. With the fix the GPU +matches the CPU exactly (small integers stored as float32 sum exactly). + +The get_launch_args part has no runtime reproduction: nothing calls it, and a +call now fails to compile. + + python repro.py +""" + +import argparse +import subprocess +import sys + +import mlx.core as mx + +SHAPES = [((1, 48, 24, 24), 2), ((1, 64, 16, 16), 2), ((64, 96, 32, 32), 1), ((4, 8, 16), 1), ((3, 5, 7), 0)] + + +def run_case(i): + shape, axis = SHAPES[i] + size = 1 + for d in shape: + size *= d + x = (mx.arange(size) % 7).astype(mx.float32).reshape(shape) + g = mx.cumsum(x, axis=axis, stream=mx.gpu) + c = mx.cumsum(x, axis=axis, stream=mx.cpu) + ok = mx.array_equal(g, c).item() + print(f"{'PASS' if ok else 'FAIL'} cumsum {shape} axis={axis}") + return 0 if ok else 1 + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--case", type=int) + a = p.parse_args() + if a.case is not None: + return run_case(a.case) + failed = 0 + for i, (shape, axis) in enumerate(SHAPES): + try: + r = subprocess.run([sys.executable, __file__, "--case", str(i)], timeout=60, + capture_output=True, text=True) + sys.stdout.write(r.stdout or f"FAIL cumsum {shape} axis={axis} exit={r.returncode}\n") + failed += r.returncode != 0 + except subprocess.TimeoutExpired: + print(f"FAIL cumsum {shape} axis={axis}: timed out (GPU fault or hang)") + failed += 1 + print(f"{failed} failing case(s)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch new file mode 100644 index 000000000..55bf19e82 --- /dev/null +++ b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch @@ -0,0 +1,27 @@ +From 4956e775308f1b72d23315a6fdfb29008df04574 Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): fall back from fused SDPA on CPU streams + +ScaledDotProductAttention::use_fallback decided from the shapes alone whether a fused kernel applies, so a call on a CPU stream with a decode-shaped query built the fused primitive, whose eval_cpu throws "NYI". use_fallback now returns true for a CPU stream before the shape checks, as the CUDA backend's use_fallback does. +--- + mlx/backend/rocm/scaled_dot_product_attention.cpp | 6 ++++++ + 1 file changed, 6 insertions(+) + +diff --git a/mlx/backend/rocm/scaled_dot_product_attention.cpp b/mlx/backend/rocm/scaled_dot_product_attention.cpp +index 3cd24ce3..3c22b7ec 100644 +--- a/mlx/backend/rocm/scaled_dot_product_attention.cpp ++++ b/mlx/backend/rocm/scaled_dot_product_attention.cpp +@@ -151,6 +151,12 @@ bool ScaledDotProductAttention::use_fallback( + bool /*is_training*/, + bool output_logsumexp, + Stream s) { ++ // The fused kernels need a GPU stream. Without this check a call on a CPU ++ // stream with a shape the fused kernels accept builds the fused primitive, ++ // whose eval_cpu throws "NYI". The CUDA backend checks the stream first too. ++ if (s.device == Device::cpu) { ++ return true; ++ } + // Vector + scalar flash reject output_logsumexp. WMMA flash can emit LSE and + // must be counted here or MLX_SDPA_FLASH_VJP never attaches (frontend only + // requests LSE when VJP is non-fallback, and VJP needs LSE forward). diff --git a/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md new file mode 100644 index 000000000..559a68e42 --- /dev/null +++ b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md @@ -0,0 +1,34 @@ +# fix(rocm): fall back from fused SDPA on CPU streams + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch`](0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 23 | +| Reproduction | `repro.py` | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +`ScaledDotProductAttention::use_fallback` in `mlx/backend/rocm/scaled_dot_product_attention.cpp` decided from the shapes alone whether a fused kernel applies. A call on a CPU stream with a decode-shaped query (the vector kernel's shape) therefore built the fused `ScaledDotProductAttention` primitive, whose `eval_cpu` throws "NYI", so attention on the CPU device failed on a ROCm build. `use_fallback` now returns `true` for a CPU stream before the shape checks, which is what the CUDA backend's `use_fallback` does. + +Measured on gfx1151 (Radeon 8060S) with HIP 7.15, with this change applied to the same backend retargeted onto a newer MLX (ml-explore/mlx `81ba1c6a`); the patch in this PR is the same change on `rocm-support`. Attention on the CPU device then matches a host softmax reference. + +## Reproduction + +`repro.py` runs `mx.fast.scaled_dot_product_attention` on the CPU stream with a decode-shaped query and compares it with a softmax reference. Without the fix it raises. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/repro.py b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/repro.py new file mode 100644 index 000000000..93a4f03be --- /dev/null +++ b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/repro.py @@ -0,0 +1,36 @@ +"""Reproduction for "fix(rocm): fall back from fused SDPA on CPU streams". + +On a ROCm build, scaled_dot_product_attention on a CPU stream with a +decode-shaped query built the fused primitive, whose eval_cpu raises "NYI". +With the fix the CPU stream takes the unfused fallback and matches a softmax +reference. + + python repro.py +""" + +import sys + +import mlx.core as mx + + +def main(): + mx.random.seed(0) + b, h, d, kv = 1, 8, 64, 128 + q = mx.random.normal((b, h, 1, d)) + k = mx.random.normal((b, h, kv, d)) + v = mx.random.normal((b, h, kv, d)) + scale = d**-0.5 + ref = mx.softmax((q * scale) @ k.swapaxes(-1, -2), axis=-1, stream=mx.cpu) @ v + try: + out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale, stream=mx.cpu) + err = mx.abs(out - ref).max().item() + ok = err < 1e-5 + print(f"{'PASS' if ok else 'FAIL'} decode-shaped SDPA on the CPU stream: max abs error {err:.2e}") + except Exception as e: + ok = False + print(f"FAIL decode-shaped SDPA on the CPU stream: {e}") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mlxcelverse/upstream/10-hip-header-dependencies/0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch b/docs/mlxcelverse/upstream/10-hip-header-dependencies/0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch new file mode 100644 index 000000000..ca4e18a34 --- /dev/null +++ b/docs/mlxcelverse/upstream/10-hip-header-dependencies/0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch @@ -0,0 +1,77 @@ +From 5fac1196929e1389ba90e987fafe6640b295f5a6 Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 15:50:29 +0900 +Subject: [PATCH] fix(rocm): track header dependencies of HIP objects + +Each .hip file is compiled by its own add_custom_command whose only dependency was the .hip source, so CMake never learned which headers an object includes, and an incremental build recompiled no HIP object when only a header changed (kernel_utils.hpp, device.h, lru_cache.h, reduce/reduce.hpp and so on). Fresh builds were correct; reused build trees could link kernels compiled against an old header. + +Each command now passes -MD -MF .d to hipcc and DEPFILE .d to add_custom_command (CMake 3.20 or newer, with CMP0116 set to NEW where it exists). Older CMake falls back to making every HIP object depend on every header under mlx/, which rebuilds them all on any header change; with the 3.25 minimum in the top-level CMakeLists.txt that branch is not reachable today. + +Measured with CMake 3.31.6 and Unix Makefiles on a build of this backend with two more .hip files than this branch (41 HIP objects): before, editing kernel_utils.hpp recompiled none of them; after, it recompiled the 39 whose depfiles name it, an edit to reduce/reduce.hpp recompiled exactly its 7 includers, and a rebuild with no change recompiled none. The depfile comes from the host compilation, so a header included only on the device side is not listed; rocwmma/rocwmma.hpp in flash_attention_wmma.hip is the one such include today. +--- + mlx/backend/rocm/CMakeLists.txt | 40 ++++++++++++++++++++++++++++++++- + 1 file changed, 39 insertions(+), 1 deletion(-) + +diff --git a/mlx/backend/rocm/CMakeLists.txt b/mlx/backend/rocm/CMakeLists.txt +index f1854457..1bbcc13c 100644 +--- a/mlx/backend/rocm/CMakeLists.txt ++++ b/mlx/backend/rocm/CMakeLists.txt +@@ -199,6 +199,34 @@ else() + endif() + endif() + ++# Header dependencies of the HIP objects. The custom commands below are opaque ++# to CMake, so on its own it only knows that each object depends on its .hip ++# file, and a warm build would keep objects compiled against an old version of ++# a header they include (kernel_utils.hpp, device.h, lru_cache.h, ...). hipcc ++# writes one depfile per object (-MD -MF) and DEPFILE hands it to the ++# generator, which then tracks every header the object read, directly or ++# transitively, by absolute path. DEPFILE needs ++# CMake 3.20 with the Makefile generators; CMP0116 NEW makes Ninja interpret ++# relative depfile paths against this binary directory, as the Makefile ++# generators do (the 3.25 minimum in MLX's top-level CMakeLists.txt already ++# implies NEW; the explicit set keeps it under a lower minimum). Older CMake ++# falls back to making every object depend on every header under mlx/, which ++# rebuilds all HIP objects on any header change: slow, but not stale for MLX ++# headers. With the 3.25 minimum the fallback is not reachable today. ++if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.20) ++ if(POLICY CMP0116) ++ cmake_policy(SET CMP0116 NEW) ++ endif() ++ set(HIP_USE_DEPFILE ON) ++ set(HIP_HEADER_DEPS "") ++else() ++ set(HIP_USE_DEPFILE OFF) ++ file( ++ GLOB_RECURSE HIP_HEADER_DEPS CONFIGURE_DEPENDS ++ "${PROJECT_SOURCE_DIR}/mlx/*.h" "${PROJECT_SOURCE_DIR}/mlx/*.hpp" ++ "${PROJECT_SOURCE_DIR}/mlx/*.cuh") ++endif() ++ + # Compile each HIP file to object file using custom commands Use -fno-gpu-rdc to + # avoid needing device link step + set(HIP_OBJECTS "") +@@ -216,12 +244,22 @@ foreach(hip_src ${HIP_SOURCES}) + set(hip_obj "${HIP_OBJ_DIR}/${hip_name}.o") + endif() + ++ if(HIP_USE_DEPFILE) ++ set(hip_dep_flags -MD -MF ${hip_obj}.d) ++ set(hip_depfile_arg DEPFILE ${hip_obj}.d) ++ else() ++ set(hip_dep_flags "") ++ set(hip_depfile_arg "") ++ endif() ++ + add_custom_command( + OUTPUT ${hip_obj} + COMMAND + ${CMAKE_HIP_COMPILER} -c ${hip_src} -o ${hip_obj} -fPIC -DMLX_USE_ROCM + ${HIP_ARCH_FLAGS} ${HIP_INCLUDE_FLAGS} -std=c++17 -parallel-jobs=${NPROC} +- DEPENDS ${hip_src} ++ ${hip_dep_flags} ++ DEPENDS ${hip_src} ${HIP_HEADER_DEPS} ++ ${hip_depfile_arg} + COMMENT "Compiling HIP source ${hip_src}" + VERBATIM) + diff --git a/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md b/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md new file mode 100644 index 000000000..9d61e021e --- /dev/null +++ b/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md @@ -0,0 +1,36 @@ +# fix(rocm): track header dependencies of HIP objects + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch`](0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 26 | +| Reproduction | `repro.sh` (needs a configured build directory) | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +`mlx/backend/rocm/CMakeLists.txt` compiles each `.hip` file with its own `add_custom_command`, whose only dependency was the `.hip` source. CMake never learned which headers an object includes, so an incremental build recompiled no HIP object when only a header changed (`kernel_utils.hpp`, `device.h`, `lru_cache.h`, `reduce/reduce.hpp` and so on). Fresh builds were correct; reused build trees could link kernels compiled against an old header, which also makes a header-only bisect unreliable. The `.cpp` sources added through `target_sources(mlx ...)` were never affected, because CMake scans those itself. + +Each command now passes `-MD -MF .d` to `hipcc` and `DEPFILE .d` to `add_custom_command`, under `if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.20)` (the first version with `DEPFILE` for the Makefile generators), with policy `CMP0116` set to `NEW` when it exists. Below 3.20 every HIP object instead depends on a `file(GLOB_RECURSE ... CONFIGURE_DEPENDS)` list of every `*.h`, `*.hpp` and `*.cuh` under `mlx/` (the HIP sources include MLX headers outside the backend too), which rebuilds every HIP object on any header change. The top-level `CMakeLists.txt` requires CMake 3.25, which also implies `CMP0116` NEW, so that branch only guards a lower minimum. The first build after this change recompiles every HIP object once, because the command line changed. + +Measured on gfx1151 with CMake 3.31.6 and Unix Makefiles, on a build of this backend with two more `.hip` files than this branch (41 HIP objects): before the change, editing `kernel_utils.hpp` recompiled none of them; after it, the same edit recompiled the 39 objects whose depfiles name the header, an edit to `reduce/reduce.hpp` recompiled exactly its 7 includers (both sets agree with a walk of the `#include` graph), reverting each recompiled the same set, and a rebuild with no change recompiled none. The same mechanism was checked under Ninja 1.13 on a small probe project; the full build was not run under Ninja. The depfile comes from the host compilation, so it lists ROCm and system headers too but not headers included only on the device side; `rocwmma/rocwmma.hpp` in `flash_attention_wmma.hip` is the one such include today. + +## Reproduction + +`repro.sh ` edits `kernel_utils.hpp`, rebuilds, and counts the `Compiling HIP source` lines, then restores the header. Without the change the edited build compiles no HIP object. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/10-hip-header-dependencies/repro.sh b/docs/mlxcelverse/upstream/10-hip-header-dependencies/repro.sh new file mode 100755 index 000000000..4c59f4906 --- /dev/null +++ b/docs/mlxcelverse/upstream/10-hip-header-dependencies/repro.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Reproduction for "fix(rocm): track header dependencies of HIP objects". +# +# Usage: repro.sh +# +# Builds once, appends a comment to mlx/backend/rocm/kernel_utils.hpp, builds +# again and counts the "Compiling HIP source" lines, then restores the header +# and builds a third time. Without the fix the edited build recompiles no HIP +# object; with it, it recompiles every object whose depfile names the header +# (all but a few), and the restore build recompiles the same set. +set -euo pipefail +src="$1" +build="$2" +hdr="$src/mlx/backend/rocm/kernel_utils.hpp" + +cmake --build "$build" --target mlx >/dev/null +cp "$hdr" "$hdr.orig" +echo "// header-dependency probe" >>"$hdr" +edited="$(cmake --build "$build" --target mlx 2>&1 | grep -c 'Compiling HIP source' || true)" +mv "$hdr.orig" "$hdr" +restored="$(cmake --build "$build" --target mlx 2>&1 | grep -c 'Compiling HIP source' || true)" +unchanged="$(cmake --build "$build" --target mlx 2>&1 | grep -c 'Compiling HIP source' || true)" +echo "HIP objects recompiled after editing kernel_utils.hpp: $edited" +echo "after restoring it: $restored" +echo "with no change: $unchanged" +[ "$edited" -gt 0 ] && [ "$unchanged" -eq 0 ] diff --git a/docs/mlxcelverse/upstream/README.md b/docs/mlxcelverse/upstream/README.md new file mode 100644 index 000000000..a96bef82a --- /dev/null +++ b/docs/mlxcelverse/upstream/README.md @@ -0,0 +1,73 @@ +# ROCm fixes prepared for NripeshN/mlx `rocm-support` + +mlxcel's ROCm backend is vendored from the `rocm-support` branch of [NripeshN/mlx](https://github.com/NripeshN/mlx/tree/rocm-support) (see `src/lib/mlx-cpp/patches-rocm/UPSTREAM`). Fixes made here that apply to the fork itself are listed in `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md`. This directory turns them into pull requests for the fork, one directory per PR, so the overlay stops drifting from its source (lablup/mlxcel#1813). + +**Nothing here has been submitted, and nothing is submitted by automation.** The maintainer's rule: fork-side fixes become PRs to `NripeshN/mlx` `rocm-support`, prepared here and submitted by hand. Automation never pushes to, forks, or opens issues, PRs or comments on NripeshN/mlx or ml-explore/mlx; only read-only fetches and API reads were used to prepare this. + +## Packages + +State checked on 2026-09-30. The fork's `rocm-support` head is `75915908` (merged 2026-07-19), which is the commit `UPSTREAM` records, and the fork has no open PRs; so none of these fixes has landed in the fork, and every package was built against that head. + +| Package | LOCAL_FIXES items | Applies cleanly to `75915908` | Depends on | Status | Upstream link | +|---|---|---|---|---|---| +| [01 quantized matmul dispatch](01-quantized-matmul-dispatch/pr.md) | 8, 10, 12, 13 | yes | none | ready for manual submission | not submitted | +| [02 ArgReduce grid limit](02-arg-reduce-grid-limit/pr.md) | 11 | yes | none | ready for manual submission | not submitted | +| [03 Scatter size argument and narrow index dtypes](03-scatter-gather-index-types/pr.md) | 14, 17 | yes | none | ready for manual submission | not submitted | +| [04 SliceUpdate tail and source donation](04-slice-update-tail-and-donation/pr.md) | 21, 24 | yes | none | ready for manual submission | not submitted | +| [05 Hadamard](05-hadamard/pr.md) | 16 | yes | none | ready for manual submission | not submitted | +| [06 blocking-sync before the first HIP queue](06-blocking-sync-before-first-queue/pr.md) | 20 | yes | none | ready for manual submission | not submitted | +| [07 FFT through hipFFT](07-fft-hipfft/pr.md) | 18, 25 | no: applies after 05 and 06 (adjacent-line conflicts with 05 in `CMakeLists.txt` and `primitives.cpp`) | 06 at runtime, 05 for a clean apply | ready for manual submission, after 05 and 06 | not submitted | +| [08 launch-geometry helpers](08-launch-geometry-helpers/pr.md) | 19, 22 | yes | none | ready for manual submission | not submitted | +| [09 SDPA fallback on CPU streams](09-sdpa-cpu-stream-fallback/pr.md) | 23 | yes | none | ready for manual submission | not submitted | +| [10 HIP header dependencies](10-hip-header-dependencies/pr.md) | 26 | yes | none | ready for manual submission | not submitted | +| 11 (reserved) mxfp4 qmv nondeterminism | 27 | | | pending: lablup/mlxcel#2072 is still in progress; package it here once it lands | not submitted | + +Packages are grouped the way the fork would review them: all of 01 is `quantized/qmm.hip`, 03 and 04 are the two halves of `indexing.hip` (scatter/gather and slice update), 08 is the two `kernel_utils.hpp` grid helpers. All ten patches also apply in sequence (01 to 10) with `git am`, so they can be submitted in any order that respects 07's dependency. + +Each directory holds the patch (`git format-patch` output, authored by the maintainer, no AI attribution), `pr.md` (PR title, a header table for the submitter, and the PR body below a rule), and the reproduction (`repro.py`, `repro.hip` or `repro.sh`). + +## LOCAL_FIXES entries not packaged + +| Item | Why | +|---|---| +| 1 to 6 | Retarget-only: core-file merges and API drift between the fork's MLX base (`39886de4`) and mlxcel's pin. They go upstream when the fork itself merges newer MLX, and they are recorded in `CORE_RESIDUAL.diff` and `LOCAL_FIXES.md`, not here. | +| 7 (GPU fault reporting) | Deferred. It is built on `Event::error()`, which ml-explore/mlx added in #3742 (`06f154bc`, 2026-08-17); the fork's MLX base predates it, so the patch does not apply. The wait changes that end a hang on a faulted queue (`HipEvent::wait`, `AtomicEvent`, `CommandEncoder::synchronize`) could be split out for the current fork, but that would be a different change from the one mlxcel ships and verified. Package it once the fork merges MLX at or past #3742. | +| 9 (expert-batched gather qmv opt-in) | Held. It disables a path that returns wrong bf16 results on gfx1151 but has no root cause yet; LOCAL_FIXES.md says to propose it only after one. | +| 15 (`SearchSorted`) | Not applicable yet: the primitive arrived in ml-explore/mlx#4035 (`5ec30acd`, 2026-08-10), after the fork's MLX base, so the fork has no `SearchSorted` to implement. Package it once the fork merges MLX at or past #4035. | + +## What was verified, and what the submitter still has to do + +Verified while preparing (2026-09-30): + +- Every patch was produced by a 3-way merge of the mlxcel commit that made the fix onto the fork file, with retarget-only hunks and item 9 left out and mlxcel-specific comments rewritten. `git apply --check` passes for each package on `75915908` (07 on `75915908` plus 05 and 06), and `git am` of all ten in order succeeds. +- After applying all ten, the fork's `mlx/backend/rocm/` differs from mlxcel's overlay only by the retarget items (2 to 6), items 7, 9 and 15, and comment wording. +- The evidence in each PR body comes from the mlxcel change and its tests, measured on gfx1151 (Radeon 8060S, HIP 7.15) with the backend retargeted onto MLX `81ba1c6a`; each body says so. + +Not verified, to do before submitting each PR: + +- **Build the fork with the patch.** The patches were not compiled against the fork head: preparing them did not build the fork. The fork's MLX base is older than mlxcel's pin, so check at least that it compiles; the fork's `build_rocm.yml` builds a wheel with `CMAKE_ARGS="-DMLX_BUILD_ROCM=ON -DMLX_ROCM_ARCHITECTURES=gfx1151 -DBLA_VENDOR=OpenBLAS"`. Package 03 adds a compile-time argument-size check to `add_kernel_node`; a fork call site that mlxcel never compiled would fail there, which is the point of the check but should be fixed in the same PR. +- **Run the reproduction** on the unpatched fork and on the patched one. None of the scripts has been run against a build of the fork; they follow the mlxcel tests that verified each fix. Several unpatched cases fault the GPU queue, so those scripts run each case in a child process with a timeout. +- **Run `pre-commit run --all-files`** (clang-format, black, cmake-format), which the fork's PR template asks for. It was not run. +- **Tick the checklist honestly.** The PR bodies end with the fork's template checklist, unticked. + +## Contribution guidelines and the fork's stance on automated PRs + +Read on 2026-09-30, read-only. + +- **The fork's `CONTRIBUTING.md`** (at `75915908`) is MLX's older generic text: fork and open a PR, add tests for code that should be tested, run benchmarks for efficiency-sensitive changes, update docs for API changes, every PR needs passing tests and at least one review, format with `pre-commit` (clang-format, black). Issues are disabled on the fork (`has_issues: false`), so a PR is the only channel. +- **The fork's PR template** (at `75915908`) has "Proposed changes" and a four-box checklist (read CONTRIBUTING, ran pre-commit, added tests, updated docs). It says nothing about AI or automation. The `pr.md` bodies follow its shape. +- **Recent PR history.** 13 PRs, all against `rocm-support` except one, 8 merged, from 4 contributors; the last merge was #13 on 2026-07-19 and nothing has merged since. Merges happen without formal GitHub reviews (0 reviews on the merged PRs sampled, a few comments each). Titles follow `fix(rocm): ...` / `ROCm: ...`, which the patches match. +- **Upstream MLX's policy matters too.** The fork's branch is the head of ml-explore/mlx#2300 (open), so what merges into the fork is headed for ml-explore review. On 2026-08-20 ml-explore/mlx added an AI usage policy (#4331): its PR template now opens with "I understand it is strictly prohibited to use AI to write PR description" and an "AI usage disclosure" field, and its `CONTRIBUTING.md` says contributors stay accountable for AI-assisted work, which must meet the same standards, and that written material should be in the contributor's own voice. The fork's branch predates this and its template does not carry it. +- **What that means for these packages.** The patches, commit messages and `pr.md` bodies were drafted with AI assistance for the maintainer to review. Nothing in the fork's own rules forbids that, but ml-explore's policy forbids AI-written PR descriptions for its repository, and the fork's maintainer may apply the same expectation. Decide before submitting; the conservative path is to treat each `pr.md` as notes, write the PR description in your own words, and state AI assistance in the description if the fork asks for a disclosure. + +## Submitting one package by hand + +1. Fork NripeshN/mlx under your account (a manual step; automation does not create forks) and branch from `rocm-support`. +2. `git am docs/mlxcelverse/upstream//*.patch` (for 07, apply 05 and 06 first or wait until they merge). +3. Build, run the reproduction before and after, run `pre-commit`. +4. Open the PR against `NripeshN/mlx:rocm-support` with the title and a description based on `pr.md`. +5. Record the link: set the "Upstream link" cell above and add "Proposed upstream: " to the matching `LOCAL_FIXES.md` items. + +## Keeping the packages current + +The packages target the fork head named above. After a fork sync (`scripts/mlxcelverse/sync_from_fork.sh`, see `docs/mlxcelverse/rocm-overlay.md`), check which packages the fork has absorbed, drop them here and from the "applies to the fork" wording in LOCAL_FIXES.md, and regenerate the rest against the new head. A new LOCAL_FIXES entry that applies to the fork gets a directory here in the same shape. diff --git a/scripts/mlxcelverse/check_api_drift.sh b/scripts/mlxcelverse/check_api_drift.sh new file mode 100755 index 000000000..338de0e90 --- /dev/null +++ b/scripts/mlxcelverse/check_api_drift.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Build the ROCm tree at a candidate MLX commit and list what breaks +# (issue #1813). +# +# Usage: +# scripts/mlxcelverse/check_api_drift.sh [options] +# +# Options: +# --mlx-commit SHA MLX commit to build against (default: the current pin) +# --rocm-from SPEC `overlay` (default): the committed ROCm overlay; +# `fork:`: that fork commit's mlx/backend/rocm/ with +# the overlay's core files, which shows what the fork's +# own code needs to compile against the candidate +# --work-dir DIR where to put the source tree, build and report +# (default: a new temporary directory) +# --jobs N parallel build jobs (default: 8) +# --arch LIST HIP targets (default: $MLX_ROCM_ARCHITECTURES, else +# the first gfx target rocminfo reports) +# --git-dir DIR, --no-fetch +# passed to rocm_overlay.py (git cache, offline mode) +# +# Run it on an AMD host with ROCm installed, typically after +# `rocm_overlay.py retarget` in a pin bump, or before a fork sync with +# `--rocm-from fork:`. It configures MLX standalone with the same +# ROCm options src/lib/mlxcel-core/build.rs passes, builds the `mlx` target +# with `make -k` so every failing translation unit is reported rather than the +# first, and then compares the defined and undefined symbols of every object: +# a primitive without a ROCm `eval_gpu` only shows up as an undefined +# mlx::core symbol, because libmlx is a static archive and nothing links it +# here. The report (compile errors, undefined symbols) is printed and written +# to /api-drift-report.txt; the exit status is 1 when anything is +# listed. It is a manual step, not part of `make verify-rocm`: it needs the +# network for MLX's own FetchContent dependencies and takes as long as a cold +# MLX build. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +mlx_commit="" +rocm_from="overlay" +work="" +jobs=8 +arch="${MLX_ROCM_ARCHITECTURES:-}" +git_args=() + +while [ $# -gt 0 ]; do + case "$1" in + --mlx-commit) mlx_commit="$2"; shift 2 ;; + --rocm-from) rocm_from="$2"; shift 2 ;; + --work-dir) work="$2"; shift 2 ;; + --jobs) jobs="$2"; shift 2 ;; + --arch) arch="$2"; shift 2 ;; + --git-dir) git_args+=(--git-dir "$2"); shift 2 ;; + --no-fetch) git_args+=(--no-fetch); shift ;; + -h|--help) sed -n '2,/^set -euo/p' "$0" | sed '$d; s/^# \{0,1\}//'; exit 0 ;; + *) echo "check_api_drift: unknown option $1" >&2; exit 2 ;; + esac +done + +rocm="${ROCM_PATH:-/opt/rocm}" +if [ ! -x "$rocm/bin/hipcc" ]; then + echo "check_api_drift: $rocm/bin/hipcc not found; set ROCM_PATH" >&2 + exit 2 +fi +if [ -z "$arch" ]; then + arch="$({ "$rocm/bin/rocminfo" 2>/dev/null || rocminfo 2>/dev/null || true; } | grep -o 'gfx[0-9a-f]*' | head -1)" +fi +if [ -z "$arch" ]; then + echo "check_api_drift: no HIP target; pass --arch or set MLX_ROCM_ARCHITECTURES" >&2 + exit 2 +fi + +if [ -z "$work" ]; then + work="$(mktemp -d -t mlxcelverse-api-drift.XXXXXX)" +fi +mkdir -p "$work" +src="$work/src" +build="$work/build" + +export_args=(export-tree --dest "$src" --rocm-from "$rocm_from") +if [ -n "$mlx_commit" ]; then + export_args+=(--mlx-commit "$mlx_commit") +fi +python3 "$here/rocm_overlay.py" "${export_args[@]}" "${git_args[@]}" + +echo "[api-drift] configuring (log: $work/configure.log)" +if ! cmake -S "$src" -B "$build" -G "Unix Makefiles" \ + -DCMAKE_BUILD_TYPE=Release \ + -DMLX_BUILD_ROCM=ON \ + -DCMAKE_HIP_ARCHITECTURES="$arch" \ + -DMLX_ROCM_ARCHITECTURES="$arch" \ + -DCMAKE_PREFIX_PATH="$rocm" \ + -DROCM_PATH="$rocm" \ + -DCMAKE_HIP_COMPILER="$rocm/bin/hipcc" \ + -DMLX_BUILD_METAL=OFF \ + -DMLX_BUILD_CUDA=OFF \ + -DMLX_BUILD_ACCELERATE=OFF \ + -DMLX_BUILD_TESTS=OFF \ + -DMLX_BUILD_EXAMPLES=OFF \ + -DMLX_BUILD_BENCHMARKS=OFF \ + -DMLX_BUILD_PYTHON_BINDINGS=OFF >"$work/configure.log" 2>&1; then + tail -30 "$work/configure.log" >&2 + echo "check_api_drift: CMake configure failed; see $work/configure.log" >&2 + exit 2 +fi + +echo "[api-drift] building target mlx with -k -j$jobs (log: $work/build.log)" +cmake --build "$build" --target mlx -j "$jobs" -- -k >"$work/build.log" 2>&1 || true + +find "$build" -name '*.o' -print0 | xargs -0 -r nm -C --defined-only 2>/dev/null >"$work/defined.txt" || true +find "$build" -name '*.o' -print0 | xargs -0 -r nm -C --undefined-only 2>/dev/null >"$work/undefined.txt" || true + +python3 "$here/rocm_overlay.py" api-report \ + --build-log "$work/build.log" \ + --defined "$work/defined.txt" \ + --undefined "$work/undefined.txt" \ + --source-dir "$src" \ + --output "$work/api-drift-report.txt" diff --git a/scripts/mlxcelverse/rocm_overlay.py b/scripts/mlxcelverse/rocm_overlay.py new file mode 100755 index 000000000..a336cc821 --- /dev/null +++ b/scripts/mlxcelverse/rocm_overlay.py @@ -0,0 +1,1041 @@ +#!/usr/bin/env python3 +"""Maintenance tooling for the mlxcelverse ROCm overlay (issue #1813). + +The overlay in src/lib/mlx-cpp/patches-rocm/ has two moving upstreams: the MLX +pin (ml-explore/mlx) and the fork it vendors its backend from +(NripeshN/mlx@rocm-support). `UPSTREAM` records the three commits that define +it: the fork commit, the fork's merge base with upstream MLX, and the MLX pin +the core files were retargeted to. Every subcommand works from those records. + +Subcommands: + + records Offline and fast; run by `make verify-rocm-overlay`. Checks that + the records agree with each other and with the tree: UPSTREAM is + well formed and its pin is the build's pin, the README counts are + the real ones, LOCAL_FIXES.md is numbered without gaps, and + CORE_RESIDUAL.diff was generated for the current commits and the + current content of every core overlay file. + drift Needs the three recorded commits (fetched into a cache). Rebuilds + each core file as "MLX pin + the fork's own change to that file" + with a 3-way merge and diffs the overlay against it. Whatever is + left is the overlay's residual: changes that are neither upstream + nor the fork's. It must match CORE_RESIDUAL.diff, where every file + carries a note naming its LOCAL_FIXES.md item. Also checks that + every backend file that differs from the fork, and every fork hook + the overlay does not carry, is named in LOCAL_FIXES.md. + sync Moves the overlay to a new fork commit: 3-way merges each backend + file (old fork, overlay, new fork) and each core file ("pin + old + fork delta", overlay, "pin + new fork delta"), carries local-only + files, and updates UPSTREAM. `--check` syncs into a scratch copy + and compares it with the committed overlay byte for byte. + retarget Moves the core files to a new MLX pin by 3-way merging each one + (old pin, overlay, new pin) and updates UPSTREAM. + export-tree + Writes the MLX tree at a commit with the ROCm files laid over it, + for scripts/mlxcelverse/check_api_drift.sh. + api-report + Summarizes a build log and `nm` output into compile errors and + undefined mlx::core symbols, for check_api_drift.sh. + +Git objects come from a cache repository (default +~/.cache/mlxcel/mlxcelverse/mlx.git, override with --git-dir or +MLXCELVERSE_GIT_DIR). It is created and fetched on demand unless --no-fetch is +given. Nothing is ever pushed. +""" + +from __future__ import annotations + +import argparse +import difflib +import hashlib +import os +import re +import shutil +import subprocess +import sys +import tempfile +from dataclasses import dataclass, field +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parents[1] +DEFAULT_OVERLAY = REPO_ROOT / "src" / "lib" / "mlx-cpp" / "patches-rocm" +PIN_SCRIPT = REPO_ROOT / "scripts" / "ci" / "mlx_pinned_commit.sh" + +# Files at the overlay root that are records, never copied into MLX. +RECORDS = ("README.md", "UPSTREAM", "LOCAL_FIXES.md", "CORE_RESIDUAL.diff") +RESIDUAL_FILE = "CORE_RESIDUAL.diff" +BACKEND_PREFIX = "mlx/backend/rocm/" +UPSTREAM_KEYS = ( + "source", + "branch", + "commit", + "fork_upstream_merge_base", + "retargeted_to_mlx_pin", +) +SHA_KEYS = ("commit", "fork_upstream_merge_base", "retargeted_to_mlx_pin") +SHA_RE = re.compile(r"^[0-9a-f]{40}$") + +DEFAULT_FORK_URL = "https://github.com/NripeshN/mlx.git" +DEFAULT_FORK_BRANCH = "rocm-support" +DEFAULT_MLX_URL = "https://github.com/ml-explore/mlx.git" +DEFAULT_MLX_BRANCH = "main" + +NOTE_TODO = "TODO: name the LOCAL_FIXES.md item this residual implements" + + +class ToolError(Exception): + """A failure with a message for the user; exits 2.""" + + +# -------------------------------------------------------------------------- +# Small helpers + + +def read_bytes(path: Path) -> bytes: + return path.read_bytes() + + +def text(data: bytes) -> str: + return data.decode("utf-8", errors="surrogateescape") + + +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def unified_diff(old: bytes, new: bytes, path: str) -> str: + """A `diff -u` style patch from old to new, stable across hosts.""" + a = text(old).splitlines(keepends=True) + b = text(new).splitlines(keepends=True) + out = [] + for line in difflib.unified_diff(a, b, f"a/{path}", f"b/{path}", n=3): + if line.startswith(("---", "+++")): + out.append(line.rstrip("\n") + "\n") + continue + if not line.endswith("\n"): + out.append(line + "\n\\ No newline at end of file\n") + else: + out.append(line) + return "".join(out) + + +def normalize_patch(patch: str) -> str: + """Drop hunk line numbers so a pure line shift is not a residual change.""" + return re.sub(r"(?m)^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@", "@@", patch) + + +def patch_stats(patch: str) -> tuple[int, int]: + plus = minus = 0 + for line in patch.splitlines(): + if line.startswith("+++") or line.startswith("---"): + continue + if line.startswith("+"): + plus += 1 + elif line.startswith("-"): + minus += 1 + return plus, minus + + +# -------------------------------------------------------------------------- +# Overlay model + + +@dataclass +class Overlay: + root: Path + + def files(self) -> list[str]: + """Every overlay file (not records), as paths relative to the root.""" + out = [] + for p in sorted(self.root.rglob("*")): + if not p.is_file(): + continue + rel = p.relative_to(self.root).as_posix() + if rel in RECORDS: + continue + out.append(rel) + return out + + def core_files(self) -> list[str]: + return [f for f in self.files() if not f.startswith(BACKEND_PREFIX)] + + def backend_files(self) -> list[str]: + return [f for f in self.files() if f.startswith(BACKEND_PREFIX)] + + def read(self, rel: str) -> bytes: + return (self.root / rel).read_bytes() + + def upstream(self) -> dict[str, str]: + return parse_upstream((self.root / "UPSTREAM").read_text()) + + +def parse_upstream(content: str) -> dict[str, str]: + values = {} + for line in content.splitlines(): + if not line.strip(): + continue + key, sep, value = line.partition(":") + if not sep: + raise ToolError(f"UPSTREAM: malformed line {line!r}") + values[key.strip()] = value.strip() + return values + + +def update_upstream(content: str, changes: dict[str, str]) -> str: + out = [] + seen = set() + for line in content.splitlines(keepends=True): + key, sep, _ = line.partition(":") + k = key.strip() + if sep and k in changes: + nl = "\n" if line.endswith("\n") else "" + out.append(f"{k}: {changes[k]}{nl}") + seen.add(k) + else: + out.append(line) + missing = set(changes) - seen + if missing: + raise ToolError(f"UPSTREAM: missing keys {sorted(missing)}") + return "".join(out) + + +def pinned_commit() -> str: + """The build's MLX pin, from the single source of truth.""" + proc = subprocess.run( + ["bash", str(PIN_SCRIPT)], capture_output=True, text=True, check=False + ) + if proc.returncode != 0: + raise ToolError(f"mlx_pinned_commit.sh failed: {proc.stderr.strip()}") + return proc.stdout.strip() + + +# -------------------------------------------------------------------------- +# Residual record + + +@dataclass +class Residual: + pin: str = "" + fork: str = "" + base: str = "" + hashes: dict[str, str] = field(default_factory=dict) + notes: dict[str, str] = field(default_factory=dict) + body: str = "" # the concatenated per-file patches + + +RESIDUAL_PREAMBLE = """\ +# CORE_RESIDUAL.diff: what the ROCm overlay's MLX core files carry beyond the +# MLX pin plus the fork's own change to each file. +# +# Generated by `scripts/mlxcelverse/rocm_overlay.py drift --write`; do not +# edit the patches by hand. For each core overlay file the tool rebuilds +# "pin + fork delta" (a 3-way merge of the fork commit into the pin, using the +# fork's merge base with upstream as the base; conflict markers stay in) and +# diffs the overlay against it. A file that matches has no entry. Every +# entry needs a `# note :` line naming the LOCAL_FIXES.md item that +# explains it; `drift --write` keeps existing notes. `rocm_overlay.py records` +# (make verify-rocm-overlay) fails when the commits below are not the ones in +# UPSTREAM or a core file's hash no longer matches, so any change to a core +# overlay, a pin bump or a fork sync has to re-run `drift` and review this +# file. That review is the line-by-line comparison a count of +/- lines cannot +# replace: an overlay that silently drops part of an upstream change shows up +# here as a new hunk, even if it was wrong before the bump. +""" + + +def parse_residual(content: str) -> Residual: + res = Residual() + lines = content.splitlines(keepends=True) + i = 0 + while i < len(lines) and not lines[i].startswith("--- "): + line = lines[i].rstrip("\n") + i += 1 + if not line.startswith("#"): + if line.strip(): + raise ToolError(f"{RESIDUAL_FILE}: unexpected header line {line!r}") + continue + body = line[1:].strip() + for key, attr in (("pin:", "pin"), ("fork:", "fork"), ("fork_upstream_merge_base:", "base")): + if body.startswith(key): + setattr(res, attr, body[len(key):].strip()) + if body.startswith("overlay-sha256:"): + parts = body[len("overlay-sha256:"):].split() + if len(parts) != 2: + raise ToolError(f"{RESIDUAL_FILE}: malformed hash line {line!r}") + res.hashes[parts[1]] = parts[0] + elif body.startswith("note "): + path, sep, note = body[len("note "):].partition(":") + if not sep: + raise ToolError(f"{RESIDUAL_FILE}: malformed note line {line!r}") + res.notes[path.strip()] = note.strip() + res.body = "".join(lines[i:]) + return res + + +def residual_files(body: str) -> list[str]: + return [ + m.group(1) + for m in re.finditer(r"(?m)^\+\+\+ b/(\S+)$", body) + ] + + +def render_residual(res: Residual) -> str: + out = [RESIDUAL_PREAMBLE, "#\n"] + out.append(f"# pin: {res.pin}\n") + out.append(f"# fork: {res.fork}\n") + out.append(f"# fork_upstream_merge_base: {res.base}\n") + for path in sorted(res.hashes): + out.append(f"# overlay-sha256: {res.hashes[path]} {path}\n") + for path in residual_files(res.body): + out.append(f"# note {path}: {res.notes.get(path, NOTE_TODO)}\n") + out.append("\n") + out.append(res.body) + return "".join(out) + + +# -------------------------------------------------------------------------- +# Git access + + +class Git: + def __init__(self, git_dir: Path, fetch: bool): + self.git_dir = git_dir + self.fetch_enabled = fetch + + def run(self, *args: str, check: bool = True, input: bytes | None = None) -> subprocess.CompletedProcess: + proc = subprocess.run( + ["git", f"--git-dir={self.git_dir}", *args], + capture_output=True, + input=input, + check=False, + ) + if check and proc.returncode != 0: + raise ToolError( + f"git {' '.join(args)} failed: {proc.stderr.decode(errors='replace').strip()}" + ) + return proc + + def ensure_repo(self, fork_url: str, mlx_url: str) -> None: + if (self.git_dir / "HEAD").exists(): + return + if not self.fetch_enabled: + raise ToolError( + f"no git cache at {self.git_dir}; run without --no-fetch once or pass --git-dir" + ) + self.git_dir.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "init", "-q", "--bare", str(self.git_dir)], check=True) + self.run("remote", "add", "fork", fork_url) + self.run("remote", "add", "upstream", mlx_url) + + def has_commit(self, sha: str) -> bool: + return self.run("cat-file", "-e", f"{sha}^{{commit}}", check=False).returncode == 0 + + def fetch(self, remote: str, *refspecs: str) -> None: + if not self.fetch_enabled: + raise ToolError(f"missing objects and --no-fetch given (wanted {refspecs} from {remote})") + print(f"fetching {' '.join(refspecs)} from {remote} ...", file=sys.stderr) + self.run("fetch", "-q", "--no-tags", remote, *refspecs) + + def ensure_commit(self, sha: str, remote: str) -> None: + if not self.has_commit(sha): + self.fetch(remote, sha) + if not self.has_commit(sha): + raise ToolError(f"commit {sha} not found on {remote}") + + def resolve(self, rev: str) -> str: + return text(self.run("rev-parse", "--verify", f"{rev}^{{commit}}").stdout).strip() + + def show(self, sha: str, path: str) -> bytes | None: + proc = self.run("cat-file", "blob", f"{sha}:{path}", check=False) + if proc.returncode != 0: + return None + return proc.stdout + + def ls_tree(self, sha: str, prefix: str) -> list[str]: + out = self.run("ls-tree", "-r", "--name-only", sha, "--", prefix).stdout + return [line for line in text(out).splitlines() if line] + + def changed_paths(self, a: str, b: str) -> list[str]: + out = self.run("diff", "--name-only", "--no-renames", a, b).stdout + return [line for line in text(out).splitlines() if line] + + def is_ancestor(self, a: str, b: str) -> bool: + return self.run("merge-base", "--is-ancestor", a, b, check=False).returncode == 0 + + def merge_base(self, a: str, b: str) -> str: + return text(self.run("merge-base", a, b).stdout).strip() + + +def merge3(ours: bytes, base: bytes, theirs: bytes, labels: tuple[str, str, str]) -> tuple[bytes, int]: + """`git merge-file -p`: returns the merged content and the conflict count.""" + if base == theirs: + return ours, 0 + if base == ours: + return theirs, 0 + with tempfile.TemporaryDirectory(prefix="mlxcelverse-merge-") as tmp: + paths = [] + for name, data in (("ours", ours), ("base", base), ("theirs", theirs)): + p = Path(tmp) / name + p.write_bytes(data) + paths.append(str(p)) + proc = subprocess.run( + ["git", "merge-file", "-p", "-L", labels[0], "-L", labels[1], "-L", labels[2], *paths], + capture_output=True, + check=False, + ) + if proc.returncode < 0 or proc.returncode > 127: + raise ToolError(f"git merge-file failed: {proc.stderr.decode(errors='replace')}") + return proc.stdout, proc.returncode + + +def reconstruct(git: Git, pin: str, base: str, fork: str, path: str) -> tuple[bytes, int]: + """The pin's copy of `path` with the fork's own change to it merged in.""" + pin_b = git.show(pin, path) + base_b = git.show(base, path) + fork_b = git.show(fork, path) + if fork_b is None: + # The fork does not have the file; the reconstruction is the pin's. + return pin_b or b"", 0 + return merge3(pin_b or b"", base_b or b"", fork_b, ("pin", "fork-merge-base", "fork")) + + +# -------------------------------------------------------------------------- +# Shared context + + +@dataclass +class Context: + overlay: Overlay + git: Git | None + fork_url: str + mlx_url: str + + +def make_context(args: argparse.Namespace, need_git: bool) -> Context: + overlay = Overlay(Path(args.overlay_dir).resolve()) + if not (overlay.root / "UPSTREAM").is_file(): + raise ToolError(f"{overlay.root} has no UPSTREAM record") + git = None + if need_git: + git_dir = Path( + args.git_dir + or os.environ.get("MLXCELVERSE_GIT_DIR") + or Path.home() / ".cache" / "mlxcel" / "mlxcelverse" / "mlx.git" + ) + git = Git(git_dir, fetch=not args.no_fetch) + git.ensure_repo(args.fork_url, args.mlx_url) + return Context(overlay, git, args.fork_url, args.mlx_url) + + +def ensure_recorded_commits(ctx: Context, up: dict[str, str]) -> None: + assert ctx.git is not None + ctx.git.ensure_commit(up["commit"], "fork") + ctx.git.ensure_commit(up["fork_upstream_merge_base"], "fork") + ctx.git.ensure_commit(up["retargeted_to_mlx_pin"], "upstream") + + +def local_fixes_mentions(overlay: Overlay, path: str) -> bool: + """True if LOCAL_FIXES.md names `path`, by full path, backend-relative path + or file name (not as part of a longer name).""" + content = (overlay.root / "LOCAL_FIXES.md").read_text() + rel = path[len(BACKEND_PREFIX):] if path.startswith(BACKEND_PREFIX) else path + for candidate in {path, rel, Path(path).name}: + if re.search(rf"(? int: + overlay = Overlay(Path(args.overlay_dir).resolve()) + errors: list[str] = [] + root = overlay.root + + # Stray files at the overlay root are neither copied nor records. + for p in sorted(root.iterdir()): + name = p.name + if name in RECORDS or name in ("CMakeLists.txt", "mlx"): + continue + errors.append( + f"{name}: not a record ({', '.join(RECORDS)}) and not an overlay path (CMakeLists.txt, mlx/); " + "CMake would silently ignore it" + ) + for rec in RECORDS: + if not (root / rec).is_file(): + errors.append(f"{rec}: missing") + if errors: + return report("records", errors) + + # UPSTREAM. + up = overlay.upstream() + for key in UPSTREAM_KEYS: + if key not in up: + errors.append(f"UPSTREAM: missing `{key}`") + for key in SHA_KEYS: + if key in up and not SHA_RE.match(up[key]): + errors.append(f"UPSTREAM: `{key}` is {up[key]!r}, not a full 40-character lowercase SHA") + pin = args.pin or pinned_commit() + if up.get("retargeted_to_mlx_pin") and up["retargeted_to_mlx_pin"] != pin: + errors.append( + f"UPSTREAM: retargeted_to_mlx_pin is {up['retargeted_to_mlx_pin']} but the MLX pin is {pin}. " + "A pin bump has to retarget the ROCm overlay too: run " + "`scripts/mlxcelverse/rocm_overlay.py retarget`, then `drift` (docs/mlxcelverse/rocm-overlay.md)." + ) + + # README counts. + readme = (root / "README.md").read_text() + backend = overlay.backend_files() + core = overlay.core_files() + m = re.search(r"`mlx/backend/rocm/\*\*`: the ROCm backend \((\d+) files\)", readme) + if not m: + errors.append("README.md: no '`mlx/backend/rocm/**`: the ROCm backend (N files)' line") + elif int(m.group(1)) != len(backend): + errors.append(f"README.md: says the backend has {m.group(1)} files; it has {len(backend)}") + m = re.search(r"(\d+) MLX core files", readme) + if not m: + errors.append("README.md: no 'N MLX core files' statement") + elif int(m.group(1)) != len(core): + errors.append(f"README.md: says {m.group(1)} MLX core files; the overlay has {len(core)}") + for path in core: + # Every core file must be listed, in the README's brace-list form or plainly. + name = Path(path).name + stem = Path(path).stem + if name not in readme and stem not in readme: + errors.append(f"README.md: core file {path} is not listed") + + # LOCAL_FIXES numbering. + fixes = (root / "LOCAL_FIXES.md").read_text() + numbers = [int(n) for n in re.findall(r"(?m)^(\d+)\. \*\*", fixes)] + if not numbers: + errors.append("LOCAL_FIXES.md: no numbered entries") + elif numbers != list(range(1, len(numbers) + 1)): + errors.append(f"LOCAL_FIXES.md: entries are numbered {numbers}, expected 1..{len(numbers)} in order") + + # Residual record. + res = parse_residual((root / RESIDUAL_FILE).read_text()) + for attr, key in (("pin", "retargeted_to_mlx_pin"), ("fork", "commit"), ("base", "fork_upstream_merge_base")): + if getattr(res, attr) != up.get(key): + errors.append( + f"{RESIDUAL_FILE}: generated for {attr} {getattr(res, attr) or '(none)'} but UPSTREAM has " + f"{key} {up.get(key)}; re-run `rocm_overlay.py drift`, review, then `drift --write`" + ) + if set(res.hashes) != set(core): + missing = sorted(set(core) - set(res.hashes)) + extra = sorted(set(res.hashes) - set(core)) + errors.append(f"{RESIDUAL_FILE}: core file set differs (not hashed: {missing}, no longer core: {extra})") + for path in core: + if path in res.hashes and res.hashes[path] != sha256(overlay.read(path)): + errors.append( + f"{RESIDUAL_FILE}: {path} changed since the residual was generated; run " + "`rocm_overlay.py drift`, review the residual, then `drift --write`" + ) + files = residual_files(res.body) + for path in files: + if path not in core: + errors.append(f"{RESIDUAL_FILE}: residual for {path}, which is not a core overlay file") + note = res.notes.get(path, "") + if not note or note.startswith("TODO"): + errors.append(f"{RESIDUAL_FILE}: {path} has a residual but no note naming its LOCAL_FIXES.md item") + for path in res.notes: + if path not in files: + errors.append(f"{RESIDUAL_FILE}: note for {path}, which has no residual") + + if not errors: + print( + f"[rocm-overlay] records OK: {len(backend)} backend + {len(core)} core files, " + f"{len(numbers)} LOCAL_FIXES entries, {len(files)} core files with a noted residual, pin {pin[:8]}" + ) + return report("records", errors) + + +def report(what: str, errors: list[str]) -> int: + for e in errors: + print(f"[rocm-overlay] {what}: {e}", file=sys.stderr) + return 1 if errors else 0 + + +# -------------------------------------------------------------------------- +# drift + + +def compute_residual(ctx: Context, up: dict[str, str]) -> tuple[str, dict[str, int]]: + assert ctx.git is not None + patches = [] + conflicts = {} + for path in ctx.overlay.core_files(): + recon, n = reconstruct( + ctx.git, up["retargeted_to_mlx_pin"], up["fork_upstream_merge_base"], up["commit"], path + ) + if n: + conflicts[path] = n + patch = unified_diff(recon, ctx.overlay.read(path), path) + if patch: + patches.append(patch) + return "".join(patches), conflicts + + +def cmd_drift(args: argparse.Namespace) -> int: + ctx = make_context(args, need_git=True) + assert ctx.git is not None + up = ctx.overlay.upstream() + ensure_recorded_commits(ctx, up) + errors: list[str] = [] + overlay = ctx.overlay + fork, base, pin = up["commit"], up["fork_upstream_merge_base"], up["retargeted_to_mlx_pin"] + + if not ctx.git.is_ancestor(base, fork): + errors.append(f"UPSTREAM: fork_upstream_merge_base {base} is not an ancestor of commit {fork}") + + # Core files. + body, conflicts = compute_residual(ctx, up) + record_path = overlay.root / RESIDUAL_FILE + old = parse_residual(record_path.read_text()) if record_path.is_file() else Residual() + new = Residual( + pin=pin, + fork=fork, + base=base, + hashes={p: sha256(overlay.read(p)) for p in overlay.core_files()}, + notes={p: n for p, n in old.notes.items() if p in residual_files(body)}, + body=body, + ) + print(f"[rocm-overlay] core files: {len(overlay.core_files())}, reconstructed from pin {pin[:8]} + fork {fork[:8]} (merge base {base[:8]})") + per_file = {} + for chunk in re.split(r"(?m)^(?=--- a/)", body): + if chunk.strip(): + m = re.search(r"(?m)^\+\+\+ b/(\S+)$", chunk) + if m: + per_file[m.group(1)] = chunk + for path in overlay.core_files(): + if path in per_file: + plus, minus = patch_stats(per_file[path]) + tag = f", {conflicts[path]} merge conflict(s) resolved by the overlay" if path in conflicts else "" + print(f" residual {path}: +{plus} -{minus}{tag}") + changed = normalize_patch(new.body) != normalize_patch(old.body) + if args.show: + sys.stdout.write(new.body) + if changed: + diff = "".join( + difflib.unified_diff( + old.body.splitlines(keepends=True), + new.body.splitlines(keepends=True), + f"{RESIDUAL_FILE} (recorded)", + f"{RESIDUAL_FILE} (now)", + n=2, + ) + ) + print("[rocm-overlay] the core residual changed; review every hunk below:") + sys.stdout.write(diff) + if not args.write: + errors.append( + f"core residual differs from {RESIDUAL_FILE}; if every change is intended, note it in LOCAL_FIXES.md and re-run with --write" + ) + stale_header = (old.pin, old.fork, old.base, old.hashes) != (new.pin, new.fork, new.base, new.hashes) + if not changed and stale_header and not args.write: + errors.append(f"{RESIDUAL_FILE} header is stale (commits or file hashes); the residual itself is unchanged, re-run with --write") + + # Backend files against the fork. + fork_backend = set(ctx.git.ls_tree(fork, BACKEND_PREFIX)) + ours_backend = set(overlay.backend_files()) + modified, local_only = [], [] + for path in sorted(ours_backend): + fb = ctx.git.show(fork, path) if path in fork_backend else None + if fb is None: + local_only.append(path) + elif fb != overlay.read(path): + modified.append(path) + dropped = sorted(fork_backend - ours_backend) + print(f"[rocm-overlay] backend: {len(ours_backend)} files, {len(modified)} modified from the fork, {len(local_only)} local-only, {len(dropped)} dropped") + for path in modified + local_only + dropped: + if not local_fixes_mentions(overlay, path): + errors.append(f"{path} differs from the fork (modified, local-only or dropped) but LOCAL_FIXES.md does not name it") + + # Fork hooks outside the backend that the overlay does not carry. + core = set(overlay.core_files()) + uncarried = [ + p + for p in ctx.git.changed_paths(base, fork) + if (p.startswith("mlx/") or p == "CMakeLists.txt") + and not p.startswith(BACKEND_PREFIX) + and p not in core + ] + for path in uncarried: + if not local_fixes_mentions(overlay, path): + errors.append(f"the fork changes {path}, which the overlay does not carry, and LOCAL_FIXES.md does not say why") + for path in sorted(core): + if ctx.git.show(fork, path) == ctx.git.show(base, path) and path not in per_file: + print(f" note: the fork does not change {path} and neither does the overlay; the overlay copy may be droppable") + + if args.write: + record_path.write_text(render_residual(new)) + print(f"[rocm-overlay] wrote {record_path}") + todo = [p for p in residual_files(new.body) if p not in new.notes] + for path in todo: + print(f"[rocm-overlay] add a note for {path} in {RESIDUAL_FILE} (it has a TODO now)", file=sys.stderr) + if not errors: + print("[rocm-overlay] drift OK") + return report("drift", errors) + + +# -------------------------------------------------------------------------- +# sync + + +def copy_overlay(src: Path, dst: Path) -> None: + if dst.exists(): + raise ToolError(f"{dst} already exists") + shutil.copytree(src, dst) + + +def cmd_sync(args: argparse.Namespace) -> int: + ctx = make_context(args, need_git=True) + git = ctx.git + assert git is not None + up = ctx.overlay.upstream() + ensure_recorded_commits(ctx, up) + f1, b1, pin = up["commit"], up["fork_upstream_merge_base"], up["retargeted_to_mlx_pin"] + + if args.fork_commit: + if SHA_RE.match(args.fork_commit): + git.ensure_commit(args.fork_commit, "fork") + f2 = args.fork_commit + else: + git.fetch("fork", f"+refs/heads/{args.fork_commit}:refs/remotes/fork/{args.fork_commit}") + f2 = git.resolve(f"refs/remotes/fork/{args.fork_commit}") + else: + branch = up.get("branch", DEFAULT_FORK_BRANCH) + if git.fetch_enabled: + git.fetch("fork", f"+refs/heads/{branch}:refs/remotes/fork/{branch}") + f2 = git.resolve(f"refs/remotes/fork/{branch}") + + if args.fork_merge_base: + b2 = args.fork_merge_base + git.ensure_commit(b2, "upstream") + elif f2 == f1: + b2 = b1 + else: + if git.fetch_enabled: + git.fetch("upstream", f"+refs/heads/{DEFAULT_MLX_BRANCH}:refs/remotes/upstream/{DEFAULT_MLX_BRANCH}") + b2 = git.merge_base(f2, f"refs/remotes/upstream/{DEFAULT_MLX_BRANCH}") + if not git.is_ancestor(b2, pin) and not args.allow_fork_ahead: + raise ToolError( + f"the fork at {f2[:8]} has merged upstream MLX up to {b2[:8]}, which the pin {pin[:8]} does not contain. " + "Bump the MLX pin to include it first (retarget), or pass --allow-fork-ahead to merge anyway." + ) + + if args.check: + tmp = Path(tempfile.mkdtemp(prefix="mlxcelverse-sync-")) + out_root = tmp / "patches-rocm" + elif args.out: + out_root = Path(args.out).resolve() + else: + out_root = ctx.overlay.root + if out_root != ctx.overlay.root: + copy_overlay(ctx.overlay.root, out_root) + out = Overlay(out_root) + conflicts: list[str] = [] + notes: list[str] = [] + changed: list[str] = [] + + def write(rel: str, data: bytes) -> None: + dest = out.root / rel + if dest.is_file() and dest.read_bytes() == data: + return + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + changed.append(rel) + + # Core files: "pin + old fork delta" -> "pin + new fork delta", onto the overlay. + for path in ctx.overlay.core_files(): + old_recon, _ = reconstruct(git, pin, b1, f1, path) + new_recon, _ = reconstruct(git, pin, b2, f2, path) + merged, n = merge3( + ctx.overlay.read(path), old_recon, new_recon, ("overlay", "pin+fork-old", "pin+fork-new") + ) + write(path, merged) + if n: + conflicts.append(f"{path}: {n} conflict(s) (core file)") + if git.show(f2, path) == git.show(b2, path): + notes.append(f"{path}: the new fork commit no longer changes this core file; check whether the overlay still needs it") + + # Backend files. + old_fork = set(git.ls_tree(f1, BACKEND_PREFIX)) + new_fork = set(git.ls_tree(f2, BACKEND_PREFIX)) + ours = set(ctx.overlay.backend_files()) + for path in sorted(ours | old_fork | new_fork): + in_ours, in_old, in_new = path in ours, path in old_fork, path in new_fork + if in_ours and in_old and in_new: + ob, nb = git.show(f1, path), git.show(f2, path) + if ob != nb: + merged, n = merge3(ctx.overlay.read(path), ob or b"", nb or b"", ("overlay", "fork-old", "fork-new")) + write(path, merged) + if n: + conflicts.append(f"{path}: {n} conflict(s)") + elif in_ours and in_old and not in_new: + if ctx.overlay.read(path) == git.show(f1, path): + (out.root / path).unlink() + changed.append(path) + else: + conflicts.append(f"{path}: the fork deleted it but the overlay changes it; kept, decide by hand") + elif in_ours and not in_old and in_new: + nb = git.show(f2, path) or b"" + if nb != ctx.overlay.read(path): + merged, n = merge3(ctx.overlay.read(path), b"", nb, ("overlay", "none", "fork-new")) + write(path, merged) + conflicts.append(f"{path}: the fork now has a file the overlay carries locally; merged with conflict markers ({n})") + elif not in_ours and in_old: + if in_new and git.show(f1, path) != git.show(f2, path): + notes.append(f"{path}: dropped locally, but the fork changed it; check the drop still holds") + elif not in_ours and not in_old and in_new: + write(path, git.show(f2, path) or b"") + notes.append(f"{path}: new in the fork, added") + + # Fork hooks outside the overlay. + core = set(ctx.overlay.core_files()) + def hooks(b: str, f: str) -> set[str]: + return { + p + for p in git.changed_paths(b, f) + if (p.startswith("mlx/") or p == "CMakeLists.txt") and not p.startswith(BACKEND_PREFIX) and p not in core + } + for path in sorted(hooks(b2, f2) - hooks(b1, f1)): + notes.append(f"{path}: the new fork commit changes this MLX file, which the overlay does not carry; decide whether it becomes a core overlay") + + upstream_path = out.root / "UPSTREAM" + new_up = update_upstream(upstream_path.read_text(), {"commit": f2, "fork_upstream_merge_base": b2}) + if new_up != upstream_path.read_text(): + upstream_path.write_text(new_up) + changed.append("UPSTREAM") + + for n in notes: + print(f"[rocm-overlay] sync note: {n}") + for c in conflicts: + print(f"[rocm-overlay] sync CONFLICT: {c}", file=sys.stderr) + + if args.check: + diffs = compare_trees(ctx.overlay.root, out.root) + shutil.rmtree(out.root.parent) + if diffs: + for d in diffs: + print(f"[rocm-overlay] sync --check: {d}", file=sys.stderr) + return 1 + print(f"[rocm-overlay] sync --check OK: syncing to {f2[:8]} reproduces the committed overlay byte for byte") + return 0 + + print(f"[rocm-overlay] synced {out.root} to fork {f2[:8]} (merge base {b2[:8]}): {len(changed)} files changed, {len(conflicts)} conflicts") + if changed and f2 != f1: + print("[rocm-overlay] next: resolve conflicts, build with --features rocm (check_api_drift.sh), run `drift`, record the sync in LOCAL_FIXES.md") + return 1 if conflicts else 0 + + +def compare_trees(a: Path, b: Path) -> list[str]: + diffs = [] + fa = {p.relative_to(a).as_posix() for p in a.rglob("*") if p.is_file()} + fb = {p.relative_to(b).as_posix() for p in b.rglob("*") if p.is_file()} + for rel in sorted(fa - fb): + diffs.append(f"{rel}: missing after sync") + for rel in sorted(fb - fa): + diffs.append(f"{rel}: added by sync") + for rel in sorted(fa & fb): + if (a / rel).read_bytes() != (b / rel).read_bytes(): + diffs.append(f"{rel}: content differs after sync") + return diffs + + +# -------------------------------------------------------------------------- +# retarget + + +def cmd_retarget(args: argparse.Namespace) -> int: + ctx = make_context(args, need_git=True) + git = ctx.git + assert git is not None + up = ctx.overlay.upstream() + old_pin = up["retargeted_to_mlx_pin"] + new_pin = args.to or pinned_commit() + if not SHA_RE.match(new_pin): + raise ToolError(f"--to must be a full commit SHA, got {new_pin!r}") + if new_pin == old_pin: + print(f"[rocm-overlay] already retargeted to {new_pin[:8]}") + return 0 + git.ensure_commit(old_pin, "upstream") + git.ensure_commit(new_pin, "upstream") + if not git.is_ancestor(old_pin, new_pin): + print(f"[rocm-overlay] warning: {old_pin[:8]} is not an ancestor of {new_pin[:8]}; merging anyway", file=sys.stderr) + conflicts = [] + for path in ctx.overlay.core_files(): + ob, nb = git.show(old_pin, path), git.show(new_pin, path) + if nb is None: + conflicts.append(f"{path}: not in MLX at {new_pin[:8]} (moved or removed upstream); resolve by hand") + continue + merged, n = merge3(ctx.overlay.read(path), ob or b"", nb, ("overlay", "old-pin", "new-pin")) + (ctx.overlay.root / path).write_bytes(merged) + if n: + conflicts.append(f"{path}: {n} conflict(s)") + elif ob != nb: + print(f" merged {path}") + upstream_path = ctx.overlay.root / "UPSTREAM" + upstream_path.write_text(update_upstream(upstream_path.read_text(), {"retargeted_to_mlx_pin": new_pin})) + for c in conflicts: + print(f"[rocm-overlay] retarget CONFLICT: {c}", file=sys.stderr) + print( + f"[rocm-overlay] retargeted the core files from {old_pin[:8]} to {new_pin[:8]}. Next: resolve conflicts, " + "run check_api_drift.sh (or build with --features rocm), fix the backend, run `drift`, and record every fix in LOCAL_FIXES.md" + ) + return 1 if conflicts else 0 + + +# -------------------------------------------------------------------------- +# export-tree and api-report (check_api_drift.sh) + + +def cmd_export_tree(args: argparse.Namespace) -> int: + ctx = make_context(args, need_git=True) + git = ctx.git + assert git is not None + commit = args.mlx_commit or pinned_commit() + git.ensure_commit(commit, "upstream") + dest = Path(args.dest).resolve() + if dest.exists(): + raise ToolError(f"{dest} already exists") + dest.mkdir(parents=True) + archive = git.run("archive", "--format=tar", commit).stdout + subprocess.run(["tar", "-x", "-C", str(dest)], input=archive, check=True) + core = ctx.overlay.core_files() + for rel in core: + target = dest / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(ctx.overlay.read(rel)) + if args.rocm_from == "overlay": + backend_src = "overlay" + for rel in ctx.overlay.backend_files(): + target = dest / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(ctx.overlay.read(rel)) + elif args.rocm_from.startswith("fork:"): + fork = args.rocm_from[len("fork:"):] + git.ensure_commit(fork, "fork") + backend_src = f"fork {fork[:8]}" + for rel in git.ls_tree(fork, BACKEND_PREFIX): + target = dest / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(git.show(fork, rel) or b"") + else: + raise ToolError("--rocm-from must be `overlay` or `fork:`") + print(f"[rocm-overlay] exported MLX {commit[:8]} + {len(core)} core overlay files + backend from {backend_src} to {dest}") + return 0 + + +NM_RE = re.compile(r"^\s*(?:[0-9a-fA-F]+\s+)?[A-Za-z?]\s+(\S.*)$") +ERROR_RE = re.compile(r"^(?P[^\s:][^:]*:\d+(?::\d+)?): (?:fatal )?error: (?P.*)$") + + +def cmd_api_report(args: argparse.Namespace) -> int: + log = Path(args.build_log).read_text(errors="replace") + src = args.source_dir.rstrip("/") + "/" if args.source_dir else "" + errors = [] + seen = set() + for line in log.splitlines(): + m = ERROR_RE.match(line.strip()) + if not m: + continue + loc = m.group("loc") + if src and loc.startswith(src): + loc = loc[len(src):] + key = (loc, m.group("msg")) + if key not in seen: + seen.add(key) + errors.append(f"{loc}: {m.group('msg')}") + defined: set[str] = set() + undefined: set[str] = set() + for path, bucket in ((args.defined, defined), (args.undefined, undefined)): + if not path: + continue + for line in Path(path).read_text(errors="replace").splitlines(): + # `nm -C` lines: " " or " U "; + # per-file headers ("foo.o:") and blank lines do not match. + m = NM_RE.match(line) + if m: + bucket.add(m.group(1)) + missing = sorted(n for n in undefined - defined if "mlx::core::" in n) + out = [f"compile errors: {len(errors)}"] + out += [f" {e}" for e in errors] + out.append(f"undefined mlx::core symbols: {len(missing)}") + out += [f" {n}" for n in missing] + if errors and missing: + out.append(" (symbols defined in a file that failed to compile show up here too; fix compile errors first)") + report_text = "\n".join(out) + "\n" + sys.stdout.write(report_text) + if args.output: + Path(args.output).write_text(report_text) + return 1 if errors or missing else 0 + + +# -------------------------------------------------------------------------- +# CLI + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--overlay-dir", default=str(DEFAULT_OVERLAY), help="the ROCm overlay (default: %(default)s)") + sub = parser.add_subparsers(dest="cmd", required=True) + + def git_options(p: argparse.ArgumentParser) -> None: + p.add_argument("--git-dir", help="git cache holding fork and MLX objects (default: $MLXCELVERSE_GIT_DIR or ~/.cache/mlxcel/mlxcelverse/mlx.git)") + p.add_argument("--no-fetch", action="store_true", help="never touch the network; fail if an object is missing") + p.add_argument("--fork-url", default=DEFAULT_FORK_URL) + p.add_argument("--mlx-url", default=DEFAULT_MLX_URL) + + p = sub.add_parser("records", help="offline consistency check of the overlay records") + p.add_argument("--pin", help="MLX pin to compare against (default: scripts/ci/mlx_pinned_commit.sh)") + p.set_defaults(func=cmd_records) + + p = sub.add_parser("drift", help="compare the overlay with pin + fork delta; check the residual record") + git_options(p) + p.add_argument("--write", action="store_true", help=f"rewrite {RESIDUAL_FILE} (keeps notes)") + p.add_argument("--show", action="store_true", help="print the whole residual") + p.set_defaults(func=cmd_drift) + + p = sub.add_parser("sync", help="move the overlay to a new fork commit") + git_options(p) + p.add_argument("--fork-commit", help="fork commit SHA or branch (default: the UPSTREAM branch head)") + p.add_argument("--fork-merge-base", help="the new fork commit's merge base with upstream MLX (default: computed)") + p.add_argument("--allow-fork-ahead", action="store_true", help="merge even if the fork has merged MLX newer than the pin") + g = p.add_mutually_exclusive_group() + g.add_argument("--out", help="write the synced overlay to this new directory instead of in place") + g.add_argument("--check", action="store_true", help="sync into a scratch copy and require it to equal the committed overlay") + p.set_defaults(func=cmd_sync) + + p = sub.add_parser("retarget", help="3-way merge the core files onto a new MLX pin") + git_options(p) + p.add_argument("--to", help="new MLX pin (default: the build's pin from mlx_pinned_commit.sh)") + p.set_defaults(func=cmd_retarget) + + p = sub.add_parser("export-tree", help="write MLX at a commit with the ROCm files over it") + git_options(p) + p.add_argument("--mlx-commit", help="MLX commit (default: the build's pin)") + p.add_argument("--rocm-from", default="overlay", help="`overlay` (default) or `fork:` for the backend directory") + p.add_argument("--dest", required=True) + p.set_defaults(func=cmd_export_tree) + + p = sub.add_parser("api-report", help="summarize a build log and nm output") + p.add_argument("--build-log", required=True) + p.add_argument("--defined", help="`nm -C --defined-only` output") + p.add_argument("--undefined", help="`nm -C --undefined-only` output") + p.add_argument("--source-dir", help="prefix to strip from error locations") + p.add_argument("--output", help="also write the report here") + p.set_defaults(func=cmd_api_report) + + args = parser.parse_args(argv) + try: + return args.func(args) + except ToolError as e: + print(f"[rocm-overlay] error: {e}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mlxcelverse/rocm_overlay_test.sh b/scripts/mlxcelverse/rocm_overlay_test.sh new file mode 100755 index 000000000..713607fe0 --- /dev/null +++ b/scripts/mlxcelverse/rocm_overlay_test.sh @@ -0,0 +1,240 @@ +#!/usr/bin/env bash +# Offline coverage for scripts/mlxcelverse/rocm_overlay.py (issue #1813). +# +# Builds a small synthetic world in a temporary directory: one git repository +# holding an "upstream" history (merge base B1, pins P1 and P2) and a "fork" +# history (F1 and variants), plus an overlay directory laid out like +# src/lib/mlx-cpp/patches-rocm/. Then it checks that each subcommand accepts +# the good cases and rejects the bad ones, including the review risk #1813 is +# about: an overlay core file that quietly drops part of an upstream change is +# reported even though its +/- line counts look plausible. Needs git, bash and +# python3; no network, no build. Runs in a few seconds. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +tool="$here/rocm_overlay.py" +tmp="$(mktemp -d -t mlxcelverse-test.XXXXXX)" +trap 'rm -rf "$tmp"' EXIT + +pass=0 +fail() { echo "FAIL: $*" >&2; exit 1; } +ok() { pass=$((pass + 1)); } + +# expect -- command... +expect() { + local want="$1" pattern="$2" + shift 3 + local out rc=0 + out="$("$@" 2>&1)" || rc=$? + if [ "$rc" -ne "$want" ]; then + echo "$out" >&2 + fail "expected exit $want, got $rc: $*" + fi + if [ -n "$pattern" ] && ! grep -q -- "$pattern" <<<"$out"; then + echo "$out" >&2 + fail "output of '$*' lacks: $pattern" + fi + ok +} + +# subst : in-place multiline substitution. Not +# `sed -i`, whose syntax differs between GNU and BSD sed (this runs in +# `make verify` on macOS too); fails when the pattern does not match. +subst() { + python3 - "$@" <<'PY' +import re, sys +path, pattern, repl = sys.argv[1:4] +with open(path) as f: + content = f.read() +if not re.search(pattern, content, flags=re.M): + sys.exit(f"subst: no match for {pattern!r} in {path}") +with open(path, "w") as f: + f.write(re.sub(pattern, repl, content, flags=re.M)) +PY +} + +export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@example.com GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@example.com +export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null + +repo="$tmp/mlx" +git init -q -b main "$repo" +g() { git -C "$repo" "$@"; } +lines() { for i in $(seq 1 "$1"); do echo "$2 line $i"; done; } +commit() { g add -A && g commit -q -m "$1" && g rev-parse HEAD; } + +# ---- upstream: B1, P1, P2 -------------------------------------------------- +mkdir -p "$repo/mlx" "$repo/python" +lines 30 core >"$repo/mlx/core.cpp" +lines 10 util >"$repo/mlx/util.cpp" +lines 5 cmake >"$repo/CMakeLists.txt" +echo "py" >"$repo/python/x.py" +B1="$(commit B1)" +subst "$repo/mlx/core.cpp" '^core line 25$' 'core line 25 upstream change 1' +P1="$(commit P1)" +subst "$repo/mlx/core.cpp" '^core line 28$' 'core line 28 upstream change 2' +P2="$(commit P2)" +g update-ref refs/remotes/upstream/main "$P2" + +# ---- fork F1 from B1 ------------------------------------------------------ +g checkout -q -b fork "$B1" +subst "$repo/mlx/core.cpp" '^core line 5$' 'core line 5\n#ifdef MLX_USE_ROCM\nrocm hook\n#endif' +subst "$repo/CMakeLists.txt" '^cmake line 2$' 'cmake line 2\noption(MLX_BUILD_ROCM)' +mkdir -p "$repo/mlx/backend/rocm" "$repo/mlx/backend/metal" +lines 20 a >"$repo/mlx/backend/rocm/a.hip" +lines 20 b >"$repo/mlx/backend/rocm/b.hip" +echo "metal custom kernel, fork variant" >"$repo/mlx/backend/metal/custom.cpp" +echo "rocm bindings" >"$repo/python/rocm.py" +F1="$(commit F1)" + +# F2: fork changes that do not collide with the local fixes. +subst "$repo/mlx/backend/rocm/a.hip" '^a line 15$' 'a line 15 fork change' +subst "$repo/mlx/backend/rocm/b.hip" '^b line 10$' 'b line 10 fork change' +lines 5 d >"$repo/mlx/backend/rocm/d.hip" +subst "$repo/mlx/core.cpp" '^rocm hook$' 'rocm hook v2' +F2="$(commit F2)" + +# F3: the fork rewrites the line a local fix changed. +g checkout -q -b fork3 "$F1" +subst "$repo/mlx/backend/rocm/a.hip" '^a line 3$' 'a line 3 fork rewrite' +F3="$(commit F3)" + +# F4: the fork merges upstream past the pin (P2 while the pin is P1). +g checkout -q -b fork4 "$F1" +g merge -q --no-edit "$P2" >/dev/null +F4="$(g rev-parse HEAD)" +g checkout -q main + +# ---- the overlay as committed at pin P1, fork F1 ---------------------------- +ov="$tmp/overlay" +mkdir -p "$ov/mlx/backend/rocm" +# pin + fork delta, the same 3-way merge the tool reconstructs with. +merge_onto_pin() { + g show "$P1:$1" >"$ov/$1" + g show "$B1:$1" >"$tmp/base" + g show "$F1:$1" >"$tmp/fork" + git merge-file -q "$ov/$1" "$tmp/base" "$tmp/fork" || fail "merging $1" +} +merge_onto_pin CMakeLists.txt +merge_onto_pin mlx/core.cpp +subst "$ov/mlx/core.cpp" '^core line 15$' 'core line 15 local fix' +g show "$F1:mlx/backend/rocm/a.hip" >"$ov/mlx/backend/rocm/a.hip" +subst "$ov/mlx/backend/rocm/a.hip" '^a line 3$' 'a line 3 local fix' +g show "$F1:mlx/backend/rocm/b.hip" >"$ov/mlx/backend/rocm/b.hip" +lines 4 c >"$ov/mlx/backend/rocm/c.hip" +cat >"$ov/UPSTREAM" <"$ov/README.md" <<'EOF' +- `mlx/backend/rocm/**`: the ROCm backend (3 files). +- 2 MLX core files (`CMakeLists.txt`, `mlx/core.cpp`). +EOF +cat >"$ov/LOCAL_FIXES.md" <<'EOF' +1. **Local core fix.** `mlx/core.cpp` line 15. +2. **Local kernel fix.** `a.hip` line 3. +3. **Local-only kernel.** `c.hip`. + +- `mlx/backend/metal/custom.cpp` from the fork is not carried. +EOF + +cmake_file() { + cat >"$1" </dev/null || true)" +grep -q '^+-core line 25 upstream change 1$' <<<"$drift_out" || fail "drift did not show the dropped upstream line" +ok + +# ---- a backend change LOCAL_FIXES.md does not name ------------------------------ +u="$(fresh unnamed)" +subst "$u/mlx/backend/rocm/b.hip" '^b line 2$' 'b line 2 unrecorded' +expect 1 "mlx/backend/rocm/b.hip differs from the fork" -- tg "$u" drift + +# ---- records negatives ---------------------------------------------------------- +n="$(fresh numbering)" +subst "$n/LOCAL_FIXES.md" '^3\. \*\*' '4. **' +expect 1 "numbered" -- t "$n" records +c="$(fresh count)" +subst "$c/README.md" '\(3 files\)' '(106 files)' +expect 1 "says the backend has 106 files" -- t "$c" records +s="$(fresh stray)" +echo x >"$s/NOTES.txt" +expect 1 "not a record" -- t "$s" records + +# ---- api-report ----------------------------------------------------------------- +cat >"$tmp/build.log" < const&, mlx::core::array&)\n' >"$tmp/defined.txt" +printf ' U mlx::core::Add::eval_gpu(std::vector const&, mlx::core::array&)\n U mlx::core::SearchSorted::eval_gpu(std::vector const&, mlx::core::array&)\n U hipMalloc\n' >"$tmp/undefined.txt" +expect 1 "compile errors: 1" -- t "$ov" api-report --build-log "$tmp/build.log" --defined "$tmp/defined.txt" --undefined "$tmp/undefined.txt" --source-dir "$tmp/src" +report_out="$(t "$ov" api-report --build-log "$tmp/build.log" --defined "$tmp/defined.txt" --undefined "$tmp/undefined.txt" --source-dir "$tmp/src" || true)" +grep -q '^ mlx::core::SearchSorted::eval_gpu' <<<"$report_out" || fail "api-report missed the undefined eval_gpu" +grep -q '^ mlx/backend/rocm/compiled.cpp:120:8: cannot decompose' <<<"$report_out" || fail "api-report did not relativize or dedupe the error" +if grep -q 'Add::eval_gpu\|hipMalloc' <<<"$report_out"; then fail "api-report listed a defined or non-MLX symbol"; fi +ok +: >"$tmp/clean.log" +expect 0 "undefined mlx::core symbols: 0" -- t "$ov" api-report --build-log "$tmp/clean.log" --defined "$tmp/defined.txt" --undefined "$tmp/defined.txt" + +echo "rocm_overlay_test: OK ($pass checks)" diff --git a/scripts/mlxcelverse/sync_from_fork.sh b/scripts/mlxcelverse/sync_from_fork.sh new file mode 100755 index 000000000..35df3169d --- /dev/null +++ b/scripts/mlxcelverse/sync_from_fork.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Sync the mlxcelverse ROCm overlay to a NripeshN/mlx rocm-support commit +# (issue #1813). +# +# Usage: +# scripts/mlxcelverse/sync_from_fork.sh [] [options] +# +# With no commit the head of the branch recorded in patches-rocm/UPSTREAM is +# used. Options are those of `rocm_overlay.py sync`, most usefully: +# --check sync into a scratch copy and require it to equal the +# committed overlay byte for byte (no change is written) +# --out DIR write the synced overlay to DIR instead of in place +# --no-fetch use only objects already in the git cache +# --git-dir DIR git cache (default ~/.cache/mlxcel/mlxcelverse/mlx.git) +# +# What it does: backend files are 3-way merged (old fork commit, overlay, new +# fork commit), so every local fix in LOCAL_FIXES.md is carried as the +# difference between the overlay and the old fork commit, and local-only files +# such as hadamard.hip and fft.hip are kept. Each MLX core file is 3-way merged +# from "pin + old fork delta" to "pin + new fork delta", which is the fork's +# change to that file against its own merge base, applied on the pin. UPSTREAM +# is updated; conflicts are left in the files with markers and make the exit +# status 1. The full procedure is docs/mlxcelverse/rocm-overlay.md. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +if [ $# -gt 0 ] && [ "${1#-}" = "$1" ]; then + commit="$1" + shift + set -- --fork-commit "$commit" "$@" +fi +exec python3 "$here/rocm_overlay.py" sync "$@" diff --git a/src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff b/src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff new file mode 100644 index 000000000..e6e0c38db --- /dev/null +++ b/src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff @@ -0,0 +1,199 @@ +# CORE_RESIDUAL.diff: what the ROCm overlay's MLX core files carry beyond the +# MLX pin plus the fork's own change to each file. +# +# Generated by `scripts/mlxcelverse/rocm_overlay.py drift --write`; do not +# edit the patches by hand. For each core overlay file the tool rebuilds +# "pin + fork delta" (a 3-way merge of the fork commit into the pin, using the +# fork's merge base with upstream as the base; conflict markers stay in) and +# diffs the overlay against it. A file that matches has no entry. Every +# entry needs a `# note :` line naming the LOCAL_FIXES.md item that +# explains it; `drift --write` keeps existing notes. `rocm_overlay.py records` +# (make verify-rocm-overlay) fails when the commits below are not the ones in +# UPSTREAM or a core file's hash no longer matches, so any change to a core +# overlay, a pin bump or a fork sync has to re-run `drift` and review this +# file. That review is the line-by-line comparison a count of +/- lines cannot +# replace: an overlay that silently drops part of an upstream change shows up +# here as a new hunk, even if it was wrong before the bump. +# +# pin: 81ba1c6a0e50a9268b931579c2d4f1158b9aab5a +# fork: 75915908dfe5028335d318b10340313744fd3a8d +# fork_upstream_merge_base: 39886de461d4f014cd60a3a68ad42fd8d776754a +# overlay-sha256: ad95c895c1bf4d10b3fdece59d617b35c8f6135a135edb5a08f91a8a0a9afb30 CMakeLists.txt +# overlay-sha256: 9da8043e8823e13c49faa62af44eb944db516da83d4f204fe3cfcb0424bd2c1f mlx/CMakeLists.txt +# overlay-sha256: c255fb0f18fb597cd7ba1708dcc5799ea26ee8541820dedb8997a279d9257496 mlx/backend/common/buffer_cache.h +# overlay-sha256: 0bc33a435855548b05a5d87e300c5b023b3ef618c728e326a5dbef98232e7fd8 mlx/backend/common/compiled.cpp +# overlay-sha256: d53bb3bc38645526fb877ed079c7a2e112bf8f74395a1887f048548bad2a9302 mlx/backend/common/compiled.h +# overlay-sha256: ccf2ae61f566cde4b740b43d62a37fd6c904838b68f8330666073842f290b0f6 mlx/backend/gpu/primitives.cpp +# overlay-sha256: 744670de21dbd5c74e2cee3afe1d542c2b73c45deee7611765fc9b0dcc99c334 mlx/compile.cpp +# overlay-sha256: 67e68d6e70df6271ed2f54d75957c4762653b6a32fa6c666ea3b014c5d425acd mlx/device.cpp +# overlay-sha256: fb3a1dfce38319f1113732bdd40e070be0886ec48f1a53b26b7377065604deed mlx/fast.cpp +# overlay-sha256: 03638686c779e32639b6887b2ce625e9bda4966f86e6ec757a47045f984361d9 mlx/fast.h +# overlay-sha256: dad142ea136ff6b4c1fd14c5578526f196d0a1724f41495bbed5798ef6c2ff50 mlx/fast_primitives.h +# overlay-sha256: f5fccd165887c2860c04fecf3fcf6073397789081183c2bcaaacad8f8f4d8e9e mlx/io/safetensors.cpp +# overlay-sha256: 029ded214e753db3ead896df34d528200abcf21bd7a6e65d96b1e0f0f5e1c041 mlx/ops.cpp +# overlay-sha256: 221cf283f6e15a1ddc4d11451eb79e930f2567828cf5fff45cb9ff020c6431e5 mlx/primitives.cpp +# overlay-sha256: adb49482ec61de1b26887b851ec499b351387d0d030fb240664ded3d3d04e5cd mlx/stream.cpp +# note mlx/backend/common/compiled.cpp: LOCAL_FIXES.md item 1: resolves the pin/fork conflict, keeping upstream's negative_strides tracking and the fork's constant-input skipping. +# note mlx/backend/gpu/primitives.cpp: LOCAL_FIXES.md item 24: DynamicSliceUpdate copies through copy_gpu (donates only when is_donatable holds) and drops the fork's graph_active() forced donation. +# note mlx/fast_primitives.h: LOCAL_FIXES.md item 1: resolves the pin/fork conflict, keeping upstream's compile_options and the fork's output_input_aliases on fast::CustomKernel. +# note mlx/io/safetensors.cpp: LOCAL_FIXES.md item 1: resolves the pin/fork conflict, keeping upstream's empty-tensor guard (as an early continue) and the fork's ROCm staged_write. + +--- a/mlx/backend/common/compiled.cpp ++++ b/mlx/backend/common/compiled.cpp +@@ -84,17 +84,13 @@ + bool all_row_contig = true; + bool all_col_contig = true; + int non_scalar_inputs = 0; +-<<<<<<< pin + bool negative_strides = false; +- for (const auto& x : inputs) { +-======= + for (size_t i = 0; i < inputs.size(); ++i) { + // Skip constants. + if (is_constant(i)) { + continue; + } + const auto& x = inputs[i]; +->>>>>>> fork + if (is_scalar(x)) { + continue; + } +@@ -181,16 +177,10 @@ + const array& out, + const std::function& is_constant) { + const Shape& shape = out.shape(); +-<<<<<<< pin + auto [contiguous, negative_strides] = +- compiled_check_contiguity(inputs, shape); ++ compiled_check_contiguity(inputs, shape, is_constant); + if (contiguous && !negative_strides) { + return {true, false, shape, {}}; +-======= +- bool contiguous = compiled_check_contiguity(inputs, shape, is_constant); +- if (contiguous) { +- return {true, shape, {}}; +->>>>>>> fork + } + + std::vector strides_vec{out.strides()}; +--- a/mlx/backend/gpu/primitives.cpp ++++ b/mlx/backend/gpu/primitives.cpp +@@ -16,13 +16,6 @@ + #define MLX_PROFILER_RANGE(message) nvtx3::scoped_range r(message) + #else + #define MLX_PROFILER_RANGE(message) +-#endif +- +-#if defined(MLX_USE_ROCM) +-namespace mlx::core::rocm { +-// True from HIP-graph capture start until the captured graph is destroyed. +-bool graph_active(); +-} // namespace mlx::core::rocm + #endif + + namespace mlx::core { +@@ -142,29 +135,14 @@ + return; + } + +- // Donate the input buffer when uniquely owned, else copy. During HIP-graph +- // capture the async pipeline inflates the buffer's use_count, forcing a full +- // copy into a FRESH buffer — the captured graph then reconstructs +- // (frozen capture input + current row) every replay and loses accumulation +- // (e.g. a growing KV cache → frozen/repeated tokens). For a contiguous, +- // fully-materialized buffer the in-place donation is the intended semantics, +- // so force it while a graph is being captured. ++ // Copy or donate the input to the output. copy_gpu donates only when ++ // is_donatable(in, out) holds, which requires the source array itself, not ++ // just its data buffer, to have no other reference (LOCAL_FIXES.md item 24). + auto s = stream(); +- bool can_donate = in.data_shared_ptr() != nullptr && in.flags().contiguous && +- in.data_size() == in.size() && +- (in.data_shared_ptr().use_count() == 1 +-#if defined(MLX_USE_ROCM) +- || mlx::core::rocm::graph_active() +-#endif +- ); +- if (can_donate) { +- out.copy_shared_buffer(in); +- } else { +- auto ctype = in.flags().contiguous && in.size() == in.data_size() +- ? CopyType::Vector +- : CopyType::General; +- copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, s); +- } ++ auto ctype = in.flags().contiguous && in.size() == in.data_size() ++ ? CopyType::Vector ++ : CopyType::General; ++ copy_gpu(in, out, in.data_size() == 1 ? CopyType::Scalar : ctype, s); + + auto out_offset = + compute_dynamic_offset(start_indices, out.strides(), axes_, s); +--- a/mlx/fast_primitives.h ++++ b/mlx/fast_primitives.h +@@ -447,11 +447,8 @@ + std::vector scalar_arguments, + bool is_precompiled, + int shared_memory, +-<<<<<<< pin +- CompileOptions::Data compile_options = {}) +-======= ++ CompileOptions::Data compile_options = {}, + std::vector> output_input_aliases = {}) +->>>>>>> fork + : Primitive(stream), + name_(std::move(name)), + source_(std::move(source)), +@@ -463,11 +460,8 @@ + scalar_arguments_(std::move(scalar_arguments)), + is_precompiled_(is_precompiled), + shared_memory_(shared_memory), +-<<<<<<< pin +- compile_options_(compile_options) {} +-======= ++ compile_options_(compile_options), + output_input_aliases_(std::move(output_input_aliases)) {} +->>>>>>> fork + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { +@@ -504,12 +498,9 @@ + std::vector scalar_arguments_; + bool is_precompiled_; + int shared_memory_; +-<<<<<<< pin + CompileOptions::Data compile_options_; +-======= + // Output index -> input index whose buffer the output reuses in-place. + std::vector> output_input_aliases_; +->>>>>>> fork + }; + + } // namespace mlx::core::fast +--- a/mlx/io/safetensors.cpp ++++ b/mlx/io/safetensors.cpp +@@ -274,13 +274,11 @@ + out_stream->write(reinterpret_cast(&header_len), 8); + out_stream->write(header.c_str(), header_len); + for (auto& [key, arr] : a) { +-<<<<<<< pin + // An empty tensor contributes a zero length span and has no data pointer + // worth asking for. +- if (arr.nbytes() > 0) { +- out_stream->write(arr.data(), arr.nbytes()); +- } +-======= ++ if (arr.nbytes() == 0) { ++ continue; ++ } + #ifdef MLX_ROCM_HOST_STAGE + // On ROCm the array lives in BAR-mapped VRAM: writing straight from + // arr.data() makes the CPU read it uncached at ~30 MB/s. staged_write +@@ -291,7 +289,6 @@ + } + #endif + out_stream->write(arr.data(), arr.nbytes()); +->>>>>>> fork + } + } + diff --git a/src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md b/src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md index 593880974..517760e0a 100644 --- a/src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md +++ b/src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md @@ -2,24 +2,26 @@ Every change this overlay carries on top of the fork commit in `UPSTREAM`, with the reason. Fixes that apply to the fork itself should also be proposed there; retarget-only changes follow the fork when it merges newer MLX. +Name the files an entry touches: `scripts/mlxcelverse/rocm_overlay.py drift` fails for a backend file that differs from the fork but no entry names, and every core-file residual in `CORE_RESIDUAL.diff` carries a note pointing at its entry. Entries that apply to the fork are prepared as pull requests to NripeshN/mlx `rocm-support` under `docs/mlxcelverse/upstream/`, submitted by hand; its README maps entries to packages and records each link once a PR is open. The procedure for pin bumps and fork syncs is `docs/mlxcelverse/rocm-overlay.md`. + ## Retarget onto the MLX pin (81ba1c6a) The fork branched from upstream on 2026-06-26 (`39886de4`). Moving its ROCm code onto the pin needed: 1. **Core file merges.** `mlx/backend/common/compiled.cpp` keeps upstream's `negative_strides` tracking and the fork's constant-input skipping. `mlx/fast_primitives.h` keeps both upstream's `compile_options` and the fork's `output_input_aliases` on `fast::CustomKernel`. `mlx/io/safetensors.cpp` keeps upstream's empty-tensor guard and the fork's ROCm `staged_write`. -2. **`isnan` lookup.** Upstream `a124ac09` (ml-explore/mlx#4291) added a host-only `mlx::core::isnan` template in `mlx/types/complex.h`, which hides the device `isnan` overloads inside the ROCm namespace. The 23 unqualified device-side calls use `::isnan`. +2. **`isnan` lookup.** Upstream `a124ac09` (ml-explore/mlx#4291) added a host-only `mlx::core::isnan` template in `mlx/types/complex.h`, which hides the device `isnan` overloads inside the ROCm namespace. The 23 unqualified device-side calls use `::isnan` (in `device/binary_ops.hpp`, `quantized/convert_fp8.hip`, `reduce/reduce.hpp`, `reduce/reduce_ops.hpp` and `sort.hip`). 3. **Compiled kernels.** `compiled_collapse_contiguous_dims` returns a 4-tuple with `negative_strides`; `mlx/backend/rocm/compiled.cpp` unpacks it and forces the large-index kernel for negative strides, as the CUDA backend does. 4. **Custom kernels.** `mlx/backend/rocm/custom_kernel.cpp` passes an empty `CompileOptions::Data` before the aliases argument. `output_input_aliases_` stays out of `CustomKernel::state()` because `mlx/export.cpp` serializes that tuple and has no encoding for it (the fork's `state()` did not include it either). 5. **SDPA.** `ScaledDotProductAttention::use_fallback` takes upstream's new `force_fused` argument, with the CUDA semantics: throw if fused is forced and no fused kernel applies. 6. **New upstream primitives.** `GatherQQMM`, `SearchSorted` and `fast::CrossEntropy` (with its VJP, using the graph fallback) get `NO_GPU` stubs in `mlx/backend/rocm/primitives.cpp`. -7. **Event errors.** `Event::error()` (ml-explore/mlx#3742) is populated on ROCm since lablup/mlxcel#1804, on the Metal model: each `CommandEncoder` owns an `Error`, and events signaled on a stream point at that stream's `Error` once the stream fails. Measured on gfx1151 with ROCm 7.15 (a probe kernel writing 2^40 bytes past its buffer): the HIP runtime does not abort the process on a queue fault, with or without `HIP_SKIP_ABORT_ON_GPU_ERROR` (the variable made no observable difference, so mlxcel does not set it); it prints the fault and the kernel name to stderr, then every HIP call on every thread returns `hipErrorIllegalAddress` for the rest of the process, `hipDeviceReset` included, and no queued `hipLaunchHostFunc` callback ever runs. That defeated all three of the backend's waits: `HipEvent::wait()` spun while `hipEventQuery` was not `hipSuccess`, `AtomicEvent::wait()` polled a counter that only a host callback lands, and `CommandEncoder::synchronize()` waited on a promise a host callback resolves. `HipEvent::wait()` now ends on any status other than `hipErrorNotReady`; `AtomicEvent` keeps the stream it was signaled from and polls `hipStreamQuery` on it about once a millisecond while waiting; `Worker::commit()` returns the `hipLaunchHostFunc` status and the encoder records a failure; `synchronize()` checks every status and polls the stream while it waits for the handlers. `Event::wait()` calls `check_error()` before and after the wait as Metal and CUDA do, `Event::is_signaled()` reports a failed event as signaled with the error attached (so `array::is_available()` detaches it and throws instead of pending forever), and `Event::wait(Stream)`/`Event::signal(Stream)` go through `scheduler::wait_event`/`signal_event` on CPU streams so the CPU-stream error path is upstream's. Synchronous launch failures: `launch_module_kernel` checks `hipModuleLaunchKernel`, and `gpu::eval` reads the thread's pending HIP error after each `eval_gpu` (kernels launched with `hipLaunchKernelGGL` or `<<<>>>` report a rejected launch no other way) and throws it as that primitive's error; a pending `hipErrorOutOfMemory` is skipped there, because it is what a recovered allocation failure leaves behind (the allocator's cache-release retry and managed fallback, hipBLASLt's workspace fallback) and an unrecovered one has already thrown. Under `MLX_GRAPH_PREFILL_REPLAY=1`, a launch that throws inside `launch_kernel`'s capture ends the capture and falls back to the eager launch, so a now-checked launch failure cannot leave the stream capturing. Destructor-path `hipGraphDestroy`/`hipGraphExecDestroy` calls discard their status explicitly, and `HipHandle::reset()` reports rather than throws, since on a faulted device every destroy fails and a throwing destructor would terminate the process at exit. `MLX_ROCM_GPU_WATCHDOG_SECS` (default off) bounds a single host wait for a kernel that never finishes; it is parsed with `strtol` and must be a whole non-negative integer, otherwise it warns once on stderr and stays off. Not covered: after a queue fault the device is dead for the process and its shutdown may hang, because HIP's teardown waits on the callbacks that never run (measured: the probe process hung at exit whenever a host callback was pending); the process has to be killed and restarted. Applies to the fork; to be proposed there. +7. **Event errors.** `Event::error()` (ml-explore/mlx#3742) is populated on ROCm since lablup/mlxcel#1804, on the Metal model: each `CommandEncoder` owns an `Error`, and events signaled on a stream point at that stream's `Error` once the stream fails. Measured on gfx1151 with ROCm 7.15 (a probe kernel writing 2^40 bytes past its buffer): the HIP runtime does not abort the process on a queue fault, with or without `HIP_SKIP_ABORT_ON_GPU_ERROR` (the variable made no observable difference, so mlxcel does not set it); it prints the fault and the kernel name to stderr, then every HIP call on every thread returns `hipErrorIllegalAddress` for the rest of the process, `hipDeviceReset` included, and no queued `hipLaunchHostFunc` callback ever runs. That defeated all three of the backend's waits: `HipEvent::wait()` spun while `hipEventQuery` was not `hipSuccess`, `AtomicEvent::wait()` polled a counter that only a host callback lands, and `CommandEncoder::synchronize()` waited on a promise a host callback resolves. `HipEvent::wait()` now ends on any status other than `hipErrorNotReady`; `AtomicEvent` keeps the stream it was signaled from and polls `hipStreamQuery` on it about once a millisecond while waiting; `Worker::commit()` returns the `hipLaunchHostFunc` status and the encoder records a failure; `synchronize()` checks every status and polls the stream while it waits for the handlers. `Event::wait()` calls `check_error()` before and after the wait as Metal and CUDA do, `Event::is_signaled()` reports a failed event as signaled with the error attached (so `array::is_available()` detaches it and throws instead of pending forever), and `Event::wait(Stream)`/`Event::signal(Stream)` go through `scheduler::wait_event`/`signal_event` on CPU streams so the CPU-stream error path is upstream's. Synchronous launch failures: `launch_module_kernel` checks `hipModuleLaunchKernel`, and `gpu::eval` reads the thread's pending HIP error after each `eval_gpu` (kernels launched with `hipLaunchKernelGGL` or `<<<>>>` report a rejected launch no other way) and throws it as that primitive's error; a pending `hipErrorOutOfMemory` is skipped there, because it is what a recovered allocation failure leaves behind (the allocator's cache-release retry and managed fallback, hipBLASLt's workspace fallback) and an unrecovered one has already thrown. Under `MLX_GRAPH_PREFILL_REPLAY=1`, a launch that throws inside `launch_kernel`'s capture ends the capture and falls back to the eager launch, so a now-checked launch failure cannot leave the stream capturing. Destructor-path `hipGraphDestroy`/`hipGraphExecDestroy` calls discard their status explicitly, and `HipHandle::reset()` reports rather than throws, since on a faulted device every destroy fails and a throwing destructor would terminate the process at exit. `MLX_ROCM_GPU_WATCHDOG_SECS` (default off) bounds a single host wait for a kernel that never finishes; it is parsed with `strtol` and must be a whole non-negative integer, otherwise it warns once on stderr and stays off. Not covered: after a queue fault the device is dead for the process and its shutdown may hang, because HIP's teardown waits on the callbacks that never run (measured: the probe process hung at exit whenever a host callback was pending); the process has to be killed and restarted. Files under `mlx/backend/rocm/`: `device.cpp`, `device.h`, `eval.cpp`, `event.h`, `event.hip`, `fence.cpp`, `jit_module.h`, `utils.h`, `worker.cpp`, `worker.h`. Applies to the fork; to be proposed there. ## Fixes to the fork's kernels 8. **mxfp4/mxfp8 scale type in qmv dispatch.** `mlx/backend/rocm/quantized/qmm.hip` dispatched every mode with the activation dtype as the scale type, but mxfp4 and mxfp8 store one E8M0 byte per group. The kernels read scales at 2 to 4 times the real stride, which gave NaN and out-of-bounds reads (a GPU memory fault in `qmv_warp_shared_kernel` on the unfixed fork). Non-affine modes now dispatch with `uint8_t` scales. Applies to the fork; to be proposed there. 9. **Expert-batched gather qmv made opt-in.** On `gfx1151` the expert-batched `gather_qmm` path returns wrong results for bf16 activations with sorted rhs indices (relative error above 1.0 against the unsorted path; f32 and f16 are correct). It is only selected for models with at most 64 experts, so it affected their prefill. It now runs only with `MLX_ROCM_GATHER_QMV_EXPERT_BATCHED=1`. Applies to the fork; to be proposed there after a root cause. 10. **mxfp4/mxfp8 in `gather_qmm`.** When a non-affine mode missed the affine-only fast paths in `GatherQMM::eval_gpu`, the generic dispatch instantiated `gather_qmv_kernel` with `AFFINE=true` and a T-typed scale pointer, so fp weights were dequantized with the affine formula (relative error 1.0 to 1e34 for mxfp8). Non-affine modes now launch `gather_qmv_kernel`; other fp group sizes throw. After the fix mxfp8 and mxfp4 `gather_qmm` match a dequantized f32 reference (relative error about 3e-3 for bf16) with sorted and unsorted indices. Applies to the fork; to be proposed there. -11. **`arg_reduce` launch geometry.** For short reduction axes `ArgReduce::eval_gpu` launched one 1024-thread block per output over a 1-D grid. AMD limits each grid dimension to 2^32 - 1 threads, so the launch failed with "invalid configuration argument" past about 4.2M outputs; mxfp4 `quantize` of a 4096x4096 matrix (an argmin over 16.7M elements) hit it. Axes of at most 64 elements now use a 64-thread block, and the grid spills into y. GPU `quantize` in mxfp4 is then bit-identical to the CPU at 4096x4096. Applies to the fork; to be proposed there. +11. **`arg_reduce` launch geometry.** For short reduction axes `ArgReduce::eval_gpu` (`mlx/backend/rocm/arg_reduce.hip`) launched one 1024-thread block per output over a 1-D grid. AMD limits each grid dimension to 2^32 - 1 threads, so the launch failed with "invalid configuration argument" past about 4.2M outputs; mxfp4 `quantize` of a 4096x4096 matrix (an argmin over 16.7M elements) hit it. Axes of at most 64 elements now use a 64-thread block, and the grid spills into y. GPU `quantize` in mxfp4 is then bit-identical to the CPU at 4096x4096. Applies to the fork; to be proposed there. 12. **f16 in the fast `gather_qmm` path.** `GatherQMM::eval_gpu` sent only bf16 activations to `gather_qmv_warp_shared_kernel`; f16 fell through to the generic `gather_qmv_kernel`, which took about 205 ms per call on `gfx1151`. f16 checkpoints such as `mlx-community/Mixtral-8x7B-Instruct-v0.1-4bit` decoded at about 0.1 tok/s, with 99.7% of GPU time in that kernel (rocprofv3). f16 now uses the same warp-shared kernel (the kernel was already templated on the element type), which takes 1.44 ms for a decode-shaped call at Mixtral's expert shape and matches a dequantized f32 reference. Applies to the fork; to be proposed there. 13. **f32 activations in the tiled qmv path.** `QuantizedMatmul::eval_gpu` entered the tiled qmv branch for any activation dtype, launched `qmv_tiled_kernel` only for bf16 and f16, and then returned, so f32 activations produced no kernel launch and the output was whatever the fresh allocation held (relative error from 1.0 up to 1e35 at every tested shape). The branch is now entered only for bf16/f16 and group sizes 32/64/128, so f32 takes the generic qmv dispatch, which matches a dequantized f32 reference (relative error about 1e-7). mlxcel-core's split/fused projection tests use f32 inputs and exposed it. Applies to the fork; to be proposed there. 14. **Scatter wrote every update to the first index.** `Scatter::eval_gpu` passed `upd_post_idx_size` as `int32_t` while `scatter_general_kernel` declares it `int64_t`. `CommandEncoder::add_kernel_node` hands HIP the address of each argument, so the kernel read eight bytes from a four-byte value, got a huge divisor, and computed index element 0 for every update: `z[idx] = v`, `.at[idx].add(...)` and everything built on scatter (`eye`, `identity`, `tri`, `diag`) applied only one update. The size is now `int64_t`, and `add_kernel_node` statically asserts that every argument has the size of its kernel parameter, so this class of mismatch fails to compile (checked by reintroducing the `int32_t`). Applies to the fork; to be proposed there. @@ -28,7 +30,7 @@ The fork branched from upstream on 2026-06-26 (`39886de4`). Moving its ROCm code 17. **Narrow index dtypes in `Gather` and `Scatter`.** Five dispatch sites in `mlx/backend/rocm/indexing.hip` picked the kernel's index type with `int32_t` for int32 and uint32 and `int64_t` for everything else, so int8, uint8, int16, uint16 and bool index arrays reached a kernel that read eight bytes per element from a one or two byte buffer. On ROCm that is an `HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION`: the GPU queue aborts and the process spins instead of failing. mlxcel reaches it with uint8, because the TurboQuant 4-bit codebook lookup is a `take` with uint8 indices, which is why every TurboQuant KV cache test faulted once the `Hadamard` stub was gone. Narrow index arrays are now widened to int32 once before the dispatch. The alternative, giving each of the eight integer dtypes its own instantiation, was implemented and measured first: it is also correct but takes this translation unit from 26 s to 348 s to compile, because the index type multiplies an existing product of twelve value dtypes and five to six index-count branches, so widening was kept at the cost of one copy pass on the paths that are broken today. Upstream does instantiate per index dtype, in both Metal (`backend/metal/indexing.cpp` puts the index dtype in the kernel name and builds the source from a template) and CUDA (`backend/cuda/indexing.cpp` passes it as an NVRTC template argument), but both compile the kernel at runtime and cache it, so the combinations cost nothing at build time. This backend compiles `indexing.hip` ahead of time, so the same strategy is paid by every build. The asymmetry is the compile model, not the strategy, and it is the argument for proposing widening rather than instantiation to the fork. Upstream already uses the same move for the offset type, choosing int32 or int64 by size rather than instantiating every combination. Verified against the CPU stream for int8, uint8, int16, uint16, int32, uint32, int64 and uint64 at four index shapes. Applies to the fork; to be proposed there. 18. **`FFT` implemented through hipFFT.** The fork leaves `FFT` a `NO_GPU` stub, which aborted Kokoro text to speech and the Phi-4-multimodal audio front end, the only two mlxcel paths that reach a device FFT (the other audio front ends use the host-side transform in `src/audio/fft.rs`). `mlx/backend/rocm/fft.hip` ports `mlx/backend/cuda/fft.cu`, with two differences. This hipFFT has no `hipfftXtMakePlanMany` or `hipfftXtExec`, so the typed API is used instead: one `hipfftType` per plan and one exec entry point per transform, which is enough because MLX only asks for float32 and complex64. And hipFFT work cannot be a HIP graph kernel node, so execution goes through `CommandEncoder::launch_kernel`, the same path the rocBLAS and hipBLASLt GEMMs take. The plan cache holds 128 entries, as in the CUDA file (`MLX_ROCM_FFT_CACHE_SIZE` overrides it). It was 8 until lablup/mlxcel#1876: at 16 and above the first plan eviction hung inside `hipfftDestroy`, whose `hipFree` never returned. The cause was not rocFFT or the number of live plans but the order of `hipSetDeviceFlags` against the first HIP queue, fixed in entry 20. Verified against the CPU stream for rfft, irfft, round trips and complex fft at lengths 2, 8, 400, 512, 1024, 1200 and 2048 and batches up to 512, all within 1e-5 relative. Applies to the fork; to be proposed there. 19. **`get_launch_args` removed.** The fork's `mlx/backend/rocm/kernel_utils.hpp` defined `get_launch_args` (a sized overload and an `array` overload) that fixed the block at 256 threads, ignored `shape`, `strides` and `large`, and capped the grid at 65535 blocks, returning that grid with nothing in its name or comment saying the kernel had to be grid-stride. A kernel written one index per thread with an early return past the end would leave every element past 65535 x 256 unwritten, with the output keeping whatever the allocation held (the failure shape of item 13). Upstream CUDA's helper of the same name (`mlx/backend/cuda/kernel_utils.cu` at the pin) does not cap x, takes a `max_block_dim`, and honours `large` through `get_2d_grid_dims`, so a kernel ported from the CUDA backend with its call intact would compile here and inherit the truncation. Nothing called it, in this overlay or in the fork at `75915908`; launch sites compute their own geometry. Most sites that clamp at 65535 blocks launch a grid-stride kernel (`binary.hip`, `unary.hip`, `hadamard.hip`, `sort.hip` among them). `SliceUpdate::eval_gpu`'s reduce-op path in `indexing.hip` was the exception when this item landed: it clamped and launched `slice_update_op_kernel`, which then did at most `NWORK` elements per thread and never read `gridDim`, so an update larger than 65535 x 256 x `NWORK` elements left its tail unapplied. That was the same defect at a real call site; it was fixed separately in item 21, because this item changes no kernel's geometry. Of the three options weighed in lablup/mlxcel#1874 (delete it, rename it to state the grid-stride requirement, or spill the overflow into another grid dimension the way upstream's `get_launch_args_general` spills y into z), deletion was taken: it cannot regress, and the other two keep a helper that only looks like upstream's. Spilling into y would not even make a one-index-per-thread kernel correct unless that kernel also reads `blockIdx.y`, and AMD caps each grid dimension at 2^32 - 1 threads (item 11), so a faithful port of upstream's geometry is not a drop-in either. In place of the definitions the header now declares `template void get_launch_args(Args&&...) = delete;` with a comment giving this reason, so a ported call fails to compile at the explanation rather than as an undeclared name someone might "fix" by restoring the old helper. A fork sync that brings the old definitions back must drop them again. Applies to the fork; to be proposed there. -20. **Blocking-sync flag set before the first HIP queue.** The fork set `hipSetDeviceFlags(hipDeviceScheduleBlockingSync)` in `rocm::device()`, but the allocator runs first: the first unified allocation's host read calls `hipStreamQuery(nullptr)` in `allocator::Buffer::raw_ptr()`, which creates the null stream's queue, and CLR gives that queue non-interrupt completion signals because active wait is still on. After the flag flips, CLR (`HwQueueTracker::ActiveSignal` in `rocvirtual.cpp`) no longer swaps such a signal for an interrupt one when a command needs a completion handler, and ROCr rejects async handlers on non-interrupt signals (`hsa_amd_signal_async_handler() failed to set the handler!` under `AMD_LOG_LEVEL=4`). The marker a device-wide sync enqueues on the null stream then never signals its waiter: `hipFree` hung in `std::condition_variable::wait` below `Device::SyncAllStreams`. rocFFT's plan destroy was the first thing to hit it (entry 18), but any `hipFree` or device-wide sync with pending null-stream work could. `rocm::ensure_device_flags()` in `device.cpp` now sets the flag once per device index, thread-safe and touching only that device, and runs before every path that can create a queue ahead of `rocm::device()`: `unified_malloc`, both branches of `raw_ptr()`, the async-pool free streams in the `RocmAllocator` constructor, `gpu::init()` and `staged_write`'s device sync; `rocm::device()` uses it too. If `hipSetDevice` fails it returns without recording the device, so a later call retries; if `hipSetDeviceFlags` fails it prints one line to stderr naming the device index and the HIP error and does not retry, so a regression of #1876 is visible. With it, `hipSetDeviceFlags` precedes the first `Created SWq` line in the `AMD_LOG_LEVEL=3` log, the 40-shape plan probe completes at plan-cache capacities 16, 32 and 128, and `tests/rocm_fft_plan_cache.rs` guards it (it times out with the ordering reverted). A standalone HIP reproducer without MLX or hipFFT (null-stream touch, then the flag, then `hipMalloc`, sync `hipMemcpy`, a null-stream kernel and `hipFree` in a loop) hangs at its first `hipFree` and completes without the early touch. Measured on gfx1151 with HIP 7.15.26333 and rocFFT 1.0.39 only. Applies to the fork; to be proposed there, and the reproducer is a candidate for a CLR report. +20. **Blocking-sync flag set before the first HIP queue.** The fork set `hipSetDeviceFlags(hipDeviceScheduleBlockingSync)` in `rocm::device()`, but the allocator runs first: the first unified allocation's host read calls `hipStreamQuery(nullptr)` in `allocator::Buffer::raw_ptr()`, which creates the null stream's queue, and CLR gives that queue non-interrupt completion signals because active wait is still on. After the flag flips, CLR (`HwQueueTracker::ActiveSignal` in `rocvirtual.cpp`) no longer swaps such a signal for an interrupt one when a command needs a completion handler, and ROCr rejects async handlers on non-interrupt signals (`hsa_amd_signal_async_handler() failed to set the handler!` under `AMD_LOG_LEVEL=4`). The marker a device-wide sync enqueues on the null stream then never signals its waiter: `hipFree` hung in `std::condition_variable::wait` below `Device::SyncAllStreams`. rocFFT's plan destroy was the first thing to hit it (entry 18), but any `hipFree` or device-wide sync with pending null-stream work could. `rocm::ensure_device_flags()` in `device.cpp` (declared in `device.h`) now sets the flag once per device index, thread-safe and touching only that device, and runs before every path that can create a queue ahead of `rocm::device()`: `unified_malloc`, both branches of `raw_ptr()` and the async-pool free streams in the `RocmAllocator` constructor (all in `allocator.cpp`), `gpu::init()` (`eval.cpp`) and `staged_write`'s device sync (`host_stage.cpp`); `rocm::device()` uses it too. If `hipSetDevice` fails it returns without recording the device, so a later call retries; if `hipSetDeviceFlags` fails it prints one line to stderr naming the device index and the HIP error and does not retry, so a regression of #1876 is visible. With it, `hipSetDeviceFlags` precedes the first `Created SWq` line in the `AMD_LOG_LEVEL=3` log, the 40-shape plan probe completes at plan-cache capacities 16, 32 and 128, and `tests/rocm_fft_plan_cache.rs` guards it (it times out with the ordering reverted). A standalone HIP reproducer without MLX or hipFFT (null-stream touch, then the flag, then `hipMalloc`, sync `hipMemcpy`, a null-stream kernel and `hipFree` in a loop) hangs at its first `hipFree` and completes without the early touch. Measured on gfx1151 with HIP 7.15.26333 and rocFFT 1.0.39 only. Applies to the fork; to be proposed there, and the reproducer is a candidate for a CLR report. 21. **`slice_update_op_kernel` made grid-stride.** `SliceUpdate::eval_gpu`'s reduce-op path (Sum, Prod, Max, Min, as built by `slice_update_add`, `slice_update_prod`, `slice_update_max`, `slice_update_min` and by `SliceUpdate::vjp` for Prod) in `mlx/backend/rocm/indexing.hip` clamps its grid at 65535 blocks of 256 threads, and `slice_update_op_kernel` handled one `NWORK`-element chunk per thread without reading `gridDim`. `NWORK` is 4, 2 or 1 by what divides the collapsed update's innermost dimension, so every element past 65535 x 256 x `NWORK` (16,776,960, 33,553,920 or 67,107,840) kept the input value, with no error. The kernel now loops over chunks with a stride of `gridDim.x * blockDim.x * NWORK`, recomputing the output and update indices at the top of each chunk (through `elem_to_loc` on the non-contiguous branches, as the old prologue did); a chunk starts at a multiple of `NWORK`, which divides the innermost dimension, so it never crosses an innermost row and the per-element stride increments stay valid. The clamp stays, as in `sort.hip` and `hadamard.hip`: removing it alone would only move the cliff, since `num_blocks` is an `int` and AMD caps each grid dimension at 2^32 - 1 threads (item 11). No template instantiation was added (item 17). mlxcel's own model paths use only the None reduce, which goes through `copy_gpu_inplace`; `tests/rocm_slice_update_reduce.rs` reaches the reduce kernel through a test-only bridge function, `slice_update_reduce`, and compares against the CPU stream exactly on int32 data. Measured on gfx1151 with the old kernel: contiguous Sum updates of 16,777,217 (NWORK=1), 33,554,434 (NWORK=2) and 67,108,868 (NWORK=4) elements left exactly the last 257, 514 and 1028 elements unapplied, a scalar-update Sum over 16,777,217 left 257, and a Max through a `[4099, 4097]` update into columns 1..4098 of a `[4099, 4099]` output (strided output, NWORK=1) left 16,643, and so did a Sum through a transposed update of the same shape (strided output and update), each the element count past the grid's reach; below that size every reduce matched. With the fix every case matches the CPU. The test runs the GPU op first on the same source the CPU reference reads afterwards, which also checks item 24. Applies to the fork; to be proposed there (upstreaming candidate, lablup/mlxcel#1813). 22. **`get_2d_grid_dims` with a divisor sized strided scans too large.** `Scan::eval_gpu` sizes the `strided_scan` grid (a scan along any axis but the last) with `get_2d_grid_dims(shape, strides, axis_size * stride)`. The fork's `mlx/backend/rocm/kernel_utils.hpp` carried its own body for that overload, an older form of upstream's that removed a dimension from the divisor only when the dimension divided it whole and never divided the grid by the remainder; upstream's `get_2d_grid_dims_common(shape, strides, divisor)` in `mlx/backend/common/utils.cpp` takes the gcd of each dimension and divides the grid by what is left, and the CUDA backend delegates to it. For `[1, 48, 24, 24]` scanned along axis 2 the old body returned 576 blocks where 48 cover the array, and each extra block read and wrote `axis_size * stride` elements past the end of it. That is the SSD `segsum` of a 48-head Mamba2 layer over a 24-token chunk, so the lablup/mlxcel#1809 correctness matrix found it as an `HSA_STATUS_ERROR_MEMORY_FAULT` in `strided_scan`: the width-8 trace of `granite-4.0-h-tiny-4bit` faulted on the chunk whose context pass was 24 tokens, and `NVIDIA-Nemotron-3-Nano-30B-A3B-4bit` (64 heads) faulted in its width-8 trace on the 16-token context pass (`[1, 64, 16, 16]`: 256 blocks for 64) and in its width-256 trace on the first chunk. Whether a shape is hit depends on how the head count and the chunk length share factors: with 48 heads, chunks of 8 and 16 tokens were sized correctly, which is why granite's width-1 trace and short prompts ran. An overshoot that stays inside mapped memory does not fault; it reads and writes whatever lies past the array. The overload now delegates to `get_2d_grid_dims_common`, as the non-divisor overload beside it already did. `tests/rocm_strided_scan.rs` compares `cumsum` on the GPU with the CPU stream, exactly, on small integers stored as f32, for that shape, for `[64, 96, 32, 32]` (6144 blocks needed, 98304 launched by the old body), and for shapes the old body sized correctly. Applies to the fork; to be proposed there (upstreaming candidate, lablup/mlxcel#1813). 23. **`ScaledDotProductAttention::use_fallback` checks the stream device.** The fork's `mlx/backend/rocm/scaled_dot_product_attention.cpp` decided from the shapes alone whether a fused kernel applies, so a call on a CPU stream with a decode-shaped query (the vector kernel's shape) built the fused `ScaledDotProductAttention` primitive, whose `eval_cpu` throws "NYI". Through the cxx bridge that is `std::terminate`: on a ROCm build, `MLXCEL_DEVICE=cpu mlxcel generate` and `examples/logit_trace` aborted at the first token of any attention model (seen on Qwen3-0.6B-4bit and a Qwen3.5 FP8 block checkpoint while building the CPU reference for lablup/mlxcel#1807). `use_fallback` now returns `true` for any non-GPU stream first, and throws for `force_fused` there, which is what upstream CUDA's `has_fused_kernel` does before its shape checks. `tests/cpu_device_sdpa.rs` runs attention on the CPU device against a host softmax reference. Applies to the fork; to be proposed there. diff --git a/src/lib/mlx-cpp/patches-rocm/README.md b/src/lib/mlx-cpp/patches-rocm/README.md index 9f23cf7ea..9ff8f5ea1 100644 --- a/src/lib/mlx-cpp/patches-rocm/README.md +++ b/src/lib/mlx-cpp/patches-rocm/README.md @@ -6,10 +6,10 @@ mlxcelverse is the name for everything mlxcel builds on top of upstream MLX: per The tree mirrors the MLX source tree. Every file is a whole-file overlay, copied over the fetched MLX checkout by `mlx_apply_source_overlays` in `../CMakeLists.txt`, and only when `MLX_BUILD_ROCM` is on. Metal and CUDA builds never see these files. -- `mlx/backend/rocm/**`: the ROCm backend (106 files). Upstream MLX has no such directory, so these files never conflict with a pin bump; they only need to keep compiling against the API of the pinned commit. +- `mlx/backend/rocm/**`: the ROCm backend (108 files). Upstream MLX has no such directory, so these files never conflict with a pin bump; they only need to keep compiling against the API of the pinned commit. - 15 MLX core files (`CMakeLists.txt`, `mlx/CMakeLists.txt`, `mlx/backend/common/{buffer_cache.h,compiled.cpp,compiled.h}`, `mlx/backend/gpu/primitives.cpp`, `mlx/{compile,device,fast,ops,primitives,stream}.cpp`, `mlx/{fast,fast_primitives}.h`, `mlx/io/safetensors.cpp`): the upstream file at the pinned commit merged with the fork's ROCm hooks, which are mostly `#ifdef MLX_USE_ROCM` blocks. -Files in this directory other than `CMakeLists.txt` and `mlx/` (this README, `UPSTREAM`, `LOCAL_FIXES.md`) are records and are not copied. +Files in this directory other than `CMakeLists.txt` and `mlx/` (this README, `UPSTREAM`, `LOCAL_FIXES.md`, `CORE_RESIDUAL.diff`) are records and are not copied. `CORE_RESIDUAL.diff` is generated by `scripts/mlxcelverse/rocm_overlay.py drift --write`: it is what the core files carry beyond the MLX pin plus the fork's own change to each file, with a note per file naming the `LOCAL_FIXES.md` entry behind it. `make verify-rocm-overlay` (part of `make verify` and `make verify-rocm`) checks that these records agree with the tree and with the MLX pin. ## Where it comes from @@ -17,8 +17,15 @@ The backend is vendored from the `rocm-support` branch of [NripeshN/mlx](https:/ ## On an MLX pin bump -1. For each of the 15 core files, 3-way merge the upstream change into the overlay (`git merge-file overlay old-upstream new-upstream`) and compare the result line by line with the new upstream file. -2. Build with `--features rocm`. Upstream API changes show up as compile errors in `mlx/backend/rocm/`, and new primitives without a ROCm kernel show up as undefined `eval_gpu` symbols at link time; give those a `NO_GPU` stub in `mlx/backend/rocm/primitives.cpp` or an implementation. -3. Record every fix in `LOCAL_FIXES.md` and update `retargeted_to_mlx_pin` in `UPSTREAM`. +The full procedure, and the one for syncing to a newer fork commit, is [docs/mlxcelverse/rocm-overlay.md](../../../../docs/mlxcelverse/rocm-overlay.md). In short: + +1. `python3 scripts/mlxcelverse/rocm_overlay.py retarget` 3-way merges each of the 15 core files onto the new pin (`git merge-file overlay old-upstream new-upstream`) and updates `retargeted_to_mlx_pin` in `UPSTREAM`. +2. `scripts/mlxcelverse/check_api_drift.sh` on an AMD host (or a `--features rocm` build) lists the backend's compile errors against the new API and the primitives without a ROCm `eval_gpu`, which show up only as undefined symbols because `libmlx` is static; give those a `NO_GPU` stub in `mlx/backend/rocm/primitives.cpp` or an implementation. +3. `python3 scripts/mlxcelverse/rocm_overlay.py drift` compares every core file line by line with the new pin plus the fork's own change; review what it reports, then `drift --write`. +4. Record every fix in `LOCAL_FIXES.md`, run `make verify-rocm`, and describe the ROCm part in the PR body. + +## On a fork sync + +`scripts/mlxcelverse/sync_from_fork.sh ` carries the local fixes onto a newer fork commit by 3-way merging each file, keeps `hadamard.hip` and `fft.hip`, and updates `UPSTREAM`; `sync_from_fork.sh --check` against the recorded commit reproduces this directory byte for byte. Fixes that apply to the fork are prepared as pull requests under [docs/mlxcelverse/upstream/](../../../../docs/mlxcelverse/upstream/README.md) and submitted by hand. Removing a file from `mlx/backend/rocm/` here also removes it from a cached MLX checkout on the next configure. Dropping one of the 15 core overlays does not restore the upstream file in a cached checkout, because the cache is keyed only by the pin; clear the `mlxcel-core` build directory (`cargo clean -p mlxcel-core`) after doing that. diff --git a/src/lib/mlx-cpp/patches-rocm/mlx/backend/rocm/rope.hip b/src/lib/mlx-cpp/patches-rocm/mlx/backend/rocm/rope.hip index 86bfd84b2..488a3ee6b 100644 --- a/src/lib/mlx-cpp/patches-rocm/mlx/backend/rocm/rope.hip +++ b/src/lib/mlx-cpp/patches-rocm/mlx/backend/rocm/rope.hip @@ -410,8 +410,8 @@ void RoPE::eval_gpu( // in-place rotate. But if the input is donatable we can rotate the first // dims_ channels IN PLACE and leave the tail untouched — no copy at all, and // `out` simply adopts the input's (possibly strided) layout. Downstream ops - // (SDPA) accept non-contiguous q/k, so this is safe. (Port of - // ml-explore/mlx#3704, "RoPE without copy".) + // (SDPA) accept non-contiguous q/k, so this is safe. (Port of ml-explore/mlx + // PR #3704, "RoPE without copy".) if (dims_ < D) { donated = true; if (in.is_donatable() && in.flags().row_contiguous) { From bd5de65873f9d2eb483aca9b99cc1b41a748ac5b Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:08:15 +0900 Subject: [PATCH 2/7] fix(rocm): stop drift accepting a backend file named only by a tail rocm_overlay.py drift requires every backend file that differs from the fork to be named in LOCAL_FIXES.md, but it accepted the bare file name anywhere, including as the tail of another path. mlx/device.cpp therefore named mlx/backend/rocm/device.cpp, and the top-level CMakeLists.txt named mlx/backend/rocm/CMakeLists.txt, so an unrecorded change to the most often edited backend files passed. A short name now counts only on its own, and a bare file name only when no other overlay file shares it; the current LOCAL_FIXES.md still passes because it names every modified file by path. records and the overlay file walk ignore .DS_Store, which Finder drops into any directory it shows and which would otherwise fail make verify on a Mac as a stray record or an extra core file. The test's negative grep uses -E instead of the GNU-only \| alternation. The procedure doc no longer claims sync --check at the recorded commit can detect an overlay changed outside the procedure: it is an identity by construction, and drift is the check that does. rocm_overlay_test.sh gains the tail-name and .DS_Store cases (27 checks; the tail-name case fails on the previous tool). make verify-rocm-overlay and an offline drift against the recorded commits pass. Refs #1813 --- docs/mlxcelverse/rocm-overlay.md | 2 +- scripts/mlxcelverse/rocm_overlay.py | 32 ++++++++++++++++++------ scripts/mlxcelverse/rocm_overlay_test.sh | 13 +++++++++- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/docs/mlxcelverse/rocm-overlay.md b/docs/mlxcelverse/rocm-overlay.md index 352260209..1f8b893b8 100644 --- a/docs/mlxcelverse/rocm-overlay.md +++ b/docs/mlxcelverse/rocm-overlay.md @@ -63,7 +63,7 @@ The general procedure is "Bumping the MLX upstream pin" in `CONTRIBUTING.md`. Fo 5. Update `LOCAL_FIXES.md` (its title names the fork commit) and `docs/mlxcelverse/upstream/README.md`. 6. `make verify-rocm`, and the same "ROCm overlay" section in the PR body. -`sync_from_fork.sh --check` against the recorded commit reproduces the committed overlay byte for byte; if it does not, the overlay has changed outside the procedure. +`sync_from_fork.sh --check` against the recorded commit reproduces the committed overlay byte for byte. That holds by construction, because the local fixes are carried as the overlay's own difference from the fork rather than replayed from a separate patch list, so it confirms only that a sync to an unchanged fork commit is a no-op; it cannot detect an unrecorded local change. That is `drift`'s job: every backend file that differs from the fork must be named in `LOCAL_FIXES.md`, and every core-file residual must be recorded in `CORE_RESIDUAL.diff`. `--check` without a commit compares against the head of the fork branch and fails once the fork has moved past `UPSTREAM`. ## The "ROCm overlay" section of a bump or sync PR diff --git a/scripts/mlxcelverse/rocm_overlay.py b/scripts/mlxcelverse/rocm_overlay.py index a336cc821..b4215af24 100755 --- a/scripts/mlxcelverse/rocm_overlay.py +++ b/scripts/mlxcelverse/rocm_overlay.py @@ -65,6 +65,11 @@ # Files at the overlay root that are records, never copied into MLX. RECORDS = ("README.md", "UPSTREAM", "LOCAL_FIXES.md", "CORE_RESIDUAL.diff") RESIDUAL_FILE = "CORE_RESIDUAL.diff" +# Files a desktop drops into any directory it shows (Finder on macOS, where +# `make verify` runs). Neither overlay files nor records; CMake copies them +# into the MLX tree harmlessly, so they must not fail the records check or +# count as core files. +IGNORED_NAMES = (".DS_Store",) BACKEND_PREFIX = "mlx/backend/rocm/" UPSTREAM_KEYS = ( "source", @@ -152,7 +157,7 @@ def files(self) -> list[str]: if not p.is_file(): continue rel = p.relative_to(self.root).as_posix() - if rel in RECORDS: + if rel in RECORDS or p.name in IGNORED_NAMES: continue out.append(rel) return out @@ -436,12 +441,25 @@ def ensure_recorded_commits(ctx: Context, up: dict[str, str]) -> None: def local_fixes_mentions(overlay: Overlay, path: str) -> bool: - """True if LOCAL_FIXES.md names `path`, by full path, backend-relative path - or file name (not as part of a longer name).""" + """True if LOCAL_FIXES.md names `path`: by full path, by backend-relative + path when that has a directory (`quantized/qmm.hip`), or by bare file name + when no other overlay file has that name. A short name only counts on its + own, not as the tail of a longer path, so `mlx/device.cpp` does not name + `mlx/backend/rocm/device.cpp` and the top-level `CMakeLists.txt` does not + name `mlx/backend/rocm/CMakeLists.txt`.""" content = (overlay.root / "LOCAL_FIXES.md").read_text() - rel = path[len(BACKEND_PREFIX):] if path.startswith(BACKEND_PREFIX) else path - for candidate in {path, rel, Path(path).name}: - if re.search(rf"(? int: # Stray files at the overlay root are neither copied nor records. for p in sorted(root.iterdir()): name = p.name - if name in RECORDS or name in ("CMakeLists.txt", "mlx"): + if name in RECORDS or name in IGNORED_NAMES or name in ("CMakeLists.txt", "mlx"): continue errors.append( f"{name}: not a record ({', '.join(RECORDS)}) and not an overlay path (CMakeLists.txt, mlx/); " diff --git a/scripts/mlxcelverse/rocm_overlay_test.sh b/scripts/mlxcelverse/rocm_overlay_test.sh index 713607fe0..09173b664 100755 --- a/scripts/mlxcelverse/rocm_overlay_test.sh +++ b/scripts/mlxcelverse/rocm_overlay_test.sh @@ -208,6 +208,17 @@ ok u="$(fresh unnamed)" subst "$u/mlx/backend/rocm/b.hip" '^b line 2$' 'b line 2 unrecorded' expect 1 "mlx/backend/rocm/b.hip differs from the fork" -- tg "$u" drift +# A local-only backend file whose name only appears as the tail of another +# path (`mlx/core.cpp` in LOCAL_FIXES.md) is not named by it. +v="$(fresh tail-name)" +echo "local core helper" >"$v/mlx/backend/rocm/core.cpp" +subst "$v/README.md" '\(3 files\)' '(4 files)' +expect 1 "mlx/backend/rocm/core.cpp differs from the fork" -- tg "$v" drift +# Finder's .DS_Store is neither an overlay file nor a stray record. +d="$(fresh finder)" +echo x >"$d/.DS_Store" +echo x >"$d/mlx/.DS_Store" +expect 0 "records OK" -- t "$d" records # ---- records negatives ---------------------------------------------------------- n="$(fresh numbering)" @@ -232,7 +243,7 @@ expect 1 "compile errors: 1" -- t "$ov" api-report --build-log "$tmp/build.log" report_out="$(t "$ov" api-report --build-log "$tmp/build.log" --defined "$tmp/defined.txt" --undefined "$tmp/undefined.txt" --source-dir "$tmp/src" || true)" grep -q '^ mlx::core::SearchSorted::eval_gpu' <<<"$report_out" || fail "api-report missed the undefined eval_gpu" grep -q '^ mlx/backend/rocm/compiled.cpp:120:8: cannot decompose' <<<"$report_out" || fail "api-report did not relativize or dedupe the error" -if grep -q 'Add::eval_gpu\|hipMalloc' <<<"$report_out"; then fail "api-report listed a defined or non-MLX symbol"; fi +if grep -qE 'Add::eval_gpu|hipMalloc' <<<"$report_out"; then fail "api-report listed a defined or non-MLX symbol"; fi ok : >"$tmp/clean.log" expect 0 "undefined mlx::core symbols: 0" -- t "$ov" api-report --build-log "$tmp/clean.log" --defined "$tmp/defined.txt" --undefined "$tmp/defined.txt" From f668487415292fdf078b939360b9d4ae3ff12ef9 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:09:18 +0900 Subject: [PATCH 3/7] chore(rocm): tidy mlxcelverse review leftovers The overlay CMake comment lists CORE_RESIDUAL.diff among the records, check_api_drift.sh no longer trips set -u on an empty git option array under bash before 4.4, and single-entry package tables say item rather than items. Refs #1813 --- docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md | 2 +- docs/mlxcelverse/upstream/05-hadamard/pr.md | 2 +- .../upstream/06-blocking-sync-before-first-queue/pr.md | 2 +- docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md | 2 +- docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md | 2 +- scripts/mlxcelverse/check_api_drift.sh | 2 +- src/lib/mlx-cpp/CMakeLists.txt | 5 +++-- 7 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md index 1f7a9522c..569d5bcae 100644 --- a/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md +++ b/docs/mlxcelverse/upstream/02-arg-reduce-grid-limit/pr.md @@ -6,7 +6,7 @@ | Patch | [`0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch`](0001-fix-rocm-keep-ArgReduce-s-grid-inside-the-per-dimens.patch), apply with `git am` | | Applies cleanly | yes, to `75915908` | | Depends on | none | -| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 11 | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 11 | | Reproduction | `repro.py` | | Status | ready for manual submission | diff --git a/docs/mlxcelverse/upstream/05-hadamard/pr.md b/docs/mlxcelverse/upstream/05-hadamard/pr.md index 6d73f9baf..942aa5baa 100644 --- a/docs/mlxcelverse/upstream/05-hadamard/pr.md +++ b/docs/mlxcelverse/upstream/05-hadamard/pr.md @@ -6,7 +6,7 @@ | Patch | [`0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch`](0001-feat-rocm-implement-Hadamard-for-power-of-two-sizes-.patch), apply with `git am` | | Applies cleanly | yes, to `75915908` | | Depends on | none (conflicts only textually with the FFT PR in `CMakeLists.txt` and `primitives.cpp`, adjacent lines) | -| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 16 | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 16 | | Reproduction | `repro.py` | | Status | ready for manual submission | diff --git a/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md index a1cb3f49b..7e691f275 100644 --- a/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md +++ b/docs/mlxcelverse/upstream/06-blocking-sync-before-first-queue/pr.md @@ -6,7 +6,7 @@ | Patch | [`0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch`](0001-fix-rocm-set-blocking-sync-before-the-first-HIP-queu.patch), apply with `git am` | | Applies cleanly | yes, to `75915908` | | Depends on | none (the FFT PR depends on this one) | -| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 20 | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 20 | | Reproduction | `repro.hip` (standalone HIP program, no MLX) | | Status | ready for manual submission | diff --git a/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md index 559a68e42..c956104a3 100644 --- a/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md +++ b/docs/mlxcelverse/upstream/09-sdpa-cpu-stream-fallback/pr.md @@ -6,7 +6,7 @@ | Patch | [`0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch`](0001-fix-rocm-fall-back-from-fused-SDPA-on-CPU-streams.patch), apply with `git am` | | Applies cleanly | yes, to `75915908` | | Depends on | none | -| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 23 | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 23 | | Reproduction | `repro.py` | | Status | ready for manual submission | diff --git a/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md b/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md index 9d61e021e..39d85f1b5 100644 --- a/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md +++ b/docs/mlxcelverse/upstream/10-hip-header-dependencies/pr.md @@ -6,7 +6,7 @@ | Patch | [`0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch`](0001-fix-rocm-track-header-dependencies-of-HIP-objects.patch), apply with `git am` | | Applies cleanly | yes, to `75915908` | | Depends on | none | -| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` items 26 | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 26 | | Reproduction | `repro.sh` (needs a configured build directory) | | Status | ready for manual submission | diff --git a/scripts/mlxcelverse/check_api_drift.sh b/scripts/mlxcelverse/check_api_drift.sh index 338de0e90..aef149cc8 100755 --- a/scripts/mlxcelverse/check_api_drift.sh +++ b/scripts/mlxcelverse/check_api_drift.sh @@ -80,7 +80,7 @@ export_args=(export-tree --dest "$src" --rocm-from "$rocm_from") if [ -n "$mlx_commit" ]; then export_args+=(--mlx-commit "$mlx_commit") fi -python3 "$here/rocm_overlay.py" "${export_args[@]}" "${git_args[@]}" +python3 "$here/rocm_overlay.py" "${export_args[@]}" ${git_args[@]+"${git_args[@]}"} echo "[api-drift] configuring (log: $work/configure.log)" if ! cmake -S "$src" -B "$build" -G "Unix Makefiles" \ diff --git a/src/lib/mlx-cpp/CMakeLists.txt b/src/lib/mlx-cpp/CMakeLists.txt index b5163a7f0..cc8881bc6 100644 --- a/src/lib/mlx-cpp/CMakeLists.txt +++ b/src/lib/mlx-cpp/CMakeLists.txt @@ -90,8 +90,9 @@ function(mlx_apply_source_overlays mlx_source_dir) # backend vendored from NripeshN/mlx (mlx/backend/rocm/) plus the MLX core # files it hooks, merged at the pinned commit. Copied only for ROCm builds so # Metal and CUDA never compile a ROCm-modified core file. Only CMakeLists.txt - # and mlx/ are overlays; README.md, UPSTREAM and LOCAL_FIXES.md next to them - # are records. See patches-rocm/README.md for the pin-bump procedure. + # and mlx/ are overlays; README.md, UPSTREAM, LOCAL_FIXES.md and + # CORE_RESIDUAL.diff next to them are records. See patches-rocm/README.md for + # the pin-bump procedure. if(MLX_BUILD_ROCM) set(_rocm_root "${CMAKE_CURRENT_SOURCE_DIR}/patches-rocm") if(NOT EXISTS "${_rocm_root}/mlx/backend/rocm") From 51b142fcaca2c9b5da6e542788b67c6236402cd4 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:12:51 +0900 Subject: [PATCH 4/7] fix(security): confine rocm_overlay writes to their output tree sync and export-tree wrote every path listed by `git ls-tree` on a fetched fork commit as `root / path`. Git stores and lists a `..` tree entry verbatim and a fetch does not fsck by default, so a hostile fork tree (or a --fork-url) could make `sync_from_fork.sh` write or delete an arbitrary file, for example mlx/backend/rocm/../../../../.bashrc. Export-tree also wrote overlay files through whatever symlinks the extracted MLX archive contained. Every write and unlink of a tree-derived path now goes through safe_dest, which rejects absolute paths, empty, `.`, `..` and `.git` components, and any destination that resolves outside the output root. ls_tree and changed_paths use -z so names are read raw instead of C-quoted. rocm_overlay_test.sh builds a fork commit with a `..` entry via mktree and asserts sync and export-tree both refuse it and nothing lands outside the output directory; against the previous tool the file escaped. make verify-rocm-overlay passes (29 checks, about 2 s). --- scripts/mlxcelverse/rocm_overlay.py | 47 +++++++++++++++++++----- scripts/mlxcelverse/rocm_overlay_test.sh | 15 ++++++++ 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/scripts/mlxcelverse/rocm_overlay.py b/scripts/mlxcelverse/rocm_overlay.py index b4215af24..b776ffb9f 100755 --- a/scripts/mlxcelverse/rocm_overlay.py +++ b/scripts/mlxcelverse/rocm_overlay.py @@ -130,6 +130,31 @@ def normalize_patch(patch: str) -> str: return re.sub(r"(?m)^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@", "@@", patch) +def safe_dest(root: Path, rel: str) -> Path: + """`root / rel` for a path read from a git tree, refusing anything that + would land outside `root`. Tree entries come from fetched objects (the fork + or a --fork-url), and git stores and lists a `..` entry verbatim, so a + hostile tree could otherwise make sync or export-tree write, or delete, a + file anywhere the user can. Rejects absolute paths, empty, `.`, `..` and + `.git` components, and a destination that resolves outside `root` through + a symlink already on disk (export-tree extracts MLX, symlinks included).""" + parts = rel.split("/") + if ( + not rel + or rel.startswith("/") + or "\\" in rel + or "\0" in rel + or any(part in ("", ".", "..") or part.lower() == ".git" for part in parts) + ): + raise ToolError(f"refusing unsafe path {rel!r} from a git tree") + dest = root / rel + base = root.resolve() + resolved = dest.resolve() + if resolved != base and base not in resolved.parents: + raise ToolError(f"refusing {rel!r}: it resolves to {resolved}, outside {base}") + return dest + + def patch_stats(patch: str) -> tuple[int, int]: plus = minus = 0 for line in patch.splitlines(): @@ -357,13 +382,15 @@ def show(self, sha: str, path: str) -> bytes | None: return None return proc.stdout + # -z: names come back raw, not C-quoted (core.quotePath quotes non-ASCII + # and control characters), so they can be looked up and validated as is. def ls_tree(self, sha: str, prefix: str) -> list[str]: - out = self.run("ls-tree", "-r", "--name-only", sha, "--", prefix).stdout - return [line for line in text(out).splitlines() if line] + out = self.run("ls-tree", "-r", "-z", "--name-only", sha, "--", prefix).stdout + return [name for name in text(out).split("\0") if name] def changed_paths(self, a: str, b: str) -> list[str]: - out = self.run("diff", "--name-only", "--no-renames", a, b).stdout - return [line for line in text(out).splitlines() if line] + out = self.run("diff", "-z", "--name-only", "--no-renames", a, b).stdout + return [name for name in text(out).split("\0") if name] def is_ancestor(self, a: str, b: str) -> bool: return self.run("merge-base", "--is-ancestor", a, b, check=False).returncode == 0 @@ -759,7 +786,7 @@ def cmd_sync(args: argparse.Namespace) -> int: changed: list[str] = [] def write(rel: str, data: bytes) -> None: - dest = out.root / rel + dest = safe_dest(out.root, rel) if dest.is_file() and dest.read_bytes() == data: return dest.parent.mkdir(parents=True, exist_ok=True) @@ -794,7 +821,7 @@ def write(rel: str, data: bytes) -> None: conflicts.append(f"{path}: {n} conflict(s)") elif in_ours and in_old and not in_new: if ctx.overlay.read(path) == git.show(f1, path): - (out.root / path).unlink() + safe_dest(out.root, path).unlink() changed.append(path) else: conflicts.append(f"{path}: the fork deleted it but the overlay changes it; kept, decide by hand") @@ -890,7 +917,7 @@ def cmd_retarget(args: argparse.Namespace) -> int: conflicts.append(f"{path}: not in MLX at {new_pin[:8]} (moved or removed upstream); resolve by hand") continue merged, n = merge3(ctx.overlay.read(path), ob or b"", nb, ("overlay", "old-pin", "new-pin")) - (ctx.overlay.root / path).write_bytes(merged) + safe_dest(ctx.overlay.root, path).write_bytes(merged) if n: conflicts.append(f"{path}: {n} conflict(s)") elif ob != nb: @@ -924,13 +951,13 @@ def cmd_export_tree(args: argparse.Namespace) -> int: subprocess.run(["tar", "-x", "-C", str(dest)], input=archive, check=True) core = ctx.overlay.core_files() for rel in core: - target = dest / rel + target = safe_dest(dest, rel) target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(ctx.overlay.read(rel)) if args.rocm_from == "overlay": backend_src = "overlay" for rel in ctx.overlay.backend_files(): - target = dest / rel + target = safe_dest(dest, rel) target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(ctx.overlay.read(rel)) elif args.rocm_from.startswith("fork:"): @@ -938,7 +965,7 @@ def cmd_export_tree(args: argparse.Namespace) -> int: git.ensure_commit(fork, "fork") backend_src = f"fork {fork[:8]}" for rel in git.ls_tree(fork, BACKEND_PREFIX): - target = dest / rel + target = safe_dest(dest, rel) target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(git.show(fork, rel) or b"") else: diff --git a/scripts/mlxcelverse/rocm_overlay_test.sh b/scripts/mlxcelverse/rocm_overlay_test.sh index 09173b664..e460cfbd8 100755 --- a/scripts/mlxcelverse/rocm_overlay_test.sh +++ b/scripts/mlxcelverse/rocm_overlay_test.sh @@ -104,6 +104,18 @@ g merge -q --no-edit "$P2" >/dev/null F4="$(g rev-parse HEAD)" g checkout -q main +# F5: a hostile fork tree. Git stores and lists a `..` entry verbatim, so +# mlx/backend/rocm/../../../../escaped would land next to the sync output +# directory. Built with mktree because no index can hold such a path. +evil="$(echo pwned | g hash-object -w --stdin)" +t="$(printf '100644 blob %s\tescaped\n' "$evil" | g mktree)" +for _ in 1 2 3; do t="$(printf '040000 tree %s\t..\n' "$t" | g mktree)"; done +t="$( { g ls-tree "$F1:mlx/backend/rocm"; printf '040000 tree %s\t..\n' "$t"; } | g mktree)" +t="$( { g ls-tree "$F1:mlx/backend" | grep -v ' rocm$'; printf '040000 tree %s\trocm\n' "$t"; } | g mktree)" +t="$( { g ls-tree "$F1:mlx" | grep -v ' backend$'; printf '040000 tree %s\tbackend\n' "$t"; } | g mktree)" +t="$( { g ls-tree "$F1" | grep -v ' mlx$'; printf '040000 tree %s\tmlx\n' "$t"; } | g mktree)" +F5="$(echo F5 | g commit-tree "$t" -p "$F1")" + # ---- the overlay as committed at pin P1, fork F1 ---------------------------- ov="$tmp/overlay" mkdir -p "$ov/mlx/backend/rocm" @@ -183,6 +195,9 @@ grep -q "^commit: $F2$" "$o/UPSTREAM" || fail "sync did not update UPSTREAM" expect 1 "CONFLICT: mlx/backend/rocm/a.hip" -- tg "$ov" sync --fork-commit "$F3" --out "$tmp/sync-f3" grep -q '^<<<<<<< overlay$' "$tmp/sync-f3/mlx/backend/rocm/a.hip" || fail "conflict markers missing" expect 2 "does not contain" -- tg "$ov" sync --fork-commit "$F4" --out "$tmp/sync-f4" +expect 2 "refusing unsafe path" -- tg "$ov" sync --fork-commit "$F5" --out "$tmp/sync-f5" +expect 2 "refusing unsafe path" -- tg "$ov" export-tree --mlx-commit "$P1" --rocm-from "fork:$F5" --dest "$tmp/export-f5" +if [ -n "$(find "$tmp" -name escaped -print -quit)" ]; then fail "a hostile tree path escaped the output directory"; fi # ---- a pin bump --------------------------------------------------------------- MLX_PIN_CMAKE_FILE="$tmp/pin-p2.cmake" expect 1 "A pin bump has to retarget" -- t "$ov" records From 0119aee947765acb733452e9ea7abde2f9ee5960 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:14:05 +0900 Subject: [PATCH 5/7] fix(rocm): refuse option-like fetch arguments in rocm_overlay A commit or ref starting with a dash reached git fetch unchecked and would be parsed as an option such as --upload-pack; it is now rejected. sync --check also removes its scratch copy when the comparison raises. Refs #1813 --- scripts/mlxcelverse/rocm_overlay.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/mlxcelverse/rocm_overlay.py b/scripts/mlxcelverse/rocm_overlay.py index b776ffb9f..24408d1a4 100755 --- a/scripts/mlxcelverse/rocm_overlay.py +++ b/scripts/mlxcelverse/rocm_overlay.py @@ -364,6 +364,11 @@ def has_commit(self, sha: str) -> bool: def fetch(self, remote: str, *refspecs: str) -> None: if not self.fetch_enabled: raise ToolError(f"missing objects and --no-fetch given (wanted {refspecs} from {remote})") + for spec in refspecs: + # A value starting with "-" would be parsed as a git option + # (for example --upload-pack=...), so refuse it outright. + if spec.startswith("-"): + raise ToolError(f"refusing to fetch {spec!r}: not a commit or ref") print(f"fetching {' '.join(refspecs)} from {remote} ...", file=sys.stderr) self.run("fetch", "-q", "--no-tags", remote, *refspecs) @@ -861,8 +866,10 @@ def hooks(b: str, f: str) -> set[str]: print(f"[rocm-overlay] sync CONFLICT: {c}", file=sys.stderr) if args.check: - diffs = compare_trees(ctx.overlay.root, out.root) - shutil.rmtree(out.root.parent) + try: + diffs = compare_trees(ctx.overlay.root, out.root) + finally: + shutil.rmtree(out.root.parent, ignore_errors=True) if diffs: for d in diffs: print(f"[rocm-overlay] sync --check: {d}", file=sys.stderr) From 53c8f1222afe069378faf440627a856b2d886f14 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:49:57 +0900 Subject: [PATCH 6/7] update(rocm): package LOCAL_FIXES item 27 for the fork Item 27 (#2079, CPU-stream OpenBLAS single-threaded over fine-grained memory) replaces the pending slot as package 11: a patch against fork head 75915908 that applies cleanly on its own and after packages 01 to 10, PR notes, and the standalone cblas_sgemm reproducer. The records check now accepts LOCAL_FIXES numbers grouped by section (27 sits in the kernel section above build item 26) as long as each of 1..N appears once. Refs #1813 --- ...-stream-BLAS-single-threaded-over-fi.patch | 62 ++++++++++++++++++ .../upstream/11-cpu-blas-finegrained/pr.md | 41 ++++++++++++ .../upstream/11-cpu-blas-finegrained/repro.c | 63 +++++++++++++++++++ docs/mlxcelverse/upstream/README.md | 8 +-- scripts/mlxcelverse/rocm_overlay.py | 9 ++- 5 files changed, 177 insertions(+), 6 deletions(-) create mode 100644 docs/mlxcelverse/upstream/11-cpu-blas-finegrained/0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch create mode 100644 docs/mlxcelverse/upstream/11-cpu-blas-finegrained/pr.md create mode 100644 docs/mlxcelverse/upstream/11-cpu-blas-finegrained/repro.c diff --git a/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch new file mode 100644 index 000000000..e7bd06c6b --- /dev/null +++ b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch @@ -0,0 +1,62 @@ +From 2218ea125668d430ec9bccf7b86b94eeb7e5bceb Mon Sep 17 00:00:00 2001 +From: Jeongkyu Shin +Date: Wed, 30 Sep 2026 16:48:44 +0900 +Subject: [PATCH] fix(rocm): run CPU-stream BLAS single-threaded over + fine-grained memory + +On an APU unified_malloc gives every array fine-grained device memory, CPU-stream arrays included, and Buffer::raw_ptr() hands the CPU that same pointer, so MLX's CPU backend calls BLAS with its output in fine-grained memory. Multithreaded OpenBLAS (Debian 0.3.29, 32 threads) then returns wrong output columns: each wrong column is the last column of one thread's share, whose 64-byte line the next thread also writes. A CPU-stream matmul(x, w.T) of [1, 2880] x [2880, 2880]^T was wrong in 35 of 60 calls; a standalone cblas_sgemm of that shape was wrong in 37 of 50 calls with inputs and output from hipExtMallocWithFlags(hipDeviceMallocFinegrained), in 10 of 300 with only the output there, and exact with malloc or hipHostMalloc buffers or with 1, 2 or 4 threads. + +The allocator now calls openblas_set_num_threads(1) once, on its first fine-grained allocation. The symbol is declared weak, so a build linked against another BLAS still links and nothing changes there. GPU work and MLX's own CPU kernels (quantized and bf16/f16 matmuls) do not use BLAS; float32 CPU-stream BLAS gets slower (this gemv went from about 0.2 s to 1.4 s per call). Giving BLAS a cacheable scratch output instead would need a change at every BLAS and LAPACK call site in the CPU backend. +--- + mlx/backend/rocm/allocator.cpp | 24 ++++++++++++++++++++++++ + 1 file changed, 24 insertions(+) + +diff --git a/mlx/backend/rocm/allocator.cpp b/mlx/backend/rocm/allocator.cpp +index 4489295f..d49c4cfc 100644 +--- a/mlx/backend/rocm/allocator.cpp ++++ b/mlx/backend/rocm/allocator.cpp +@@ -25,6 +25,10 @@ + #include + #include + ++// OpenBLAS's thread-count setter, weak so a build linked against another BLAS ++// still links (the pointer is then null and nothing changes). ++extern "C" void openblas_set_num_threads(int) __attribute__((weak)); ++ + namespace mlx::core { + + namespace rocm { +@@ -123,6 +127,25 @@ static void ensure_mlx_device_current() { + } + } + ++// The CPU stream's BLAS and LAPACK calls write their results straight into ++// buffers from this allocator. Multithreaded OpenBLAS (0.3.29, 32 threads on ++// the gfx1151 host) returns wrong columns when its output is fine-grained ++// device memory: a standalone cblas_sgemm of [1, 2880] x [2880, 2880]^T was ++// wrong in 37 of 50 calls with inputs and output in fine-grained memory and in ++// 10 of 300 with only the output there, and exact in every call with one ++// thread or with a malloc'd output. One BLAS thread keeps ++// the CPU stream correct; GPU work is unaffected. Runs once, on the first ++// fine-grained allocation, which precedes any CPU-stream BLAS call writing ++// such a buffer. ++inline void single_thread_cpu_blas_for_finegrained() { ++ static std::once_flag once; ++ std::call_once(once, [] { ++ if (openblas_set_num_threads != nullptr) { ++ openblas_set_num_threads(1); ++ } ++ }); ++} ++ + // CUDA unified_malloc: managed if supported else host pinned. + // ROCm discrete training: prefer real VRAM (hipMalloc) so we never spill GTT. + // APU: fine-grained coherent. Managed only as explicit fallback. +@@ -134,6 +157,7 @@ inline void* unified_malloc(size_t size, bool& is_managed) { + if (use_finegrained()) { + err = hipExtMallocWithFlags(&data, size, hipDeviceMallocFinegrained); + if (err == hipSuccess) { ++ single_thread_cpu_blas_for_finegrained(); + is_managed = true; + return data; + } diff --git a/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/pr.md b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/pr.md new file mode 100644 index 000000000..7daf4dfc4 --- /dev/null +++ b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/pr.md @@ -0,0 +1,41 @@ +# fix(rocm): run CPU-stream BLAS single-threaded over fine-grained memory + +| | | +|---|---| +| Target | `NripeshN/mlx`, branch `rocm-support`, head `75915908` (the head on 2026-09-30) | +| Patch | [`0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch`](0001-fix-rocm-run-CPU-stream-BLAS-single-threaded-over-fi.patch), apply with `git am` | +| Applies cleanly | yes, to `75915908` (and on top of packages 01 to 10) | +| Depends on | none | +| mlxcel records | `src/lib/mlx-cpp/patches-rocm/LOCAL_FIXES.md` item 27 | +| Reproduction | `repro.c` (standalone C program, no MLX) | +| Status | ready for manual submission | + +The PR title is the heading above. The PR body is everything below the rule. Read the submission notes in [the index](../README.md) first: the body is a draft for the submitter to check and put in their own words. + +--- + +## Proposed changes + +On an APU, `unified_malloc` in `mlx/backend/rocm/allocator.cpp` gives every array fine-grained device memory, CPU-stream arrays included, and `Buffer::raw_ptr()` hands the CPU that same pointer. MLX's CPU backend therefore calls BLAS with its output in fine-grained memory, and multithreaded OpenBLAS returns wrong output columns there. Each wrong column is the last column of one OpenBLAS thread's share of the output, the column whose 64-byte line the next thread also writes. + +Measured on gfx1151 (Radeon 8060S) with Debian OpenBLAS 0.3.29 at 32 threads: + +- A CPU-stream `matmul(x, w.T)` of [1, 2880] x [2880, 2880]^T was wrong in 35 of 60 calls with the host idle, and correct in 300 of 300 with `OPENBLAS_NUM_THREADS=1`. +- A standalone `cblas_sgemm` of the same shape (`repro.c`) was wrong in 37 of 50 calls with inputs and output from `hipExtMallocWithFlags(hipDeviceMallocFinegrained)`, in 10 of 300 with only the output there, and in none with `malloc` or `hipHostMalloc` buffers or with 1, 2 or 4 threads. + +The allocator now calls `openblas_set_num_threads(1)` once, on its first fine-grained allocation, which comes before any CPU-stream BLAS call that writes such a buffer. The symbol is declared weak, so a build linked against another BLAS still links and nothing changes there. + +Cost: float32 BLAS on the CPU stream gets slower (this gemv went from about 0.2 s to about 1.4 s per call, because the CPU reads fine-grained memory slowly and now does so on one thread). GPU work and MLX's own CPU kernels (quantized matmuls, bf16/f16 matmuls) do not use BLAS. The alternative, giving BLAS a cacheable scratch output, would need a change at every BLAS and LAPACK call site in the CPU backend. Whether other OpenBLAS versions or discrete GPUs (which do not take the fine-grained path) are affected was not checked. + +## Reproduction + +`repro.c` has the build line and the `MODE` settings in its header: `MODE=11` puts inputs and output in fine-grained memory, `MODE=00` uses `malloc`, and `OPENBLAS_NUM_THREADS=1` removes the errors. It shows the OpenBLAS behavior without MLX; with the patch, the same product through MLX on the CPU stream matches a float64 reference on every call. + +## Checklist + +Put an `x` in the boxes that apply. + +- [ ] I have read the [CONTRIBUTING](https://github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document +- [ ] I have run `pre-commit run --all-files` to format my code / installed pre-commit prior to committing changes +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have updated the necessary documentation (if needed) diff --git a/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/repro.c b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/repro.c new file mode 100644 index 000000000..19a0ded7d --- /dev/null +++ b/docs/mlxcelverse/upstream/11-cpu-blas-finegrained/repro.c @@ -0,0 +1,63 @@ +// Reproduction for "fix(rocm): run CPU-stream BLAS single-threaded over +// fine-grained memory". No MLX: cblas_sgemm with M=1 (x[1,K] @ W^T, W [N,K]), +// the shape of an MLX CPU-stream matmul(x, transpose(w)), with its buffers in +// malloc (0), fine-grained device memory (1) or hipHostMalloc (2) memory. +// +// gcc -O2 repro.c -I/opt/rocm/include -D__HIP_PLATFORM_AMD__ \ +// -L/opt/rocm/lib -lamdhip64 -lopenblas -lm -o repro +// MODE=11 ./repro 50 # inputs and output fine-grained: many bad iterations +// MODE=01 ./repro 300 # output fine-grained only: some bad iterations +// MODE=00 ./repro 300 # malloc: 0 bad +// OPENBLAS_NUM_THREADS=1 MODE=11 ./repro 300 # one thread: 0 bad +// +// Seen on gfx1151 (Radeon 8060S APU) with Debian OpenBLAS 0.3.29, 32 threads. +// +// Standalone check: is OpenBLAS cblas_sgemm with M=1 (x[1,K] @ W^T, W [N,K]) +// deterministic on this host? Mirrors MLX CPU matmul(x, transpose(w)). +#include +#include +#include +#include +#include +#include +static void* amalloc(size_t n, int mode){ void* p=0; if(mode==0) return malloc(n); if(mode==1){ if(hipExtMallocWithFlags(&p,n,hipDeviceMallocFinegrained)!=hipSuccess){printf("alloc fail\n");exit(1);} return p;} hipHostMalloc(&p,n,hipHostMallocDefault); return p; } + +int main(int argc, char** argv) { + int iters = argc > 1 ? atoi(argv[1]) : 300; int N = argc > 2 ? atoi(argv[2]) : 2880; int K = argc > 3 ? atoi(argv[3]) : 2880; + const char* e=getenv("MODE"); int in_mode = e? e[0]-'0':0; int out_mode = e? e[1]-'0':0; + float* w = amalloc(sizeof(float) * N * K, in_mode); + float* x = amalloc(sizeof(float) * K, in_mode); + float* y = amalloc(sizeof(float) * N, out_mode); + double* exact = malloc(sizeof(double) * N); + srand(18081); + for (int i = 0; i < N * K; i++) w[i] = (float)rand() / RAND_MAX * 2 - 1; + for (int i = 0; i < K; i++) x[i] = (float)rand() / RAND_MAX * 2 - 1; + double scale = 0; + for (int c = 0; c < N; c++) { + double s = 0; + for (int k = 0; k < K; k++) s += (double)w[c * K + k] * x[k]; + exact[c] = s; + if (fabs(s) > scale) scale = fabs(s); + } + int bad_iters = 0; + for (int it = 0; it < iters; it++) { + memset(y, 0, sizeof(float) * N); + // C[1,N] = A[1,K] * B^T, B stored row-major [N,K] + cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 1, N, K, 1.0f, x, K, + w, K, 0.0f, y, N); + int bad = 0, first = -1; + for (int c = 0; c < N; c++) + if (fabs(y[c] - exact[c]) / scale > 1e-4) { + if (first < 0) first = c; + bad++; + } + if (bad) { + bad_iters++; + printf("iter %d: %d bad, first col %d got %f exact %f\n", it, bad, first, + y[first], exact[first]); + } + } + printf("SGEMM SUMMARY bad %d/%d (config: %s)\n", bad_iters, iters, + openblas_get_config()); + return 0; +} diff --git a/docs/mlxcelverse/upstream/README.md b/docs/mlxcelverse/upstream/README.md index a96bef82a..cf8ab7dfd 100644 --- a/docs/mlxcelverse/upstream/README.md +++ b/docs/mlxcelverse/upstream/README.md @@ -20,9 +20,9 @@ State checked on 2026-09-30. The fork's `rocm-support` head is `75915908` (merge | [08 launch-geometry helpers](08-launch-geometry-helpers/pr.md) | 19, 22 | yes | none | ready for manual submission | not submitted | | [09 SDPA fallback on CPU streams](09-sdpa-cpu-stream-fallback/pr.md) | 23 | yes | none | ready for manual submission | not submitted | | [10 HIP header dependencies](10-hip-header-dependencies/pr.md) | 26 | yes | none | ready for manual submission | not submitted | -| 11 (reserved) mxfp4 qmv nondeterminism | 27 | | | pending: lablup/mlxcel#2072 is still in progress; package it here once it lands | not submitted | +| [11 CPU-stream BLAS over fine-grained memory](11-cpu-blas-finegrained/pr.md) | 27 | yes (also on top of 01 to 10) | none | ready for manual submission | not submitted | -Packages are grouped the way the fork would review them: all of 01 is `quantized/qmm.hip`, 03 and 04 are the two halves of `indexing.hip` (scatter/gather and slice update), 08 is the two `kernel_utils.hpp` grid helpers. All ten patches also apply in sequence (01 to 10) with `git am`, so they can be submitted in any order that respects 07's dependency. +Packages are grouped the way the fork would review them: all of 01 is `quantized/qmm.hip`, 03 and 04 are the two halves of `indexing.hip` (scatter/gather and slice update), 08 is the two `kernel_utils.hpp` grid helpers. All eleven patches also apply in sequence (01 to 11) with `git am`, so they can be submitted in any order that respects 07's dependency. Each directory holds the patch (`git format-patch` output, authored by the maintainer, no AI attribution), `pr.md` (PR title, a header table for the submitter, and the PR body below a rule), and the reproduction (`repro.py`, `repro.hip` or `repro.sh`). @@ -39,8 +39,8 @@ Each directory holds the patch (`git format-patch` output, authored by the maint Verified while preparing (2026-09-30): -- Every patch was produced by a 3-way merge of the mlxcel commit that made the fix onto the fork file, with retarget-only hunks and item 9 left out and mlxcel-specific comments rewritten. `git apply --check` passes for each package on `75915908` (07 on `75915908` plus 05 and 06), and `git am` of all ten in order succeeds. -- After applying all ten, the fork's `mlx/backend/rocm/` differs from mlxcel's overlay only by the retarget items (2 to 6), items 7, 9 and 15, and comment wording. +- Every patch was produced by a 3-way merge of the mlxcel commit that made the fix onto the fork file, with retarget-only hunks and item 9 left out and mlxcel-specific comments rewritten. `git apply --check` passes for each package on `75915908` (07 on `75915908` plus 05 and 06), and `git am` of all eleven in order succeeds. +- After applying 01 to 10, the fork's `mlx/backend/rocm/` differs from mlxcel's overlay only by the retarget items (2 to 6), items 7, 9 and 15, and comment wording. - The evidence in each PR body comes from the mlxcel change and its tests, measured on gfx1151 (Radeon 8060S, HIP 7.15) with the backend retargeted onto MLX `81ba1c6a`; each body says so. Not verified, to do before submitting each PR: diff --git a/scripts/mlxcelverse/rocm_overlay.py b/scripts/mlxcelverse/rocm_overlay.py index 24408d1a4..9c7feffc5 100755 --- a/scripts/mlxcelverse/rocm_overlay.py +++ b/scripts/mlxcelverse/rocm_overlay.py @@ -562,8 +562,13 @@ def cmd_records(args: argparse.Namespace) -> int: numbers = [int(n) for n in re.findall(r"(?m)^(\d+)\. \*\*", fixes)] if not numbers: errors.append("LOCAL_FIXES.md: no numbered entries") - elif numbers != list(range(1, len(numbers) + 1)): - errors.append(f"LOCAL_FIXES.md: entries are numbered {numbers}, expected 1..{len(numbers)} in order") + elif sorted(numbers) != list(range(1, len(numbers) + 1)): + # Entries are grouped by section (core, kernels, build), so a new + # kernel fix can sit above an older build fix; what matters is that + # every number is used exactly once with no gap. + errors.append( + f"LOCAL_FIXES.md: entries are numbered {numbers}; expected each of 1..{len(numbers)} exactly once" + ) # Residual record. res = parse_residual((root / RESIDUAL_FILE).read_text()) From a79ab3ddd796add947274ce0bd09580ae9510924 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Wed, 30 Sep 2026 16:56:15 +0900 Subject: [PATCH 7/7] docs: add technical report for PR #2078 --- ...se-sync-drift-fork-packages-20260930.en.md | 206 ++++++++++++++++++ ...se-sync-drift-fork-packages-20260930.ko.md | 206 ++++++++++++++++++ 2 files changed, 412 insertions(+) create mode 100644 TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.en.md create mode 100644 TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.ko.md diff --git a/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.en.md b/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.en.md new file mode 100644 index 000000000..e61ae9a86 --- /dev/null +++ b/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.en.md @@ -0,0 +1,206 @@ +# Technical Report: PR #2078 - mlxcelverse ROCm sync, drift checks and fork PR packages + +**Date**: 2026-09-30 + +**Status**: Implemented and validated on the gfx1151 host (branch `update/issue-1813-mlxcelverse-sync` at `53c8f122` on `origin/main` `c5a71cfa`); pending merge. + +**Languages**: Python and Bash (tooling), Make, Markdown, git patches; one comment-only change in a HIP file + +**Risk Level**: Low for the build (no functional change to compiled code; the only overlay edit is a comment revert in `rope.hip`). Medium for process: `make verify` and `make verify-rocm` gain a new gate that fails any pin bump which skips the ROCm retarget, on every host. + +## Executive Summary + +Issue #1813 (phase 3 of epic #1801) asked for tooling and a written procedure for the two upstreams of mlxcel's ROCm overlay, the MLX pin (ml-explore/mlx) and the fork the backend is vendored from (NripeshN/mlx `rocm-support`), plus sending the overlay's fork-side fixes back to the fork. + +The PR adds `scripts/mlxcelverse/rocm_overlay.py` with five subcommands (`records`, `drift`, `sync`, `retarget`, and the `export-tree`/`api-report` helpers behind `check_api_drift.sh`), the entry points `sync_from_fork.sh` and `check_api_drift.sh`, and a 29-check synthetic-history test. The central addition is a drift check that rebuilds each of the 15 core overlay files as "MLX pin plus the fork's own change to that file" and requires what remains, the overlay's residual, to match a reviewed record, `patches-rocm/CORE_RESIDUAL.diff`, in which every hunk carries a note naming its `LOCAL_FIXES.md` item. Unlike the old +/- line-count comparison, this sees an overlay that was already wrong before a bump. The offline half runs as `make verify-rocm-overlay`, now part of both `make verify` and `make verify-rocm`. + +The PR also prepares eleven PR packages for the fork under `docs/mlxcelverse/upstream/` (patch, PR notes, reproduction), covering LOCAL_FIXES items 8, 10 to 14 and 16 to 27. None were submitted. The maintainer's rule is that automation prepares them and he submits them by hand, and ml-explore/mlx's AI usage policy (#4331) means each `pr.md` is notes for him to rewrite in his own words, not a finished description. + +Building fork code was denied by the auto-mode permission check in the implementing session, so `check_api_drift.sh` end to end, compiling the packages against the fork, and running their reproductions on a fork build were not done. They are listed as steps before submission. + +## 1. Problem Statement + +The ROCm overlay (`src/lib/mlx-cpp/patches-rocm/`) is 108 backend files under `mlx/backend/rocm/` plus 15 whole-file copies of MLX core files merged with the fork's hooks. `UPSTREAM` records three commits: the fork commit `75915908`, the fork's merge base with MLX `39886de4`, and the MLX pin the core files were retargeted to, `81ba1c6a`. Before this PR: + +- **No tooling** existed for either upstream. `scripts/mlxcelverse/` did not exist; the pin-bump procedure was three lines in `patches-rocm/README.md` and a paragraph in `CONTRIBUTING.md`. The retarget in #1801 had needed six hand fixes after 360 upstream commits. +- **The bump check could not see a wrong overlay.** Comparing an overlay's +/- line counts against the old and new upstream base confirms that upstream's changes arrived and the local ones stayed. It cannot tell whether the overlay was correct to begin with. A Metal overlay once carried half of an upstream fix for months until a reviewer compared it line by line (TECHNICAL_REPORTS/1772, section 3). +- **Nothing had gone back to the fork.** `LOCAL_FIXES.md` had grown to 27 entries, many marked "applies to the fork; to be proposed there", with no upstream link on any of them. +- **The records had drifted.** The README said 106 backend files (there are 108), several LOCAL_FIXES entries did not name the files they touch, and `rope.hip` differed from the fork only by a rewrapped comment that no entry recorded. + +## 2. Change Summary + +- **`scripts/mlxcelverse/rocm_overlay.py`** (new, about 1100 lines): `records`, `drift`, `sync`, `retarget`, `export-tree`, `api-report`. Git objects come from a cache repository (`~/.cache/mlxcel/mlxcelverse/mlx.git`) holding both remotes; the tool only fetches, never pushes. +- **`scripts/mlxcelverse/sync_from_fork.sh`** and **`check_api_drift.sh`** (new): the entry points the issue named. `check_api_drift.sh` configures MLX standalone with the ROCm options `build.rs` passes, builds with `make -k` so every failing translation unit is listed, and compares defined and undefined symbols across objects, since a primitive without a ROCm `eval_gpu` only appears as an undefined `mlx::core` symbol in a static libmlx. +- **`scripts/mlxcelverse/rocm_overlay_test.sh`** (new): 29 checks on a synthetic upstream and fork history built in a temporary repository. +- **`src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff`** (new, generated): the residual of the 4 core files that do not rebuild byte for byte, each with a note. +- **`Makefile`**: new `verify-rocm-overlay` target, added to `verify` and `verify-rocm`. +- **`docs/mlxcelverse/rocm-overlay.md`** (new): the records, the tools, the pin-bump and fork-sync procedures, and a "ROCm overlay" section template for bump PR bodies and reports. `CONTRIBUTING.md`, `patches-rocm/README.md`, `docs/architecture.md`, `docs/README.md` and the overlay comment in `src/lib/mlx-cpp/CMakeLists.txt` point to it or list the new record. +- **`docs/mlxcelverse/upstream/`** (new): an index and eleven package directories. +- **Records**: README backend count 106 to 108; LOCAL_FIXES now names the files of items 2, 7, 11 and 20 and states the naming rule; `rope.hip`'s comment is reverted to the fork's wording. + +Outside scripts and docs, the code diff is the comment revert in `rope.hip` and a reproduction `.hip` under `docs/` (package 06), which no build compiles. + +## 3. How the drift check catches an overlay that was already wrong + +### 3.1 The reconstruction + +For each core file, `drift` builds the file the overlay should be: + +``` +reconstruct(path) = git merge-file pin:path fork-merge-base:path fork:path +``` + +That is the pin's copy with the fork's own change to the file merged in, using the fork's merge base with upstream as the 3-way base, conflict markers kept. Using the fork's diff against its own merge base, applied on the pin, is what keeps upstream changes the fork picked up by merging MLX from being mistaken for fork changes. If the fork does not have the file, the reconstruction is the pin's copy. + +The overlay is then diffed against the reconstruction. What remains is exactly what the overlay adds on its own: conflict resolutions and local fixes. At `81ba1c6a`/`75915908`, 11 of the 15 core files rebuild byte for byte. The other four carry a residual, all explained: + +| Core file | Residual explained by | +|---|---| +| `mlx/backend/common/compiled.cpp` | item 1: keeps upstream's `negative_strides` tracking and the fork's constant-input skipping | +| `mlx/fast_primitives.h` | item 1: keeps upstream's `compile_options` and the fork's `output_input_aliases` | +| `mlx/io/safetensors.cpp` | item 1: keeps upstream's empty-tensor guard and the fork's ROCm `staged_write` | +| `mlx/backend/gpu/primitives.cpp` | item 24: `DynamicSliceUpdate` copies through `copy_gpu` and drops the fork's forced donation | + +### 3.2 The reviewed record + +The residual is committed as `CORE_RESIDUAL.diff`. Its header records the three commits and a SHA-256 of every core overlay file; each file with a residual needs a `# note :` line naming its LOCAL_FIXES item. `drift` fails when the recomputed residual differs from the record, prints the difference hunk by hunk, and requires `--write` to accept it; `--write` keeps existing notes and flags new files as needing one. + +This is how a wrong overlay surfaces. The residual is "everything the overlay does that neither upstream nor the fork does". An overlay that dropped half of an upstream change has a hunk there that deletes an upstream line, and the only way past the check is for a reviewer to see that hunk and write a note tying it to a LOCAL_FIXES entry. The initial generation of the record was itself that review of the existing overlay: every residual hunk was traced to items 1 and 24, and no half-applied upstream change was found. From then on: + +- any edit to a core file changes its hash, so `records` (offline) fails with "changed since the residual was generated" until `drift` is re-run and reviewed; +- a pin bump or fork sync changes the header commits, so `records` fails until the residual is regenerated for the new commits. + +The synthetic test covers the case directly: it replaces an upstream line of a core file with its pre-change form, and asserts that `records` fails on the hash, `drift` fails with "core residual differs", and the drift output contains the dropped upstream line as a new hunk. + +### 3.3 Backend files and uncarried hooks + +The backend files have no pin to reconstruct against, so `drift` compares each against the fork commit instead. Every file that is modified, local-only (`hadamard.hip`, `fft.hip`) or dropped relative to the fork must be named in `LOCAL_FIXES.md`. The check also lists fork changes to MLX files outside the backend that the overlay does not carry, and requires LOCAL_FIXES to say why. + +Review found the first version too lenient: a bare file name anywhere counted as naming, so `mlx/device.cpp` named `mlx/backend/rocm/device.cpp` and the top-level `CMakeLists.txt` named the backend's. A short name now counts only on its own, and a bare file name only when no other overlay file shares it (`bd5de658`, with a regression case that fails on the earlier tool). This rule is also why the PR had to touch the records: LOCAL_FIXES items 2, 7, 11 and 20 now name their files, and `rope.hip`, whose only difference from the fork was a rewrapped comment, was reverted rather than recorded as a local fix. + +### 3.4 What `sync --check` does not prove + +`sync_from_fork.sh --check` against the recorded fork commit reproduces `patches-rocm/` byte for byte, which was one of the issue's acceptance items. It holds by construction: `sync` carries local fixes as the overlay's own difference from the old fork commit, so syncing to the same commit is an identity. It cannot detect an unrecorded local change; the procedure doc says so, and points to `drift` as the check that can. + +## 4. The `make verify-rocm-overlay` gate + +```make +verify-rocm-overlay: + @python3 scripts/mlxcelverse/rocm_overlay.py records + @bash scripts/mlxcelverse/rocm_overlay_test.sh +``` + +`records` reads only files in the repository and takes about two seconds together with the test. It checks that `UPSTREAM` is well formed and names the build's MLX pin (from `scripts/ci/mlx_pinned_commit.sh`), that the README's backend and core counts and core file list match the tree, that LOCAL_FIXES entries 1 to N each appear once, and that `CORE_RESIDUAL.diff` was generated for the current commits and current core-file hashes, with a note for every residual and no note without one. On this branch it reports 108 backend and 15 core files, 27 LOCAL_FIXES entries, 4 core files with a noted residual, pin `81ba1c6a`. + +The target sits in **both** `make verify` and `make verify-rocm`. Pin bumps are usually made on a Mac, where `verify-rocm` never runs; with the gate in `verify`, editing `GIT_TAG` without running `rocm_overlay.py retarget` fails on the Mac immediately instead of first breaking an AMD build. The online checks (`drift`, `sync_from_fork.sh`, `check_api_drift.sh`) fetch or build and stay manual steps in the procedure. + +## 5. The eleven upstream packages + +Each directory under `docs/mlxcelverse/upstream/` holds a `git format-patch` against fork head `75915908` (authored by the maintainer, no AI attribution), `pr.md` (title, a header table for the submitter, and a draft body in the shape of the fork's PR template), and a reproduction. On 2026-09-30 the fork head was still `75915908`, the commit `UPSTREAM` records, and the fork had no open PRs, so none of these fixes had landed there. + +| Package | LOCAL_FIXES items | Applies cleanly to `75915908` | Status | +|---|---|---|---| +| 01 quantized matmul dispatch | 8, 10, 12, 13 | yes | ready for manual submission, not submitted | +| 02 ArgReduce grid limit | 11 | yes | same | +| 03 Scatter size argument and narrow index dtypes | 14, 17 | yes | same | +| 04 SliceUpdate tail and source donation | 21, 24 | yes | same | +| 05 Hadamard | 16 | yes | same | +| 06 blocking-sync before the first HIP queue | 20 | yes | same | +| 07 FFT through hipFFT | 18, 25 | only after 05 and 06 (adjacent-line conflicts with 05 in `CMakeLists.txt` and `primitives.cpp`) | ready after 05 and 06, not submitted | +| 08 launch-geometry helpers | 19, 22 | yes | ready for manual submission, not submitted | +| 09 SDPA fallback on CPU streams | 23 | yes | same | +| 10 HIP header dependencies | 26 | yes | same | +| 11 CPU-stream BLAS over fine-grained memory | 27 | yes, also on top of 01 to 10 | same | + +Package 11 was added after the branch was rebased onto `c5a71cfa`, which merged item 27 (#2072, PR #2079). The index records that each patch passes `git apply --check` on the fork head (07 after 05 and 06) and that all eleven apply in sequence with `git am`. + +Items not packaged, with the reason recorded in the index: 1 to 6 are retarget-only and go upstream when the fork merges newer MLX; 7 (GPU fault reporting) is built on `Event::error()` from ml-explore/mlx#3742, which the fork's MLX base predates; 9 disables a wrong-result path that has no root cause yet; 15 (`SearchSorted`) implements a primitive the fork's base does not have (ml-explore/mlx#4035). + +Packages are grouped as the fork would review them (all of 01 is `quantized/qmm.hip`; 03 and 04 are the two halves of `indexing.hip`; 08 is the two grid helpers in `kernel_utils.hpp`), and each patch was built by 3-way merging the mlxcel commit that made the fix onto the fork file, leaving out retarget hunks and item 9 and rewriting mlxcel-specific comments. + +## 6. Contribution situation and the AI usage policy + +### 6.1 Prepared by automation, submitted by hand + +The maintainer's direction, restated in the issue thread and at the top of the index, is that fork-side fixes become PRs to NripeshN/mlx `rocm-support`, prepared under #1813 and submitted manually. Automation never pushes to, forks, or opens issues, PRs or comments on NripeshN/mlx or ml-explore/mlx; only read-only fetches and API reads were used. The index ends with the manual steps: fork, `git am`, build, run the reproduction before and after, `pre-commit`, open the PR, then record the link in the index and in the matching LOCAL_FIXES items. + +### 6.2 The fork + +Read-only on 2026-09-30: + +- The fork's `CONTRIBUTING.md` is MLX's older generic text (tests, benchmarks for performance changes, docs for API changes, passing tests and one review, `pre-commit`). Issues are disabled, so a PR is the only channel. +- Its PR template has "Proposed changes" and a four-box checklist, and says nothing about AI or automation. The `pr.md` drafts follow its shape and leave the checklist unticked. +- 13 PRs from 4 contributors, 8 merged, the last on 2026-07-19; merges happen without formal GitHub reviews. Titles follow `fix(rocm): ...`, which the patches match. The fork has been quiet for over two months, so response time is unknown. + +### 6.3 ml-explore/mlx's AI usage policy + +The fork's branch is the head of ml-explore/mlx#2300, so what merges into the fork is headed for ml-explore review. On 2026-08-20 ml-explore/mlx adopted an AI usage policy (#4331): its PR template opens with "I understand it is strictly prohibited to use AI to write PR description" and adds an "AI usage disclosure" field, and its `CONTRIBUTING.md` holds contributors accountable for AI-assisted work and asks for written material in the contributor's own voice. The fork's branch predates this. + +The patches, commit messages and `pr.md` bodies were drafted with AI assistance. The fork's own rules do not forbid that, but its maintainer may apply the upstream expectation. The index therefore treats each `pr.md` as **notes for the maintainer to rewrite in his own words**, recommends stating AI assistance if a disclosure is asked for, and leaves the decision to him. That is why every package is "ready for manual submission" rather than submitted, and why the acceptance item "the scale-dispatch fix is proposed upstream with a link recorded" stays open after this PR. + +## 7. Technical Decisions + +### Reconstruct against the fork's merge base, not the fork commit + +Diffing the overlay against the fork's copy of a core file would mix in every upstream change between the fork's MLX base and the pin. Taking the fork's delta against its own merge base and merging it onto the pin isolates the three sources (upstream, fork, local), so the residual is only the local part. The same idea drives `sync` for core files: a 3-way merge from "pin plus old fork delta" to "pin plus new fork delta". + +### A committed, reviewed residual instead of a zero-residual rule + +Items 1 and 24 are legitimate local differences, so "the overlay must equal the reconstruction" would never pass. Recording the residual and requiring a note per file makes every legitimate difference explicit and makes any new one a visible diff in review. The file hashes in the header let the offline `records` check catch a core-file edit without fetching anything. + +### Carry local fixes as the overlay's own difference + +`sync` 3-way merges old fork commit, overlay and new fork commit for each backend file, so the difference between the overlay and the old fork commit (the full local fix list) is carried automatically, including local-only files. The alternative, replaying a separate patch list, would need that list kept in step with the overlay by hand. The trade-off, discussed in section 3.4, is that `sync --check` proves nothing about unrecorded changes; `drift`'s naming rule covers that. + +### Offline checks in the gate, online checks manual + +Only `records` and the synthetic test run in `make verify`: they need no network and no ROCm, and they finish in about two seconds on any host. `drift` fetches, and `check_api_drift.sh` needs an AMD host and a cold MLX build. Putting those in a gate would make `make verify` depend on the network and on hardware most contributors do not have. + +### Treat fetched trees as untrusted + +Git stores a `..` tree entry verbatim and a fetch does not fsck by default, so a hostile fork commit (or a `--fork-url`) could have made `sync` or `export-tree` write outside the overlay, for example `mlx/backend/rocm/../../../../.bashrc`. Security review reproduced it with a crafted tree. Every write or unlink of a tree-derived path now goes through `safe_dest`, tree listings use `-z`, and option-like fetch arguments are refused (`51b142fc`, `0119aee9`), with a test that builds such a tree through `git mktree`. + +## 8. Validation + +PR author (gfx1151): + +- `sync_from_fork.sh --check` at the recorded fork commit, with a freshly fetched cache, reproduced `patches-rocm/` byte for byte. Because that is an identity (section 3.4), the author also ran a forward sync of a copy claiming the older fork commit `53cbdf8c` (34 files changed since): 30 files merged cleanly and 4 were flagged as real interactions with local fixes. +- `drift` passed against the recorded commits: 11 of 15 core files byte for byte, residual items 1 and 24. +- `git apply --check` of each package on `75915908` (07 after 05 and 06) and `git am` in sequence. The PR body's verification line says "all ten"; package 11 was added afterwards, and its commit records that it applies on its own and after 01 to 10. +- `cargo test --features rocm --test dead_doc_pointers` passed. + +Orchestrator verification (gfx1151, branch at `53c8f122` on `c5a71cfa`): + +- `make verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt verify-rocm-overlay` passed. The records check reported 108 backend and 15 core files, 27 LOCAL_FIXES entries, 4 core files with a noted residual, pin `81ba1c6a`. +- `scripts/mlxcelverse/rocm_overlay_test.sh` passed 29 checks: good-overlay records and drift, `sync --check`, a forward sync, a fork conflict, a fork ahead of the pin, a `..` tree entry for both `sync` and `export-tree`, a pin bump and retarget, the already-wrong overlay, an unrecorded backend change (including one named only by a same-named file elsewhere), `.DS_Store`, gap-numbered LOCAL_FIXES, a wrong README count, a stray record, and `api-report` on a synthetic build log. +- The full test suite was not rerun for this PR. Outside scripts and docs the diff is a comment-only change in `rope.hip` and a `.hip` reproduction under `docs/` that no build compiles, so a suite run would only have exercised unchanged code, while two GPU-measuring units were running on the host. +- The orchestrator found the unit's rebase onto `c5a71cfa` and the item-27 commit unpushed, pushed them with `--force-with-lease`, and corrected the package count in the PR body. + +## 9. Learning Points + +- **Count checks confirm movement, not correctness.** A +/- line comparison across a bump can only say that the delta was preserved. Checking correctness needs a reference for what the file should be, and here that reference is constructible: pin plus the fork's delta against its own base. +- **Make the reviewed exception list the artifact.** The residual is small (4 files, 2 LOCAL_FIXES items) and each hunk is annotated, so the review a human would otherwise redo on every bump is recorded once and re-triggered only when something changes. +- **An identity check needs to be named as one.** `sync --check` at the recorded commit is byte for byte by construction. The first version of the procedure doc claimed it could detect an overlay changed outside the procedure; review corrected that, and the useful sync evidence became the forward sync from an older commit. +- **Name matching is a security-relevant heuristic.** Accepting a bare file name as "recorded" silently exempted the two most often edited backend files. Checks that decide whether a change is documented need the same care as checks that decide whether it is allowed. +- **Paths from fetched git trees are input.** Tooling that only fetches still writes files derived from someone else's tree; treat those paths as untrusted. + +## 10. What Is Not Verified + +The auto-mode permission check in the implementing session denied building fork code. As a result: + +- **`check_api_drift.sh` was not run end to end.** The acceptance item "the drift check lists the six known breaks against the fork's merge base plus current upstream" is unchecked. The command to run is `scripts/mlxcelverse/check_api_drift.sh --rocm-from fork:75915908dfe5028335d318b10340313744fd3a8d` on an AMD host. `api-report` is covered only by the synthetic build log in the test. +- **No package was compiled against the fork.** The fork's MLX base is older than mlxcel's pin, so each patch must at least compile there. Package 03 adds a compile-time argument-size check to `add_kernel_node`, which may flag a fork call site mlxcel never compiled. +- **No reproduction was run on a fork build**, unpatched or patched. The scripts follow the mlxcel tests that verified each fix; several unpatched cases fault the GPU queue, so those scripts run each case in a child process with a timeout. +- **`pre-commit run --all-files`**, which the fork's template asks for, was not run on the patches. + +The index lists all four as steps before submitting each PR. Separately: Metal and CUDA were not run (not available on this host); the PR touches no Metal or CUDA code, and `verify-rocm-overlay` is pure Python and git. + +## 11. Remaining Work + +- Before each submission: build the fork with the patch, run the reproduction before and after, run `pre-commit`, rewrite `pr.md` in the maintainer's own words, and decide on AI disclosure. +- After each submission: record the link in the index and add "Proposed upstream: " to the LOCAL_FIXES items. The issue's acceptance item for the scale-dispatch fix (package 01) is met only then. +- Run `check_api_drift.sh --rocm-from fork:75915908...` once on an AMD host to confirm the six known breaks. +- Package item 7 once the fork merges MLX at or past #3742, item 15 at or past #4035, and item 9 once it has a root cause. +- After any fork sync, drop the packages the fork absorbed and regenerate the rest against the new head. + +Refs: #1813 (closed by this PR), #1801, #1802, PR #1818, PR #1819, #1811, PR #2079, #2072, TECHNICAL_REPORTS/1772, ml-explore/mlx#2300, ml-explore/mlx#4331, ml-explore/mlx#3742, ml-explore/mlx#4035. diff --git a/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.ko.md b/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.ko.md new file mode 100644 index 000000000..a6b8bfd02 --- /dev/null +++ b/TECHNICAL_REPORTS/2078-mlxcelverse-sync-drift-fork-packages-20260930.ko.md @@ -0,0 +1,206 @@ +# 기술 보고서: PR #2078 - mlxcelverse ROCm 동기화, drift 검사, fork PR 패키지 + +**날짜**: 2026-09-30 + +**상태**: gfx1151 호스트에서 구현 및 검증 완료 (`origin/main` `c5a71cfa` 위의 `update/issue-1813-mlxcelverse-sync` 브랜치, `53c8f122`). 머지 대기 중. + +**언어**: Python, Bash (도구), Make, Markdown, git 패치. HIP 파일 하나에 주석만 바뀐 변경 + +**위험도**: 빌드에는 낮음 (컴파일되는 코드의 기능 변경 없음. overlay 변경은 `rope.hip`의 주석 되돌리기뿐). 절차 측면에서는 중간: `make verify`와 `make verify-rocm`에 새 게이트가 추가되어, ROCm retarget을 빠뜨린 pin bump는 어느 호스트에서든 실패한다. + +## 요약 + +이슈 #1813 (에픽 #1801의 3단계)은 mlxcel ROCm overlay의 두 upstream, 즉 MLX pin (ml-explore/mlx)과 백엔드를 가져온 fork (NripeshN/mlx `rocm-support`)를 따라가기 위한 도구와 문서화된 절차, 그리고 overlay가 가진 fork 측 수정을 fork로 돌려보내는 일을 요구했다. + +이 PR은 `scripts/mlxcelverse/rocm_overlay.py`를 추가한다. 하위 명령은 `records`, `drift`, `sync`, `retarget`, 그리고 `check_api_drift.sh`가 쓰는 `export-tree`/`api-report`다. 진입점 `sync_from_fork.sh`, `check_api_drift.sh`와 29개 검사로 된 합성 이력 테스트도 함께 들어간다. 핵심은 drift 검사다. 15개 core overlay 파일 각각을 "MLX pin에 fork가 그 파일에 가한 변경을 합친 것"으로 다시 만들고, 남는 차이(overlay의 residual)가 리뷰를 거친 기록 `patches-rocm/CORE_RESIDUAL.diff`와 일치해야 한다. 이 기록의 각 hunk에는 해당 `LOCAL_FIXES.md` 항목을 가리키는 note가 붙는다. 기존의 +/- 줄 수 비교와 달리, 이 방법은 bump 이전부터 이미 잘못되어 있던 overlay를 잡아낸다. 오프라인으로 도는 부분은 `make verify-rocm-overlay`가 되었고, 이 타깃은 `make verify`와 `make verify-rocm` 양쪽에 들어간다. + +PR은 또한 `docs/mlxcelverse/upstream/` 아래에 fork용 PR 패키지 11개(패치, PR 노트, 재현 스크립트)를 준비한다. LOCAL_FIXES 항목 8, 10~14, 16~27을 다룬다. 하나도 제출되지 않았다. 메인테이너의 원칙은 패키지 준비는 자동화가, 제출은 본인이 손으로 한다는 것이다. 또 ml-explore/mlx의 AI 사용 정책(#4331) 때문에 각 `pr.md`는 완성된 설명이 아니라 메인테이너가 자기 말로 다시 쓸 노트다. + +구현 세션에서 auto 모드 권한 검사가 fork 코드 빌드를 거부했다. 그래서 `check_api_drift.sh` 전체 실행, 패키지를 fork에 대고 컴파일하기, fork 빌드에서 재현 스크립트 실행은 하지 못했다. 이들은 제출 전 단계로 기록되어 있다. + +## 1. 문제 정의 + +ROCm overlay(`src/lib/mlx-cpp/patches-rocm/`)는 `mlx/backend/rocm/` 아래 백엔드 파일 108개와, fork의 hook을 합친 MLX core 파일 15개의 전체 파일 사본으로 이루어진다. `UPSTREAM`은 커밋 세 개를 기록한다: fork 커밋 `75915908`, fork와 MLX의 merge base `39886de4`, core 파일을 retarget한 MLX pin `81ba1c6a`. 이 PR 이전에는: + +- **두 upstream 어느 쪽에도 도구가 없었다.** `scripts/mlxcelverse/`는 존재하지 않았고, pin bump 절차는 `patches-rocm/README.md`의 세 줄과 `CONTRIBUTING.md`의 한 문단이 전부였다. #1801의 retarget은 upstream 커밋 360개를 넘으며 손으로 여섯 군데를 고쳐야 했다. +- **bump 검사는 잘못된 overlay를 볼 수 없었다.** 이전과 이후 upstream base에 대한 overlay의 +/- 줄 수 비교는 upstream 변경이 들어왔고 로컬 변경이 남았다는 것만 확인한다. overlay가 애초에 맞았는지는 알 수 없다. Metal overlay 하나가 upstream 수정의 절반만 가진 채 몇 달을 지냈고, 리뷰어가 한 줄씩 비교하고 나서야 발견되었다 (TECHNICAL_REPORTS/1772, 3절). +- **fork로 돌아간 것이 없었다.** `LOCAL_FIXES.md`는 27개 항목으로 늘었고 상당수가 "fork에도 해당, fork에 제안 예정"으로 표시되어 있었지만, upstream 링크가 달린 항목은 없었다. +- **기록이 어긋나 있었다.** README는 백엔드 파일을 106개라고 했고(실제 108개), 몇몇 LOCAL_FIXES 항목은 건드린 파일을 명시하지 않았으며, `rope.hip`은 어느 항목에도 기록되지 않은 주석 줄바꿈 차이만으로 fork와 달랐다. + +## 2. 변경 요약 + +- **`scripts/mlxcelverse/rocm_overlay.py`** (신규, 약 1100줄): `records`, `drift`, `sync`, `retarget`, `export-tree`, `api-report`. git 객체는 두 remote를 모두 가진 캐시 저장소(`~/.cache/mlxcel/mlxcelverse/mlx.git`)에서 가져온다. 도구는 fetch만 하고 push는 하지 않는다. +- **`scripts/mlxcelverse/sync_from_fork.sh`**, **`check_api_drift.sh`** (신규): 이슈가 이름을 정한 진입점. `check_api_drift.sh`는 `build.rs`가 넘기는 ROCm 옵션으로 MLX를 단독 configure하고, 실패하는 translation unit을 모두 보도록 `make -k`로 빌드한 뒤 object들의 정의/미정의 심볼을 비교한다. libmlx가 정적 라이브러리라서 ROCm `eval_gpu`가 없는 primitive는 미정의 `mlx::core` 심볼로만 드러나기 때문이다. +- **`scripts/mlxcelverse/rocm_overlay_test.sh`** (신규): 임시 저장소에 만든 합성 upstream/fork 이력 위에서 29개 검사. +- **`src/lib/mlx-cpp/patches-rocm/CORE_RESIDUAL.diff`** (신규, 생성 파일): byte 단위로 재구성되지 않는 core 파일 4개의 residual과 파일별 note. +- **`Makefile`**: 새 `verify-rocm-overlay` 타깃, `verify`와 `verify-rocm`에 추가. +- **`docs/mlxcelverse/rocm-overlay.md`** (신규): 기록 파일, 도구, pin bump와 fork 동기화 절차, bump PR 본문과 보고서에 넣을 "ROCm overlay" 절 템플릿. `CONTRIBUTING.md`, `patches-rocm/README.md`, `docs/architecture.md`, `docs/README.md`, `src/lib/mlx-cpp/CMakeLists.txt`의 overlay 주석이 이 문서를 가리키거나 새 기록 파일을 나열한다. +- **`docs/mlxcelverse/upstream/`** (신규): 색인과 패키지 디렉터리 11개. +- **기록**: README 백엔드 수 106에서 108로. LOCAL_FIXES는 항목 2, 7, 11, 20의 파일을 명시하고 파일 명시 규칙을 적었다. `rope.hip` 주석은 fork 문구로 되돌렸다. + +scripts와 docs 밖의 코드 diff는 `rope.hip` 주석 되돌리기와, 어떤 빌드도 컴파일하지 않는 `docs/` 아래 재현용 `.hip`(패키지 06)뿐이다. + +## 3. drift 검사가 이미 잘못된 overlay를 잡는 방식 + +### 3.1 재구성 + +drift는 core 파일마다 overlay가 되어야 할 파일을 만든다. + +``` +reconstruct(path) = git merge-file pin:path fork-merge-base:path fork:path +``` + +pin의 사본에 fork가 그 파일에 가한 변경을 합친 것이다. 3-way base는 fork의 upstream merge base이고, 충돌 표시는 그대로 둔다. fork의 자기 merge base 대비 diff를 pin 위에 적용하기 때문에, fork가 MLX를 머지하며 가져온 upstream 변경을 fork의 변경으로 착각하지 않는다. fork에 파일이 없으면 재구성 결과는 pin의 사본이다. + +그다음 overlay를 재구성 결과와 diff한다. 남는 것은 overlay가 스스로 더한 것, 즉 충돌 해결과 로컬 수정뿐이다. `81ba1c6a`/`75915908` 기준으로 core 파일 15개 중 11개는 byte 단위로 일치한다. 나머지 4개의 residual은 모두 설명된다: + +| Core 파일 | residual의 근거 | +|---|---| +| `mlx/backend/common/compiled.cpp` | 항목 1: upstream의 `negative_strides` 추적과 fork의 상수 입력 건너뛰기를 모두 유지 | +| `mlx/fast_primitives.h` | 항목 1: upstream의 `compile_options`와 fork의 `output_input_aliases`를 모두 유지 | +| `mlx/io/safetensors.cpp` | 항목 1: upstream의 빈 텐서 가드와 fork의 ROCm `staged_write`를 모두 유지 | +| `mlx/backend/gpu/primitives.cpp` | 항목 24: `DynamicSliceUpdate`가 `copy_gpu`로 복사하고 fork의 강제 donation을 제거 | + +### 3.2 리뷰된 기록 + +residual은 `CORE_RESIDUAL.diff`로 커밋된다. 헤더에는 커밋 세 개와 모든 core overlay 파일의 SHA-256이 기록되고, residual이 있는 파일마다 해당 LOCAL_FIXES 항목을 적은 `# note :` 줄이 필요하다. 다시 계산한 residual이 기록과 다르면 drift는 실패하고, 차이를 hunk 단위로 출력하며, 받아들이려면 `--write`가 필요하다. `--write`는 기존 note를 유지하고 note가 필요한 새 파일을 알려 준다. + +잘못된 overlay는 이렇게 드러난다. residual은 "upstream도 fork도 하지 않는데 overlay가 하는 모든 것"이다. upstream 변경의 절반을 빠뜨린 overlay라면 residual에 upstream 줄을 지우는 hunk가 생기고, 검사를 통과하려면 리뷰어가 그 hunk를 보고 LOCAL_FIXES 항목과 연결하는 note를 써야 한다. 기록을 처음 생성한 것 자체가 기존 overlay에 대한 그 리뷰였다. residual의 모든 hunk가 항목 1과 24로 추적되었고, 절반만 적용된 upstream 변경은 발견되지 않았다. 이후로는: + +- core 파일을 수정하면 해시가 바뀌므로, drift를 다시 돌려 리뷰할 때까지 `records`(오프라인)가 "changed since the residual was generated"로 실패한다. +- pin bump나 fork 동기화는 헤더의 커밋을 바꾸므로, 새 커밋 기준으로 residual을 다시 만들 때까지 `records`가 실패한다. + +합성 테스트는 이 경우를 직접 다룬다. core 파일의 upstream 줄 하나를 변경 이전 형태로 되돌리고, `records`가 해시로 실패하는지, drift가 "core residual differs"로 실패하는지, drift 출력에 빠진 upstream 줄이 새 hunk로 나오는지 확인한다. + +### 3.3 백엔드 파일과 overlay가 옮기지 않은 hook + +백엔드 파일은 재구성할 pin 사본이 없으므로, drift는 각 파일을 fork 커밋과 비교한다. fork 대비 수정되었거나, 로컬에만 있거나(`hadamard.hip`, `fft.hip`), 빠진 파일은 모두 `LOCAL_FIXES.md`에 이름이 있어야 한다. 또한 overlay가 옮기지 않은 백엔드 밖 MLX 파일에 대한 fork의 변경을 나열하고, LOCAL_FIXES가 그 이유를 적도록 요구한다. + +리뷰에서 첫 버전이 너무 느슨하다는 것이 드러났다. 파일 이름만 어디든 나오면 명시로 인정되어, `mlx/device.cpp`가 `mlx/backend/rocm/device.cpp`를, 최상위 `CMakeLists.txt`가 백엔드의 것을 명시한 것으로 처리되었다. 이제 짧은 이름은 독립적으로 나올 때만, 파일 이름만 쓴 경우는 같은 이름의 다른 overlay 파일이 없을 때만 인정된다(`bd5de658`, 이전 도구에서 실패하는 회귀 케이스 포함). PR이 기록을 건드려야 했던 이유도 이 규칙이다. LOCAL_FIXES 항목 2, 7, 11, 20이 파일을 명시하게 되었고, fork와의 차이가 주석 줄바꿈뿐이던 `rope.hip`은 로컬 수정으로 기록하는 대신 되돌렸다. + +### 3.4 `sync --check`가 증명하지 않는 것 + +기록된 fork 커밋에 대한 `sync_from_fork.sh --check`는 `patches-rocm/`를 byte 단위로 재현하며, 이는 이슈의 수락 조건 중 하나였다. 이는 구조상 당연하다. `sync`는 로컬 수정을 이전 fork 커밋 대비 overlay 자신의 차이로 옮기므로, 같은 커밋으로 동기화하면 항등 변환이 된다. 기록되지 않은 로컬 변경은 잡을 수 없다. 절차 문서는 이를 명시하고, 그 역할은 drift가 한다고 적는다. + +## 4. `make verify-rocm-overlay` 게이트 + +```make +verify-rocm-overlay: + @python3 scripts/mlxcelverse/rocm_overlay.py records + @bash scripts/mlxcelverse/rocm_overlay_test.sh +``` + +`records`는 저장소 안의 파일만 읽고, 테스트와 합쳐 약 2초 걸린다. `UPSTREAM`의 형식이 올바르고 빌드의 MLX pin(`scripts/ci/mlx_pinned_commit.sh`)을 가리키는지, README의 백엔드/core 파일 수와 core 파일 목록이 트리와 맞는지, LOCAL_FIXES 항목 1~N이 각각 한 번씩 있는지, `CORE_RESIDUAL.diff`가 현재 커밋과 현재 core 파일 해시로 생성되었고 residual마다 note가 있고 residual 없는 note가 없는지 확인한다. 이 브랜치에서는 백엔드 108개와 core 15개, LOCAL_FIXES 27개 항목, note가 있는 residual core 파일 4개, pin `81ba1c6a`를 보고한다. + +이 타깃은 `make verify`와 `make verify-rocm` **양쪽**에 있다. pin bump는 보통 Mac에서 하는데, Mac에서는 `verify-rocm`이 돌지 않는다. `verify`에 게이트가 있으면 `rocm_overlay.py retarget` 없이 `GIT_TAG`만 바꾼 경우 AMD 빌드가 먼저 깨지는 대신 Mac에서 바로 실패한다. 온라인 검사(`drift`, `sync_from_fork.sh`, `check_api_drift.sh`)는 fetch나 빌드가 필요하므로 절차의 수동 단계로 남는다. + +## 5. upstream 패키지 11개 + +`docs/mlxcelverse/upstream/` 아래 각 디렉터리에는 fork head `75915908`에 대한 `git format-patch`(작성자는 메인테이너, AI 표기 없음), `pr.md`(제목, 제출자용 헤더 표, fork PR 템플릿 형태의 본문 초안), 재현 스크립트가 있다. 2026-09-30 기준 fork head는 여전히 `UPSTREAM`이 기록한 `75915908`이고 열린 PR이 없으므로, 이 수정들 중 fork에 들어간 것은 없다. + +| 패키지 | LOCAL_FIXES 항목 | `75915908`에 깨끗이 적용 | 상태 | +|---|---|---|---| +| 01 quantized matmul dispatch | 8, 10, 12, 13 | 예 | 수동 제출 준비 완료, 미제출 | +| 02 ArgReduce grid limit | 11 | 예 | 동일 | +| 03 Scatter 크기 인자와 좁은 인덱스 dtype | 14, 17 | 예 | 동일 | +| 04 SliceUpdate tail과 source donation | 21, 24 | 예 | 동일 | +| 05 Hadamard | 16 | 예 | 동일 | +| 06 첫 HIP 큐 이전의 blocking-sync | 20 | 예 | 동일 | +| 07 hipFFT를 통한 FFT | 18, 25 | 05, 06 이후에만 (`CMakeLists.txt`와 `primitives.cpp`에서 05와 인접 줄 충돌) | 05, 06 이후 준비 완료, 미제출 | +| 08 launch geometry helper | 19, 22 | 예 | 수동 제출 준비 완료, 미제출 | +| 09 CPU stream에서의 SDPA fallback | 23 | 예 | 동일 | +| 10 HIP header 의존성 | 26 | 예 | 동일 | +| 11 fine-grained 메모리 위 CPU stream BLAS | 27 | 예, 01~10 위에서도 | 동일 | + +패키지 11은 브랜치를 항목 27(#2072, PR #2079)이 머지된 `c5a71cfa` 위로 rebase한 뒤 추가되었다. 색인에는 각 패치가 fork head에서 `git apply --check`를 통과하고(07은 05, 06 이후), 11개 모두 `git am`으로 순서대로 적용된다고 기록되어 있다. + +패키지로 만들지 않은 항목과 이유도 색인에 있다. 1~6은 retarget 전용이라 fork가 새 MLX를 머지할 때 upstream으로 간다. 7(GPU fault 보고)은 ml-explore/mlx#3742의 `Event::error()` 위에 만들어졌는데 fork의 MLX base가 그보다 오래되었다. 9는 잘못된 결과를 내는 경로를 끄는 것인데 아직 근본 원인이 없다. 15(`SearchSorted`)는 fork의 base에 없는 primitive(ml-explore/mlx#4035)를 구현한다. + +패키지는 fork가 리뷰할 단위로 묶었다(01은 모두 `quantized/qmm.hip`, 03과 04는 `indexing.hip`의 두 부분, 08은 `kernel_utils.hpp`의 grid helper 두 개). 각 패치는 수정을 만든 mlxcel 커밋을 fork 파일에 3-way 머지해 만들었고, retarget hunk와 항목 9는 빼고 mlxcel 고유의 주석은 다시 썼다. + +## 6. 기여 상황과 AI 사용 정책 + +### 6.1 준비는 자동화가, 제출은 손으로 + +이슈 스레드와 색인 첫머리에 적힌 메인테이너의 지시는, fork 측 수정은 #1813 아래에서 NripeshN/mlx `rocm-support`에 대한 PR로 준비하되 제출은 수동으로 한다는 것이다. 자동화는 NripeshN/mlx나 ml-explore/mlx에 push, fork, 이슈/PR/댓글 작성을 하지 않는다. 준비 과정에서는 읽기 전용 fetch와 API 조회만 사용했다. 색인 끝에 수동 절차가 있다: fork, `git am`, 빌드, 적용 전후 재현 실행, `pre-commit`, PR 생성, 그리고 색인과 해당 LOCAL_FIXES 항목에 링크 기록. + +### 6.2 fork + +2026-09-30에 읽기 전용으로 확인한 내용: + +- fork의 `CONTRIBUTING.md`는 MLX의 예전 일반 문구다(테스트, 성능 변경 시 벤치마크, API 변경 시 문서, 테스트 통과와 리뷰 1회, `pre-commit`). 이슈가 비활성화되어 있어 PR이 유일한 경로다. +- PR 템플릿은 "Proposed changes"와 네 칸짜리 체크리스트이고, AI나 자동화에 대한 언급은 없다. `pr.md` 초안은 이 형태를 따르고 체크리스트는 비워 두었다. +- PR 13개, 기여자 4명, 머지 8개, 마지막 머지는 2026-07-19. 공식 GitHub 리뷰 없이 머지된다. 제목은 `fix(rocm): ...` 형식이고 패치도 이를 따른다. fork는 두 달 넘게 조용해서 응답 시간은 알 수 없다. + +### 6.3 ml-explore/mlx의 AI 사용 정책 + +fork의 브랜치는 ml-explore/mlx#2300의 head이므로, fork에 머지된 것은 결국 ml-explore 리뷰로 간다. 2026-08-20 ml-explore/mlx는 AI 사용 정책(#4331)을 도입했다. PR 템플릿은 "I understand it is strictly prohibited to use AI to write PR description"으로 시작하고 "AI usage disclosure" 칸을 추가했으며, `CONTRIBUTING.md`는 AI를 활용한 작업에도 기여자가 책임을 지고 글은 기여자 자신의 목소리로 쓰라고 요구한다. fork의 브랜치는 이보다 앞선다. + +패치, 커밋 메시지, `pr.md` 본문은 AI의 도움을 받아 작성되었다. fork 자체 규칙은 이를 금지하지 않지만, fork 메인테이너가 upstream의 기대를 적용할 수 있다. 그래서 색인은 각 `pr.md`를 **메인테이너가 자기 말로 다시 쓸 노트**로 다루고, disclosure를 요구받으면 AI 도움을 밝히라고 권하며, 결정은 메인테이너에게 맡긴다. 모든 패키지가 제출이 아니라 "수동 제출 준비 완료" 상태인 이유이고, "scale-dispatch 수정이 upstream에 제안되고 링크가 기록됨"이라는 수락 조건이 이 PR 이후에도 열려 있는 이유다. + +## 7. 기술적 선택과 그 이유 + +### fork 커밋이 아니라 fork의 merge base 기준으로 재구성 + +overlay를 fork의 core 파일 사본과 직접 diff하면 fork의 MLX base와 pin 사이의 모든 upstream 변경이 섞인다. fork의 자기 merge base 대비 delta를 pin 위에 머지하면 세 출처(upstream, fork, 로컬)가 분리되어 residual에는 로컬 부분만 남는다. core 파일에 대한 `sync`도 같은 생각이다: "pin + 이전 fork delta"에서 "pin + 새 fork delta"로 가는 3-way 머지. + +### residual 0 규칙 대신 커밋되고 리뷰된 residual + +항목 1과 24는 정당한 로컬 차이이므로 "overlay는 재구성 결과와 같아야 한다"는 규칙은 절대 통과하지 못한다. residual을 기록하고 파일마다 note를 요구하면 정당한 차이는 모두 명시되고, 새 차이는 리뷰에서 보이는 diff가 된다. 헤더의 파일 해시 덕분에 오프라인 `records` 검사가 아무것도 fetch하지 않고 core 파일 수정을 잡는다. + +### 로컬 수정을 overlay 자신의 차이로 옮기기 + +`sync`는 백엔드 파일마다 이전 fork 커밋, overlay, 새 fork 커밋을 3-way 머지한다. 따라서 overlay와 이전 fork 커밋의 차이(로컬 수정 전체)가 로컬 전용 파일까지 포함해 자동으로 옮겨진다. 별도 패치 목록을 다시 적용하는 대안은 그 목록을 overlay와 손으로 맞춰야 한다. 대가는 3.4절에서 본 것처럼 `sync --check`가 기록되지 않은 변경에 대해 아무것도 증명하지 못한다는 점이고, 이는 drift의 파일 명시 규칙이 맡는다. + +### 게이트에는 오프라인 검사만, 온라인 검사는 수동 + +`make verify`에는 `records`와 합성 테스트만 들어간다. 네트워크도 ROCm도 필요 없고 어느 호스트에서든 2초 정도면 끝난다. drift는 fetch를 하고, `check_api_drift.sh`는 AMD 호스트와 cold MLX 빌드가 필요하다. 이들을 게이트에 넣으면 `make verify`가 네트워크와 대부분의 기여자에게 없는 하드웨어에 의존하게 된다. + +### fetch한 트리를 신뢰하지 않기 + +git은 `..` 트리 항목을 그대로 저장하고 fetch는 기본적으로 fsck를 하지 않는다. 그래서 악의적인 fork 커밋(또는 `--fork-url`)이 `sync`나 `export-tree`로 하여금 overlay 밖, 예컨대 `mlx/backend/rocm/../../../../.bashrc`에 쓰게 할 수 있었다. 보안 리뷰가 조작한 트리로 이를 재현했다. 이제 트리에서 온 경로에 대한 모든 쓰기와 삭제는 `safe_dest`를 거치고, 트리 목록은 `-z`를 쓰며, 옵션처럼 보이는 fetch 인자는 거부한다(`51b142fc`, `0119aee9`). 테스트는 `git mktree`로 그런 트리를 만들어 확인한다. + +## 8. 검증 + +PR 작성자 (gfx1151): + +- 새로 fetch한 캐시로 기록된 fork 커밋에 대해 `sync_from_fork.sh --check`를 실행했고 `patches-rocm/`가 byte 단위로 재현되었다. 이는 항등 변환이므로(3.4절) 작성자는 이전 fork 커밋 `53cbdf8c`(이후 34개 파일 변경)를 가리키는 사본에서 forward sync도 돌렸다. 30개 파일이 깨끗이 머지되었고 4개가 로컬 수정과의 실제 상호작용으로 표시되었다. +- 기록된 커밋에 대한 drift 통과: core 15개 중 11개 byte 단위 일치, residual은 항목 1과 24. +- 각 패키지의 `75915908`에 대한 `git apply --check`(07은 05, 06 이후)와 순차 `git am`. PR 본문 검증 줄은 "all ten"이라고 쓰는데, 패키지 11은 그 뒤에 추가되었고 해당 커밋은 단독으로도, 01~10 위에서도 적용된다고 기록한다. +- `cargo test --features rocm --test dead_doc_pointers` 통과. + +오케스트레이터 검증 (gfx1151, `c5a71cfa` 위 `53c8f122`): + +- `make verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt verify-rocm-overlay` 통과. records 검사는 백엔드 108개와 core 15개, LOCAL_FIXES 27개 항목, note가 있는 residual core 파일 4개, pin `81ba1c6a`를 보고했다. +- `scripts/mlxcelverse/rocm_overlay_test.sh` 29개 검사 통과: 정상 overlay의 records와 drift, `sync --check`, forward sync, fork 충돌, pin보다 앞선 fork, `sync`와 `export-tree` 양쪽의 `..` 트리 항목, pin bump와 retarget, 이미 잘못된 overlay, 기록되지 않은 백엔드 변경(다른 곳의 같은 이름 파일로만 명시된 경우 포함), `.DS_Store`, 번호가 빠진 LOCAL_FIXES, 틀린 README 수, 엉뚱한 기록 파일, 합성 빌드 로그에 대한 `api-report`. +- 이 PR에서는 전체 테스트 스위트를 다시 돌리지 않았다. scripts와 docs 밖의 diff는 `rope.hip`의 주석 변경과 어떤 빌드도 컴파일하지 않는 `docs/` 아래 `.hip` 재현 파일뿐이라, 스위트는 바뀌지 않은 코드만 돌렸을 것이다. 게다가 호스트에서 GPU 측정 유닛 두 개가 돌고 있었다. +- 오케스트레이터는 유닛의 `c5a71cfa` rebase와 항목 27 커밋이 push되지 않은 것을 발견해 `--force-with-lease`로 push했고, PR 본문의 패키지 수를 고쳤다. + +## 9. 학습 포인트 + +- **개수 검사는 이동을 확인할 뿐 정확성을 확인하지 않는다.** bump 전후의 +/- 줄 수 비교는 delta가 보존되었다는 것만 말해 준다. 정확성을 확인하려면 파일이 어떠해야 하는지에 대한 기준이 필요하고, 여기서는 그 기준을 만들 수 있다: pin + fork의 자기 base 대비 delta. +- **리뷰한 예외 목록 자체를 산출물로 만든다.** residual은 작고(파일 4개, LOCAL_FIXES 항목 2개) hunk마다 주석이 있어서, 매 bump마다 사람이 다시 해야 할 리뷰가 한 번 기록되고 무언가 바뀔 때만 다시 요구된다. +- **항등 검사는 항등 검사라고 밝혀야 한다.** 기록된 커밋에 대한 `sync --check`는 구조상 byte 단위로 일치한다. 절차 문서 첫 버전은 이것이 절차 밖에서 바뀐 overlay를 잡을 수 있다고 적었고, 리뷰가 이를 고쳤다. 쓸모 있는 동기화 증거는 이전 커밋에서의 forward sync가 되었다. +- **이름 매칭은 보안에 영향을 주는 휴리스틱이다.** 파일 이름만으로 "기록됨"을 인정하자 가장 자주 수정되는 백엔드 파일들이 조용히 면제되었다. 변경이 문서화되었는지 판단하는 검사도 변경이 허용되는지 판단하는 검사만큼 신중해야 한다. +- **fetch한 git 트리의 경로는 입력이다.** fetch만 하는 도구도 남의 트리에서 나온 경로로 파일을 쓴다. 그 경로는 신뢰하지 않아야 한다. + +## 10. 검증하지 않은 것 + +구현 세션에서 auto 모드 권한 검사가 fork 코드 빌드를 거부했다. 그 결과: + +- **`check_api_drift.sh`를 끝까지 실행하지 않았다.** "fork의 merge base + 현재 upstream에 대해 알려진 여섯 개의 깨짐을 나열한다"는 수락 조건은 확인되지 않았다. AMD 호스트에서 실행할 명령은 `scripts/mlxcelverse/check_api_drift.sh --rocm-from fork:75915908dfe5028335d318b10340313744fd3a8d`다. `api-report`는 테스트의 합성 빌드 로그로만 검증되었다. +- **어떤 패키지도 fork에 대고 컴파일하지 않았다.** fork의 MLX base는 mlxcel의 pin보다 오래되었으므로 각 패치가 적어도 거기서 컴파일되는지 확인해야 한다. 패키지 03은 `add_kernel_node`에 컴파일 타임 인자 크기 검사를 추가하는데, mlxcel이 컴파일한 적 없는 fork 호출 지점이 여기서 걸릴 수 있다. +- **fork 빌드에서 재현 스크립트를 실행하지 않았다**(패치 전후 모두). 스크립트는 각 수정을 검증한 mlxcel 테스트를 따른다. 패치 전 일부 케이스는 GPU 큐 fault를 일으키므로, 해당 스크립트는 케이스마다 타임아웃이 있는 자식 프로세스에서 실행한다. +- fork 템플릿이 요구하는 **`pre-commit run --all-files`**를 패치에 대해 돌리지 않았다. + +색인은 이 네 가지를 각 PR 제출 전 단계로 적어 둔다. 별도로, Metal과 CUDA는 이 호스트에서 돌리지 못했다. PR은 Metal이나 CUDA 코드를 건드리지 않고, `verify-rocm-overlay`는 순수 Python과 git이다. + +## 11. 남은 작업 + +- 각 제출 전: 패치를 적용한 fork 빌드, 적용 전후 재현 실행, `pre-commit`, `pr.md`를 메인테이너 자신의 말로 다시 쓰기, AI disclosure 결정. +- 각 제출 후: 색인에 링크를 기록하고 해당 LOCAL_FIXES 항목에 "Proposed upstream: "를 추가. scale-dispatch 수정(패키지 01)에 대한 이슈의 수락 조건은 그때 충족된다. +- AMD 호스트에서 `check_api_drift.sh --rocm-from fork:75915908...`를 한 번 실행해 알려진 여섯 개의 깨짐을 확인. +- 항목 7은 fork가 #3742 이후의 MLX를 머지하면, 항목 15는 #4035 이후를 머지하면, 항목 9는 근본 원인이 밝혀지면 패키지로 만든다. +- fork 동기화 후에는 fork가 흡수한 패키지를 지우고 나머지를 새 head 기준으로 다시 만든다. + +참고: #1813 (이 PR로 닫힘), #1801, #1802, PR #1818, PR #1819, #1811, PR #2079, #2072, TECHNICAL_REPORTS/1772, ml-explore/mlx#2300, ml-explore/mlx#4331, ml-explore/mlx#3742, ml-explore/mlx#4035.