From 17860b6c01757a07f4383f581aa963c214f8adc1 Mon Sep 17 00:00:00 2001 From: ethenotethan <42627790+ethenotethan@users.noreply.github.com> Date: Mon, 14 Sep 2026 04:28:49 +0700 Subject: [PATCH] feat(forkdiff): publish a fork-diff page and gate it on the analysis staying true MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Layr-Labs/mlx is a fork of ml-explore/mlx; nothing recorded what it changes or which upstream commit it sits on. Adopt protolambda/forkdiff the way op-geth does for go-ethereum: `fork.yaml` names the upstream base (77a0c1e8, upstream main 2026-08-14) and groups every changed file into a described section — Metal eval use-after-free fix, sorted expert-tile quantized matmul (E=128/E=256) with diagnostics, GPT-OSS MXFP4 masked-tail decode, coherent allocator accounting, FP32 SDPA partials, declared-mutable custom-kernel inputs, cross-thread compile-cache cleanup — plus one honest section for the 131 files that are byte-identical to upstream v0.32.2 and only look like fork changes because PR #10 applied them instead of merging. `forkdiff-pages.yml` renders and deploys the page to GitHub Pages on push to main (skipping the deploy with a notice until an admin enables Pages). `scripts/check_forkdiff.py` runs on every PR and push (`forkdiff-check.yml`) and fails when base.hash is not merge-base(HEAD, upstream/main) — which is exactly what a rebase changes — or when a changed file is undescribed, or a section names files the fork no longer changes. The same check runs before publishing so a stale page is never served. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/forkdiff-check.yml | 76 ++++++++ .github/workflows/forkdiff-pages.yml | 99 ++++++++++ FORKDIFF.md | 80 ++++++++ README.md | 2 + fork.yaml | 278 +++++++++++++++++++++++++++ scripts/check_forkdiff.py | 259 +++++++++++++++++++++++++ 6 files changed, 794 insertions(+) create mode 100644 .github/workflows/forkdiff-check.yml create mode 100644 .github/workflows/forkdiff-pages.yml create mode 100644 FORKDIFF.md create mode 100644 fork.yaml create mode 100644 scripts/check_forkdiff.py diff --git a/.github/workflows/forkdiff-check.yml b/.github/workflows/forkdiff-check.yml new file mode 100644 index 0000000000..67f75cc69e --- /dev/null +++ b/.github/workflows/forkdiff-check.yml @@ -0,0 +1,76 @@ +name: Fork Diff Check + +# Fails a PR whose `fork.yaml` no longer describes this fork. +# +# The fork-diff page (https://layr-labs.github.io/mlx/, rendered by +# protolambda/forkdiff from `fork.yaml`, deployed by forkdiff-pages.yml) is +# only useful while it is true, and two things make it go stale silently: +# +# 1. A rebase onto newer upstream. `base.hash` keeps pointing at the old +# upstream commit, so the page shows upstream's own changes as the fork's. +# `scripts/check_forkdiff.py` requires base.hash == merge-base(HEAD, +# upstream/main); a rebase moves the merge-base and the gate stays red +# until the hash — and the sections — are brought up to date. +# 2. A fork change nobody described. Every file in the base..HEAD diff must +# match a section glob (or a global ignore), and every glob must still +# match something. +# +# The page is also rendered here so a fork.yaml that forkdiff itself rejects +# cannot merge. See FORKDIFF.md. + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + analysis-up-to-date: + name: fork.yaml describes the fork + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # full history: merge-base with upstream, and forkdiff diffs against base.hash + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx.git \ + main:refs/remotes/upstream/main + echo "upstream/main = $(git rev-parse --short refs/remotes/upstream/main)" + echo "merge-base = $(git merge-base HEAD refs/remotes/upstream/main | cut -c1-12)" + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Verify fork.yaml against the real diff + run: | + python3 -m pip install --quiet pyyaml + python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Render the fork-diff page + # fork.yaml names refs/heads/main; on a PR the checkout is a detached + # merge commit, so point the local branch at what we are checking. + run: | + git update-ref refs/heads/main HEAD + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + echo "rendered $(wc -c < tmp/pages/index.html) bytes" + + - name: Upload rendered page + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 7 diff --git a/.github/workflows/forkdiff-pages.yml b/.github/workflows/forkdiff-pages.yml new file mode 100644 index 0000000000..0bc606f255 --- /dev/null +++ b/.github/workflows/forkdiff-pages.yml @@ -0,0 +1,99 @@ +name: Deploy Fork Diff + +# Renders `fork.yaml` with protolambda/forkdiff and publishes the result as the +# repository's GitHub Pages site — the same setup ethereum-optimism/op-geth +# uses for its go-ethereum fork diff. Runs the analysis gate first, so a page +# that lies about the fork is never published. + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: "pages" + cancel-in-progress: true + +jobs: + deploy: + name: Render and deploy + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 # forkdiff diffs against base.hash, deep in history + + - name: Fetch upstream main + run: | + git fetch --no-tags --quiet https://github.com/ml-explore/mlx.git \ + main:refs/remotes/upstream/main + + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Refuse to publish a stale analysis + run: | + python3 -m pip install --quiet pyyaml + python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main + + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version: "1.24" + cache: false + + - name: Build forkdiff + run: | + mkdir -p tmp/pages + go run github.com/protolambda/forkdiff@v0.1.1 \ + -repo . -fork fork.yaml -out tmp/pages/index.html + touch tmp/pages/.nojekyll + + - name: Is GitHub Pages enabled? + # Pages must be switched on once by a repo admin (Settings → Pages → + # Source: "GitHub Actions"). The workflow token cannot do that itself + # (`configure-pages` enablement needs an admin PAT), so until then the + # page is built and kept as an artifact but not deployed — a notice, + # not a red run. + id: pages + env: + GH_TOKEN: ${{ github.token }} + run: | + if gh api "repos/${GITHUB_REPOSITORY}/pages" --silent 2>/dev/null; then + echo "enabled=true" >> "$GITHUB_OUTPUT" + else + echo "enabled=false" >> "$GITHUB_OUTPUT" + echo "::notice::GitHub Pages is not enabled for ${GITHUB_REPOSITORY}; built the page but skipped the deploy. Enable it once under Settings → Pages (Source: GitHub Actions) and re-run this workflow." + fi + + - name: Keep the rendered page as an artifact + if: steps.pages.outputs.enabled != 'true' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: forkdiff-page + path: tmp/pages/index.html + retention-days: 30 + + - name: Setup Pages + if: steps.pages.outputs.enabled == 'true' + uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0 + + - name: Upload artifact + if: steps.pages.outputs.enabled == 'true' + uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3.0.1 + with: + path: tmp/pages + + - name: Deploy to GitHub Pages + if: steps.pages.outputs.enabled == 'true' + id: deployment + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5 diff --git a/FORKDIFF.md b/FORKDIFF.md new file mode 100644 index 0000000000..61f3007e77 --- /dev/null +++ b/FORKDIFF.md @@ -0,0 +1,80 @@ +# Fork diff: what this fork changes, and keeping that page honest + +This repository is a fork of [`ml-explore/mlx`](https://github.com/ml-explore/mlx). +Everything it changes relative to upstream is published as a browsable page: + +**https://layr-labs.github.io/mlx/** + +The page is rendered by [`protolambda/forkdiff`](https://github.com/protolambda/forkdiff) +from [`fork.yaml`](fork.yaml) at the repo root, in the style of +[op-geth's go-ethereum fork diff](https://op-geth.optimism.io/). `fork.yaml` +groups the changed files into sections with a paragraph each, names the exact +upstream commit the fork is based on (`base.hash`), and lists files that are +not code (`ignore`). Every push to `main` re-renders and redeploys it +(`.github/workflows/forkdiff-pages.yml`). + +**One-time setup.** GitHub Pages has to be switched on by a repo admin: +Settings → Pages → Source: **GitHub Actions**. The workflow token cannot do +this itself. Until it's done the deploy workflow still builds the page (kept +as a run artifact, `forkdiff-page`) and exits with a notice instead of failing. + +## The gate + +A fork-diff page is only useful while it is true, and two things make it go +stale silently. `scripts/check_forkdiff.py` runs on every PR and on every push +to `main` (`.github/workflows/forkdiff-check.yml`) and fails on both: + +| Drift | Check | Why it matters | +|-------|-------|----------------| +| **Rebase onto newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a rebase the old base makes upstream's own commits look like fork changes: thousands of files, none of them ours. | +| **New fork change nobody described** | every path in `git diff --name-only base.hash HEAD` must match a section glob or a global `ignore` | An undescribed file is a change the page can't explain. | +| **Section describing code we no longer carry** | every glob must match at least one changed path | Stale sections are as misleading as missing ones. | + +The check also renders the page, so a `fork.yaml` that forkdiff itself rejects +cannot merge. The deploy workflow runs the same check before publishing, so a +stale analysis is never served. + +## Day to day + +**Adding or changing fork files in a PR.** If the check lists uncovered files, +add each to the section that explains it in `fork.yaml` (or start a new +section with a short description). Files that are not code go under the +top-level `ignore`. Keep globs specific: a `mlx/**` catch-all would swallow +upstream's changes after a bad rebase and defeat the gate. + +**Rebasing onto newer upstream.** The gate will fail with the new merge-base +in its message: + +``` +git fetch https://github.com/ml-explore/mlx.git main:refs/remotes/upstream/main +git merge-base HEAD refs/remotes/upstream/main # → new base.hash +``` + +Set `base.hash` to that value, then run the check locally and fix what it +reports — usually files upstream absorbed (stale globs to delete) and files +that moved (globs to rename). In particular, the "Upstream v0.32.2 sync" +section exists only because the fork applied upstream's v0.32.2 changes +instead of merging them; a rebase onto a commit at or past v0.32.2 makes it +disappear. + +``` +python3 -m pip install pyyaml +python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main +``` + +**Previewing the page locally** (Go 1.21+): + +``` +go run github.com/protolambda/forkdiff@v0.1.1 -repo . -fork fork.yaml -out tmp/index.html +open tmp/index.html +``` + +## Design notes + +- `base.hash` is a full 40-hex commit id, never a branch name: a symbolic base + would move underneath the page and the gate alike. +- Section `ignore` lists count as coverage (forkdiff still lists those files, + grayed out); the top-level `ignore` is for things that aren't code at all. +- The glob semantics are forkdiff's: `*` and `?` stop at `/`, `**` spans + directories (and may match none), `[!x]` negates a class. +- The check is pure git + PyYAML so the same command runs locally and in CI. diff --git a/README.md b/README.md index fb30a24f2c..b316d5a61b 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ [![CircleCI](https://circleci.com/gh/ml-explore/mlx.svg?style=svg)](https://circleci.com/gh/ml-explore/mlx) +> **This is a fork.** `Layr-Labs/mlx` tracks [`ml-explore/mlx`](https://github.com/ml-explore/mlx) and carries the kernel, allocator and Metal-runtime work behind Layr-Labs' Apple-silicon inference stack (`mlx` → `mlx-c` → `mlx-swift` → `mlx-swift-lm`). Everything changed relative to upstream is published as a fork diff at **https://layr-labs.github.io/mlx/**, described in [`fork.yaml`](fork.yaml) and kept honest by CI — see [FORKDIFF.md](FORKDIFF.md). + MLX is an array framework for machine learning on Apple silicon, brought to you by Apple machine learning research. diff --git a/fork.yaml b/fork.yaml new file mode 100644 index 0000000000..5e4fa0916a --- /dev/null +++ b/fork.yaml @@ -0,0 +1,278 @@ +title: "Layr-Labs/mlx - MLX fork diff overview" +footer: | + Fork-diff overview of [`Layr-Labs/mlx`](https://github.com/Layr-Labs/mlx), a fork of + [`ml-explore/mlx`](https://github.com/ml-explore/mlx) · created with + [Forkdiff](https://github.com/protolambda/forkdiff) +base: + name: ml-explore/mlx + url: https://github.com/ml-explore/mlx + # The upstream commit this fork is based on. CI (`scripts/check_forkdiff.py`) + # requires this to equal `git merge-base HEAD upstream/main`, so a rebase onto + # newer upstream fails the gate until the hash — and the sections below — are + # brought up to date. Upstream main as of 2026-08-14. + hash: 77a0c1e8ae16eb781a79e2b7134ba84b2ee7b597 +fork: + name: Layr-Labs/mlx + url: https://github.com/Layr-Labs/mlx + ref: refs/heads/main +def: + title: "Layr-Labs/mlx" + description: | + This is an overview of the changes in [`Layr-Labs/mlx`](https://github.com/Layr-Labs/mlx), + a fork of [`ml-explore/mlx`](https://github.com/ml-explore/mlx). + + The fork is the core of Layr-Labs' Apple-silicon inference stack — `mlx` → `mlx-c` → + `mlx-swift` → `mlx-swift-lm` — and carries the kernel, allocator and Metal-runtime work + that serving production MoE models (Gemma 4, Qwen 3.5/3.6, GPT-OSS) needed before or + beyond what upstream ships: sorted expert-tile quantized matmul routes, a masked-tail + MXFP4 decode kernel, FP32-safe SDPA partials, coherent allocator accounting for admission + control, declared-mutable custom-kernel inputs for paged KV, and a use-after-free fix in + Metal eval. Every change is meant to be additive and rebasable; each is gated by shape, + device or environment checks so the upstream path stays the default elsewhere. + + One section is not fork work at all: the fork carries upstream's own v0.32.2 changes + (applied in PR #10 rather than merged), and those files are listed as such so the page + stays honest about what Layr-Labs actually changed. + sub: + - title: "Metal eval: use-after-free with mid-eval synchronization" + description: | + `gpu::eval` captured the `MTL::CommandBuffer*` before `eval_gpu` ran and attached the + input-buffer liveness handler to it afterwards. Any primitive that calls + `CommandEncoder::synchronize()` mid-eval — the expert-tile route's sortedness-retract + check does — commits and replaces the encoder's buffer, so the handler landed on a + dangling pointer (latent on Gemma E=128, a deterministic SIGSEGV on Qwen E=256). The + buffer is now fetched from the encoder *after* `eval_gpu`, so inputs outlive exactly the + tail of the primitive's work. (PR #5) + globs: + - "mlx/backend/metal/eval.cpp" + - title: "Sorted expert-tile quantized matmul (Gemma 4 E=128, Qwen 3.5/3.6 E=256)" + description: | + An opt-in route (`MLX_GATHER_QMM_EXPERT_SLICES=1|trust`) for gathered, affine-quantized + MoE expert matmuls: a descriptor kernel builds sorted expert tiles on device (one + instantiation per expert count) and a single expert-count-agnostic tile kernel consumes + them. `classify_gemma4_expert_qmm` is a pure route table admitting exactly the shapes + the kernel is built for; availability is all-or-nothing on a source-matched metallib so + an older library fails the route closed; `trust` skips the descriptor-retract readback + when the caller guarantees sorted indices. Diagnostics counters + (`mlx_metal_gemma4_expert_qmm_diagnostics_*`) are exposed through a C ABI so mlx-c / + mlx-swift can arm, snapshot and reset them. Also in these kernels: every affine + quantized-vector bias-sum operand is promoted to the accumulator type before summation + (PR #15). + globs: + - "mlx/backend/common/gemma4_expert_qmm.h" + - "mlx/backend/metal/device.h" + - "mlx/backend/metal/device.cpp" + - "mlx/backend/metal/kernels/quantized.h" + - "mlx/backend/metal/kernels/quantized.metal" + - "tests/gpu_tests.cpp" + - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" + description: | + GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's + 512-element alignment and fell to the general path. `fp_gather_qmv_fast_tail` runs five + full blocks plus a 320-value tail read only by the participating lanes, preserving FP32 + accumulation and the gathered indices/strides. It is enabled automatically only on the + physical M4 Max architecture (`applegpu_g16s`) for the exact MXFP4/group-32/4-bit, + E=32, K=2880, N=2880|5760, FP32/BF16 shape; `MLX_GPTOSS_MXFP4_DECODE_FAST_TAIL=0` + restores the original route and `MLX_GPTOSS_MXFP4_PREFILL_TILE=m32n32k32` opts into a + separately measured prefill tile (`gptoss_mxfp4_policy.h`). (PR #14) + globs: + - "mlx/backend/metal/gptoss_mxfp4_policy.h" + - "mlx/backend/metal/kernels/fp_quantized.h" + - "mlx/backend/metal/kernels/fp_quantized.metal" + - "mlx/backend/metal/quantized.cpp" + - "tests/gptoss_mxfp4_tests.cpp" + - "tests/CMakeLists.txt" + - title: "Coherent allocator accounting for admission control" + description: | + Admission accounting used to combine independent reads of the allocator counters with + logical buffer sizes, so concurrent allocator activity could produce an incoherent + snapshot and alignment / cache reuse could make the real backing larger than the + request. `get_memory_snapshot()` reads active / cache / peak under one lock; + `get_allocation_size_upper_bound()` and the detached, lock-free + `AllocationFootprintPolicy` bound a buffer including alignment and the (now inclusive, + overflow-checked) cache-reuse limit shared with `BufferCache`. Metal, CPU and CUDA + allocators implement the same interface; the allocator's own behaviour stays the + authority. These describe allocator accounting, not process RSS. (PR #15) + globs: + - "mlx/memory.h" + - "mlx/backend/common/allocation_footprint.h" + - "mlx/backend/common/buffer_cache.h" + - "mlx/backend/metal/allocator.h" + - "mlx/backend/metal/allocator.cpp" + - "mlx/backend/cuda/allocator.h" + - "mlx/backend/cuda/allocator.cpp" + - "mlx/backend/no_gpu/allocator.cpp" + - "tests/allocator_tests.cpp" + - title: "FP32 partial sums in two-pass vector SDPA" + description: | + The two-pass vector SDPA cast unnormalized partial sums to the input dtype before + combining them: BF16 lost cancellation residuals and FP16 could overflow even when the + final output was representable. Partials now stay FP32 through the second pass and only + the final result is cast; kernel entry names change so a stale shader cannot silently + satisfy the new buffer contract. Python regressions cover cancellation and overflow + across D64/D128/D256, 32/128 partitions, masked and unmasked. (PR #16) + globs: + - "mlx/backend/metal/kernels/sdpa_vector.h" + - "mlx/backend/metal/kernels/scaled_dot_product_attention.metal" + - "mlx/backend/metal/scaled_dot_product_attention.cpp" + - "python/tests/test_fast_sdpa.py" + - title: "Declared-mutable inputs for Metal custom kernels" + description: | + `metal_kernel_with_mutable_inputs` lets a caller declare which custom-kernel inputs will + be written, so paged-KV consumers keep writes on the original allocation and Metal sees + the read/write hazard. Mutable names must identify exactly one input; mutable `device` + pointers are generated (including for small/scalar storage) and take part in the + compiled-kernel identity; an implicit contiguous copy of declared-mutable storage is + rejected; allocations are registered for writes as well as reads. A separate + `MutableInputCustomKernel` primitive serializes the declaration while the existing + `CustomKernel` export schema is untouched. (PR #18) + globs: + - "mlx/fast.h" + - "mlx/fast_primitives.h" + - "mlx/backend/common/metal_kernel.cpp" + - "mlx/backend/metal/custom_kernel.cpp" + - "mlx/export.cpp" + - title: "Cross-thread compile-cache cleanup" + description: | + Compile caches became thread-local upstream; bindings built before that (the mlx-c / + mlx-swift consumers) still call the process-wide `compile_erase` / `compile_clear_cache`. + A process-lifetime registry records each thread's cache once at construction so those + entrypoints can erase or clear every live cache, with no per-call hot-path work. (PR #10) + globs: + - "mlx/compile.cpp" + - "mlx/compile_impl.h" + - "tests/compile_tests.cpp" + - title: "Upstream v0.32.2 sync carried in PR #10" + description: | + **Not fork work.** PR #10 moved the fork from an 0.32.0-era upstream main to official + v0.32.2 by applying upstream's changes rather than merging them, so `git` sees them as + fork commits even though every file below is byte-identical to upstream `v0.32.2` + (CUDA backend, CPU SIMD, kernels, Python bindings and tests, repository CI and + templates, `AGENTS.md` / `CLAUDE.md`, docs). Listed here so the page does not credit + Layr-Labs with upstream's changes; the section disappears once the fork rebases onto + an upstream commit at or past v0.32.2. + globs: + - ".pre-commit-config.yaml" + - "AGENTS.md" + - "CLAUDE.md" + - "CMakeLists.txt" + - "CONTRIBUTING.md" + - "setup.py" + - ".github/pull_request_template.md" + - ".github/ISSUE_TEMPLATE/*" + - ".github/actions/build/action.yml" + - ".github/actions/build-macos/action.yml" + - ".github/actions/build-wheel/action.yml" + - ".github/actions/setup/action.yml" + - ".github/actions/test-linux/action.yml" + - ".github/actions/test-macos/action.yml" + - ".github/actions/test-wheel/action.yml" + - ".github/actions/test-windows/action.yml" + - ".github/scripts/*" + - ".github/workflows/build_and_test.yml" + - ".github/workflows/release.yml" + - ".github/workflows/update_bypass_list.yml" + - "benchmarks/python/sdpa_bench.py" + - "docs/src/install.rst" + - "docs/src/python/fast.rst" + - "examples/extensions/*" + - "mlx/array.h" + - "mlx/einsum.cpp" + - "mlx/error.h" + - "mlx/event.h" + - "mlx/fast.cpp" + - "mlx/fence.h" + - "mlx/fft.cpp" + - "mlx/ops.cpp" + - "mlx/ops.h" + - "mlx/primitives.cpp" + - "mlx/primitives.h" + - "mlx/scheduler.cpp" + - "mlx/scheduler.h" + - "mlx/version.h" + - "mlx/backend/common/load.cpp" + - "mlx/backend/cpu/*" + - "mlx/backend/cpu/simd/base_simd.h" + - "mlx/backend/cuda/CMakeLists.txt" + - "mlx/backend/cuda/cross_entropy.cu" + - "mlx/backend/cuda/cuda_utils.h" + - "mlx/backend/cuda/custom_kernel.cpp" + - "mlx/backend/cuda/delayload.cpp" + - "mlx/backend/cuda/device.cpp" + - "mlx/backend/cuda/device.h" + - "mlx/backend/cuda/dirs.cpp" + - "mlx/backend/cuda/event.cu" + - "mlx/backend/cuda/event.h" + - "mlx/backend/cuda/fence.cpp" + - "mlx/backend/cuda/jit_module.cpp" + - "mlx/backend/cuda/scaled_dot_product_attention.cpp" + - "mlx/backend/cuda/device/binary_ops.cuh" + - "mlx/backend/metal/compiled.cpp" + - "mlx/backend/metal/conv.cpp" + - "mlx/backend/metal/event.cpp" + - "mlx/backend/metal/event.h" + - "mlx/backend/metal/fence.cpp" + - "mlx/backend/metal/jit_kernels.cpp" + - "mlx/backend/metal/kernels.h" + - "mlx/backend/metal/nojit_kernels.cpp" + - "mlx/backend/metal/normalization.cpp" + - "mlx/backend/metal/primitives.cpp" + - "mlx/backend/metal/kernels/binary_ops.h" + - "mlx/backend/metal/kernels/copy.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.metal" + - "mlx/backend/metal/kernels/fp8.h" + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/quantized_nax.metal" + - "mlx/backend/metal/kernels/rms_norm.metal" + - "mlx/backend/metal/kernels/sort.h" + - "mlx/backend/metal/kernels/utils.h" + - "mlx/backend/metal/kernels/reduction/*" + - "mlx/backend/metal/kernels/steel/attn/kernels/*" + - "mlx/backend/no_gpu/event.cpp" + - "mlx/backend/no_gpu/fence.cpp" + - "mlx/backend/no_gpu/primitives.cpp" + - "mlx/distributed/mpi/mpi.cpp" + - "mlx/distributed/ring/ring.cpp" + - "mlx/io/gguf.cpp" + - "python/mlx/*" + - "python/mlx/_distributed_utils/launch.py" + - "python/mlx/nn/losses.py" + - "python/mlx/nn/layers/normalization.py" + - "python/mlx/optimizers/optimizers.py" + - "python/src/*" + - "python/tests/__main__.py" + - "python/tests/mlx_tests.py" + - "python/tests/run.py" + - "python/tests/test_array.py" + - "python/tests/test_compile.py" + - "python/tests/test_conv_transpose.py" + - "python/tests/test_conv.py" + - "python/tests/test_double.py" + - "python/tests/test_einsum.py" + - "python/tests/test_eval.py" + - "python/tests/test_fast.py" + - "python/tests/test_fft.py" + - "python/tests/test_load.py" + - "python/tests/test_nn.py" + - "python/tests/test_ops.py" + - "python/tests/test_quantized.py" + - "python/tests/test_reduce.py" + - "python/tests/test_vmap.py" + - "tests/load_tests.cpp" + - "tests/ops_tests.cpp" + - title: "Fork tooling" + description: | + The gate that keeps this page honest: `check_forkdiff.py` fails CI when `base.hash` is + not the merge-base with upstream, when a file the fork changes is not described by a + section above, or when a section names files the fork no longer changes. + globs: + - "scripts/check_forkdiff.py" + - "FORKDIFF.md" + - "README.md" + +# ignored globally, does not count towards line count +ignore: + - "fork.yaml" + - ".github/workflows/forkdiff-check.yml" + - ".github/workflows/forkdiff-pages.yml" diff --git a/scripts/check_forkdiff.py b/scripts/check_forkdiff.py new file mode 100644 index 0000000000..8e10e811d6 --- /dev/null +++ b/scripts/check_forkdiff.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Gate: ``fork.yaml`` must describe this fork as it is *now*. + +The fork-diff page (rendered with protolambda/forkdiff and published on GitHub +Pages) is only useful while it is true. Two things make it go stale silently: + +1. **A rebase onto newer upstream.** ``base.hash`` still points at the old + upstream commit, so the page shows upstream's own changes as if the fork + made them. This script requires ``base.hash`` to equal + ``git merge-base HEAD ``; a rebase moves the merge-base, and the + gate stays red until the hash is bumped. +2. **A new fork change nobody described.** Every path in + ``git diff --name-only base.hash HEAD`` must match a glob in some section + (or a global ``ignore``), and every glob must still match something — a + section describing code the fork no longer carries is as misleading as a + missing one. + +Both are pure git + YAML, so the same check runs locally:: + + python3 scripts/check_forkdiff.py # coverage only + python3 scripts/check_forkdiff.py --upstream-ref upstream/main + +Exit status is non-zero on any violation. ``--review-status-out`` writes the +JSON the CI comment synthesizer consumes (same shape as history-check). +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path +from typing import Iterable + +import yaml + +GLOB_CLASS_RE = re.compile(r"\[([^\]]*)\]") + + +def glob_to_regex(glob: str) -> re.Pattern[str]: + """Translate a forkdiff glob into a regex over the repo-relative path. + + Semantics follow the doublestar rules forkdiff uses: ``*`` and ``?`` never + cross a ``/``; ``**`` matches any number of directories (``a/**/b`` also + matches ``a/b``); ``[...]`` character classes pass through, with a leading + ``!`` meaning negation. + """ + out: list[str] = [] + i = 0 + while i < len(glob): + c = glob[i] + if c == "*": + if glob.startswith("**", i): + if glob.startswith("**/", i): + out.append("(?:.*/)?") + i += 3 + continue + out.append(".*") + i += 2 + continue + out.append("[^/]*") + elif c == "?": + out.append("[^/]") + elif c == "[": + end = glob.find("]", i + 1) + if end == -1: + out.append(re.escape(c)) + else: + cls = glob[i + 1 : end] + if cls.startswith("!"): + cls = "^" + cls[1:] + out.append("[" + cls + "]") + i = end + 1 + continue + else: + out.append(re.escape(c)) + i += 1 + return re.compile("^" + "".join(out) + "$") + + +def collect_globs(node: dict, path: str = "def") -> list[tuple[str, str]]: + """Every glob in the section tree as ``(section path, glob)``. + + A section's ``ignore`` list counts as coverage too: forkdiff still lists + those files under the section (grayed out), so they are described. + """ + found: list[tuple[str, str]] = [] + title = node.get("title") or "(untitled)" + here = f"{path} › {title}" if path != "def" else title + for g in node.get("globs") or []: + found.append((here, str(g))) + for g in node.get("ignore") or []: + found.append((here, str(g))) + for child in node.get("sub") or []: + found.extend(collect_globs(child, here)) + return found + + +def git(*args: str, cwd: Path) -> str: + result = subprocess.run( + ["git", *args], cwd=cwd, capture_output=True, text=True, check=False + ) + if result.returncode != 0: + raise RuntimeError(f"git {' '.join(args)} failed: {result.stderr.strip()}") + return result.stdout.strip() + + +def changed_paths(repo: Path, base: str, head: str) -> list[str]: + out = git("diff", "--name-only", f"{base}..{head}", cwd=repo) + return [line for line in out.splitlines() if line] + + +def check_coverage( + paths: Iterable[str], globs: list[tuple[str, str]] +) -> tuple[list[str], list[tuple[str, str]], dict[str, int]]: + """Return ``(uncovered paths, stale globs, matches per glob)``.""" + compiled = [(section, g, glob_to_regex(g)) for section, g in globs] + hits: dict[str, int] = {g: 0 for _, g in globs} + uncovered: list[str] = [] + for p in paths: + matched = False + for _, g, rx in compiled: + if rx.match(p): + hits[g] += 1 + matched = True + if not matched: + uncovered.append(p) + stale = [(section, g) for section, g in globs if hits[g] == 0] + return uncovered, stale, hits + + +def check_base(repo: Path, base: str, head: str, upstream_ref: str | None) -> list[str]: + problems: list[str] = [] + if not re.fullmatch(r"[0-9a-f]{40}", base): + problems.append( + f"base.hash must be a full 40-hex commit id, got {base!r} — a short or " + "symbolic ref would silently move under the page." + ) + return problems + try: + git("cat-file", "-e", f"{base}^{{commit}}", cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not present in this repository. The fork must " + "sit on top of it (fetch upstream if the clone is shallow)." + ) + return problems + if upstream_ref is None: + return problems + try: + git("merge-base", "--is-ancestor", base, upstream_ref, cwd=repo) + except RuntimeError: + problems.append( + f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must name " + "a commit on upstream main, not a fork commit." + ) + merge_base = git("merge-base", head, upstream_ref, cwd=repo) + if merge_base != base: + problems.append( + f"base.hash {base[:12]} != merge-base({head}, {upstream_ref}) = " + f"{merge_base[:12]}. The fork was rebased onto newer upstream; update " + "fork.yaml's base.hash and re-describe the sections (see docs/forkdiff.md)." + ) + return problems + + +def review_status(problems: list[str], detail: str) -> list[dict]: + if not problems: + return [] + return [ + { + "source": "fork diff analysis", + "results": [ + { + "kind": "action_required", + "title": "fork.yaml no longer describes the fork", + "summary": problems[0] + if len(problems) == 1 + else f"{len(problems)} issues: {problems[0]}", + "detail": detail, + "how_to_fix": ( + "See docs/forkdiff.md. After a rebase: set base.hash to " + "`git merge-base HEAD upstream/main`. For new files: add them to " + "the section that explains them (or to a global `ignore` if they " + "are not code). Then run `python3 scripts/check_forkdiff.py " + "--upstream-ref upstream/main` locally." + ), + } + ], + } + ] + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--repo", default=".", help="path to the fork checkout") + ap.add_argument("--fork", default="fork.yaml", help="fork page definition") + ap.add_argument("--head", default="HEAD", help="the fork revision to describe") + ap.add_argument( + "--upstream-ref", + default=None, + help="a ref holding upstream main (e.g. refs/remotes/upstream/main); " + "enables the merge-base check", + ) + ap.add_argument("--review-status-out", default=None, help="write review-status JSON here") + args = ap.parse_args(argv) + + repo = Path(args.repo).resolve() + fork_path = repo / args.fork + spec = yaml.safe_load(fork_path.read_text(encoding="utf-8")) or {} + base = str((spec.get("base") or {}).get("hash") or "").strip() + problems: list[str] = [] + lines: list[str] = [] + + problems += check_base(repo, base, args.head, args.upstream_ref) + + globs = collect_globs(spec.get("def") or {}) + globs += [("(global ignore)", str(g)) for g in spec.get("ignore") or []] + + paths: list[str] = [] + if re.fullmatch(r"[0-9a-f]{40}", base): + try: + paths = changed_paths(repo, base, args.head) + except RuntimeError as exc: + problems.append(str(exc)) + + uncovered, stale, hits = check_coverage(paths, globs) + if uncovered: + problems.append( + f"{len(uncovered)} changed file(s) are not described by any fork.yaml section" + ) + lines.append("Uncovered files (add each to the section that explains it):") + lines += [f" - {p}" for p in uncovered] + if stale: + problems.append(f"{len(stale)} glob(s) match nothing the fork changes") + lines.append("Stale globs (the fork no longer changes anything they name):") + lines += [f" - {g} [{section}]" for section, g in stale] + + covered = len(paths) - len(uncovered) + print(f"fork.yaml: base {base[:12]} head {args.head} changed files {len(paths)} " + f"described {covered} sections+ignores {len(globs)}") + if args.upstream_ref is None: + print(" (no --upstream-ref: merge-base check skipped)") + for line in lines: + print(line) + for p in problems: + print(f"::error::{p}") + + if args.review_status_out: + Path(args.review_status_out).write_text( + json.dumps(review_status(problems, "\n".join(lines))), encoding="utf-8" + ) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main())