diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml new file mode 100644 index 0000000000..f26f9dca29 --- /dev/null +++ b/.github/workflows/fork-tests.yml @@ -0,0 +1,172 @@ +name: Fork Tests + +# Builds the fork and runs its self-contained Metal test suites on a GitHub-hosted +# Mac. These suites use tiny test models. They need no model weights, no +# network access at test time, and no secrets. + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fork-tests-${{ github.ref }} + # A new push to a pull request cancels the older run. Runs on main are not + # cancelled once they start. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build-and-test: + name: Build and test + runs-on: macos-26 + timeout-minutes: 150 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Select an Xcode with Swift 6.3 or newer + id: xcode + # Selects the newest release of Xcode 26. Beta and release candidate + # apps are left out, so a new beta on the runner image cannot change + # CI without a pull request. mlx-swift declares swift-tools-version 6.3. + run: | + ls -d /Applications/Xcode* + version=$(for app in /Applications/Xcode_26.*.app; do + name=${app#/Applications/Xcode_} + name=${name%.app} + if [[ "$name" =~ ^26(\.[0-9]+)+$ ]]; then + echo "$name" + fi + done | sort -t . -k 1,1n -k 2,2n -k 3,3n | tail -n 1) + if [ -z "$version" ]; then + echo "::error::No release of Xcode 26 is on this runner." + exit 1 + fi + sudo xcode-select -s "/Applications/Xcode_$version.app" + xcodebuild -version + swift --version + read -r major minor <<< "$(swift --version 2>&1 | sed -nE 's/.*Swift version ([0-9]+)\.([0-9]+).*/\1 \2/p')" + if ! (( major > 6 || (major == 6 && minor >= 3) )); then + echo "::error::Xcode $version has Swift $major.$minor. mlx-swift needs Swift 6.3 or newer." + exit 1 + fi + xcrun -sdk macosx metal --version + echo "version=$(xcodebuild -version | awk 'NR == 1 { v = $2 } /Build version/ { b = $3 } END { print v "-" b }')" >> "$GITHUB_OUTPUT" + + - name: Show the runner hardware + run: | + sysctl -n machdep.cpu.brand_string hw.ncpu hw.memsize + df -h "$GITHUB_WORKSPACE" + + - name: Restore the SwiftPM cache + id: cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/Library/Caches/org.swift.swiftpm + ~/Library/org.swift.swiftpm + .build + key: spm-${{ runner.os }}-xcode-${{ steps.xcode.outputs.version }}-${{ hashFiles('Package.swift', 'Package.resolved') }}-${{ github.sha }} + restore-keys: | + spm-${{ runner.os }}-xcode-${{ steps.xcode.outputs.version }}- + + - name: Remove cached Metal libraries + # A cached library can come from other MLX sources. A later step + # builds a new one from the current sources. + run: | + if [ -d .build ]; then + find .build -type f -name mlx.metallib -delete + fi + + - name: Build the package and its tests + id: build + run: | + start=$(date +%s) + swift build --build-tests + elapsed=$(( $(date +%s) - start )) + echo "swift build --build-tests took $(( elapsed / 60 )) min $(( elapsed % 60 )) s" + + - name: Build and stage the full Metal library + id: metallib + run: | + start=$(date +%s) + scripts/build-metallib.sh "$RUNNER_TEMP/mlx.metallib" + scripts/stage-test-metallib.sh "$RUNNER_TEMP/mlx.metallib" "$(swift build --show-bin-path)" + elapsed=$(( $(date +%s) - start )) + echo "The Metal library took $(( elapsed / 60 )) min $(( elapsed % 60 )) s" + + # One step for each suite, so the job summary shows which suite failed. + # Each suite step runs when the Metal library step succeeded, also after + # an earlier suite failed. scripts/run-nested-suite.sh fails the step + # when the suite executed zero tests or skipped a test. + + - name: Run CBv2PagedSafetyTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Runs the paged Metal kernels that are compiled at run time. + timeout-minutes: 10 + run: scripts/run-nested-suite.sh CBv2PagedSafetyTests + + - name: Run CBv2PrefixCacheHasherTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Checks the prompt hash of the prefix cache. Pure Swift. + timeout-minutes: 10 + run: scripts/run-nested-suite.sh CBv2PrefixCacheHasherTests + + - name: Run CBv2PagedEligibilityTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Checks the threadgroup memory budget. Pure Swift, no GPU work. + timeout-minutes: 5 + run: scripts/run-nested-suite.sh CBv2PagedEligibilityTests + + - name: Run CBv2PagedBackendTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Checks the page pool, the page tables, the windowed rings, and the + # backend lifecycle. Uses small MLX arrays. + timeout-minutes: 10 + run: scripts/run-nested-suite.sh CBv2PagedBackendTests + + - name: Run CBv2PagedKernelTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Compares the paged decode kernel with an fp32 reference, checks that + # batch composition does not change the output, and runs a 200-step + # greedy decode. The script runs the batch composition test in its + # own process. + timeout-minutes: 20 + run: scripts/run-paged-kernel-tests.sh + + - name: Run CBv2KVSharingParityTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Compares contiguous and paged KV storage on the tiny KV-sharing + # model. A skip here means that the paged backend is not available. + timeout-minutes: 10 + run: scripts/run-nested-suite.sh CBv2KVSharingParityTests + + - name: Run CBv2SchedulerLoopTests + if: ${{ !cancelled() && steps.metallib.outcome == 'success' }} + # Checks the CBv2 engine loop with a scripted model: admission, + # waiting queue, cancellation, preemption, shutdown and watchdog. + timeout-minutes: 10 + run: scripts/run-nested-suite.sh CBv2SchedulerLoopTests + + - name: Remove the Metal libraries and coverage data before saving + # The next run builds its own Metal library and coverage data. + if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.cache.outputs.cache-hit != 'true' }} + run: | + find .build -type f -name mlx.metallib -delete + rm -rf "$(swift build --show-bin-path)/codecov" + + - name: Save the SwiftPM cache + # Save only on pushes to main. Pull requests only restore. Each push + # to main saves a new entry, and a run restores the newest entry for + # the same Xcode. + if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.cache.outputs.cache-hit != 'true' }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/Library/Caches/org.swift.swiftpm + ~/Library/org.swift.swiftpm + .build + key: ${{ steps.cache.outputs.cache-primary-key }} diff --git a/Tests/MLXLMTests/CBv2SchedulerLoopTests.swift b/Tests/MLXLMTests/CBv2SchedulerLoopTests.swift index 5ea3469d27..2dad9afa32 100644 --- a/Tests/MLXLMTests/CBv2SchedulerLoopTests.swift +++ b/Tests/MLXLMTests/CBv2SchedulerLoopTests.swift @@ -97,20 +97,22 @@ final class CBv2SchedulerLoopTests: XCTestCase { admissionConfig: .init(watermarkFraction: 0)) let zeroBudget = await cbv2SchedCollect( - try engine.submit(CBv2Request( - id: CBv2RequestID(9003), - promptTokens: [1], - maxTokens: 0, - tokenConstraint: CBv2SchedulerPassthroughConstraint(maxTokens: 7)))) + try engine.submit( + CBv2Request( + id: CBv2RequestID(9003), + promptTokens: [1], + maxTokens: 0, + tokenConstraint: CBv2SchedulerPassthroughConstraint(maxTokens: 7)))) XCTAssertEqual(zeroBudget.finishReason, .length) XCTAssertEqual(zeroBudget.usage?.completionTokens, 0) let emptyPrompt = await cbv2SchedCollect( - try engine.submit(CBv2Request( - id: CBv2RequestID(9004), - promptTokens: [], - maxTokens: 2, - tokenConstraint: CBv2SchedulerPassthroughConstraint(maxTokens: 3)))) + try engine.submit( + CBv2Request( + id: CBv2RequestID(9004), + promptTokens: [], + maxTokens: 2, + tokenConstraint: CBv2SchedulerPassthroughConstraint(maxTokens: 3)))) XCTAssertEqual(emptyPrompt.finishReason, .error("empty prompt")) await engine.shutdown() } @@ -125,13 +127,27 @@ final class CBv2SchedulerLoopTests: XCTestCase { maxConcurrentRequests: 2, maxBatchedTokensPerStep: 256, prefillChunkSize: 16, maxWaiting: 8)) harness.backend.maxLiveStates = 1 - async let a = cbv2SchedCollect( - try harness.engine.submit( - CBv2SchedFixtures.request(prompt: Array(0 ..< 6), maxTokens: 4))) - async let b = cbv2SchedCollect( - try harness.engine.submit( - CBv2SchedFixtures.request(prompt: Array(6 ..< 12), maxTokens: 4))) - let (ra, rb) = try await (a, b) + // The test owns the race it asserts on. It mints and submits both + // requests on this task: minting inside two `async let` children + // races on `CBv2SchedFixtures.nextID`, so both requests can get the + // same id and the second submit throws `duplicateRequestID`. It also + // holds the step loop until both requests wait, so both compete for + // the single KV slot. Without the hold, the first request can finish + // before the second one arrives, and nothing is requeued. + let loop = harness.engine.loopForTesting + loop.onEngineQueueSync { loop.suspendStepExecutionAtCountForTesting = 0 } + // A throwing submit must not leave the step loop held. + defer { loop.onEngineQueueSync { loop.suspendStepExecutionAtCountForTesting = nil } } + let first = try harness.engine.submit( + CBv2SchedFixtures.request(prompt: Array(0 ..< 6), maxTokens: 4)) + let second = try harness.engine.submit( + CBv2SchedFixtures.request(prompt: Array(6 ..< 12), maxTokens: 4)) + let bothWaiting = loop.onEngineQueueSync { loop.scheduler.waitingCount == 2 } + XCTAssertTrue(bothWaiting, "both requests must wait before the first step") + loop.onEngineQueueSync { loop.suspendStepExecutionAtCountForTesting = nil } + async let a = cbv2SchedCollect(first) + async let b = cbv2SchedCollect(second) + let (ra, rb) = await (a, b) await harness.engine.shutdown() XCTAssertEqual(ra.finishReason, .length, "first request must complete") XCTAssertEqual( @@ -228,15 +244,22 @@ final class CBv2SchedulerLoopTests: XCTestCase { let harness = CBv2SchedHarness( schedulerConfig: CBv2SchedulerConfig( maxConcurrentRequests: 1, maxBatchedTokensPerStep: 256, - prefillChunkSize: 16, maxWaiting: 1)) - // Hog pins the single RUNNING slot for many steps… (wait on the - // PUBLISHED gauge, not the backend, so the waiter's submit-side - // fast path is guaranteed to see the waiting queue as empty). + prefillChunkSize: 16, maxWaiting: 1), + loopConfig: CBv2EngineLoopConfig(eventBufferCapacity: 4)) + // Hog pins the single RUNNING slot, and the test owns its lifetime: + // its unread stream hits backpressure, so it pauses with its slot + // retained until the test drains it below. (Left to run, it finished + // its 60 scripted tokens in milliseconds, and the poll could miss + // it.) Also wait on the PUBLISHED gauge, not the backend, so the + // waiter's submit-side fast path is guaranteed to see the waiting + // queue as empty. + let hogID = CBv2RequestID(9101) let hogStream = try harness.engine.submit( - CBv2Request(id: CBv2RequestID(9101), promptTokens: [3], maxTokens: 60)) + CBv2Request(id: hogID, promptTokens: [3], maxTokens: 60)) let hogRunning = await cbv2SchedWait { let snapshot = harness.engine.capacity() - return snapshot.activeRequests == 1 && snapshot.waitingRequests == 0 + return harness.engine.loopForTesting.pausedIDsSnapshot() == [hogID] + && snapshot.activeRequests == 1 && snapshot.waitingRequests == 0 } XCTAssertTrue(hogRunning, "hog must be running before filling the waiting queue") // …and the waiter fills the single WAITING slot (it cannot be @@ -262,6 +285,7 @@ final class CBv2SchedulerLoopTests: XCTestCase { message, "token_budget_exhausted: request queue full", "backstop rejection must carry the provider's canonical queue-full marker") + // Draining the hog's stream resumes it, and it finishes its 60 tokens. let hog = await cbv2SchedCollect(hogStream) let waiter = await cbv2SchedCollect(waiterStream) await harness.engine.shutdown() @@ -684,7 +708,7 @@ final class CBv2SchedulerLoopTests: XCTestCase { let clock = CBv2SchedFakeClock(autoAdvanceSeconds: 20) // 20s per step let harness = CBv2SchedHarness( loopConfig: CBv2EngineLoopConfig( - decodeProgressLease: 120, // 20s/step gap ≪ 120 ⇒ never stalls + decodeProgressLease: 120, // 20s/step gap ≪ 120 ⇒ never stalls safetyCeilingDecodeFloorTPS: 0.01, // huge ceiling: irrelevant here clock: clock.clock)) let request = CBv2SchedFixtures.request(prompt: [1], maxTokens: 12) @@ -751,8 +775,8 @@ final class CBv2SchedulerLoopTests: XCTestCase { maxConcurrentRequests: 1, maxBatchedTokensPerStep: 2048, prefillChunkSize: 512, maxWaiting: 8), loopConfig: CBv2EngineLoopConfig( - admissionLease: 1, // tiny admission window - decodeProgressLease: 3600, // running peer stays healthy + admissionLease: 1, // tiny admission window + decodeProgressLease: 3600, // running peer stays healthy safetyCeilingDecodeFloorTPS: 0.0001, clock: clock.clock)) harness.model.forwardDelay = 0.005 @@ -801,8 +825,8 @@ final class CBv2SchedulerLoopTests: XCTestCase { let clock = CBv2SchedFakeClock(autoAdvanceSeconds: 40) // 40s per step let harness = CBv2SchedHarness( loopConfig: CBv2EngineLoopConfig( - admissionLease: 120, // 40s/step ⇒ admits before timeout - decodeProgressLease: 120, // 40s/step gap ≪ 120 ⇒ never stalls + admissionLease: 120, // 40s/step ⇒ admits before timeout + decodeProgressLease: 120, // 40s/step gap ≪ 120 ⇒ never stalls safetyCeilingDecodeFloorTPS: 1_000_000, // tiny decode bound ⇒ ~180s ceiling clock: clock.clock)) // Large maxTokens so the request keeps generating until the ceiling. diff --git a/fork.yaml b/fork.yaml index 94e8aab534..2b377e9946 100644 --- a/fork.yaml +++ b/fork.yaml @@ -294,7 +294,9 @@ def: - "Tests/OnboardingQualificationTests/**" - "benchmarks/**" - "script/**" - - "scripts/*.sh" + - "scripts/benchmark-mtp.sh" + - "scripts/build-qwen36-a3b-bench.sh" + - "scripts/stamp-bench-revision.sh" - "scripts/build-qwen36-python-contexts.py" - "scripts/patch-qwen36-mtp.py" - "Makefile" @@ -319,8 +321,17 @@ def: This page and the gate that keeps it honest: `check_forkdiff.py` fails CI when `base.hash` is not the merge-base with upstream, or when a file the fork changes is not described by a section above. + + The Fork Tests workflow (`.github/workflows/fork-tests.yml`) builds the package on a GitHub-hosted Mac. + It runs the self-contained Metal test suites, one suite at a time. + Its scripts build the full MLX Metal library with cmake and copy it next to the test binaries. + A suite fails when it executes zero tests or skips a test. globs: - "scripts/check_forkdiff.py" + - "scripts/build-metallib.sh" + - "scripts/stage-test-metallib.sh" + - "scripts/run-nested-suite.sh" + - "scripts/run-paged-kernel-tests.sh" - "FORKDIFF.md" - "README.md" diff --git a/scripts/build-metallib.sh b/scripts/build-metallib.sh new file mode 100755 index 0000000000..c926631168 --- /dev/null +++ b/scripts/build-metallib.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Build the full MLX Metal library (mlx.metallib) with cmake. +# +# `swift build` makes no Metal library. The pinned mlx-swift excludes the MLX +# kernel sources and nojit_kernels.cpp from its Cmlx target, so SwiftPM builds +# MLX in JIT mode. Without a staged mlx.metallib, every MLX operation in the +# tests traps with "Failed to load the default metallib". (xcodebuild compiles +# the .metal files in Source/Cmlx/mlx-generated into a partial +# default.metallib of about 459 symbols. This workflow does not use +# xcodebuild.) +# +# This script compiles every kernel ahead of time (-DMLX_METAL_JIT=OFF). It +# uses the MLX source that SwiftPM checked out for the mlx-swift revision in +# Package.swift. +# +# Usage: scripts/build-metallib.sh +# Run it from the package root after `swift build`. +set -euo pipefail + +if [[ $# -ne 1 ]]; then + echo "usage: $0 " >&2 + exit 2 +fi +output=$1 + +mlx_source=.build/checkouts/mlx-swift/Source/Cmlx/mlx +# MLX compiles the NAX kernels only for a deployment target of 26.2 or later. +deployment_target=26.2 +# The full library has about 17,000 symbols. A JIT-mode build +# (-DMLX_METAL_JIT=ON) or an incomplete build has far fewer. The check at the +# end rejects a library with fewer than 10,000 symbols. +minimum_symbols=10000 + +if [[ ! -f "$mlx_source/mlx/version.h" ]]; then + echo "No MLX source at $mlx_source. Run swift build first." >&2 + exit 1 +fi + +build_directory=$(mktemp -d) +trap 'rm -rf "$build_directory"' EXIT + +echo "MLX source: $mlx_source at $(git -C "$mlx_source" rev-parse HEAD)" +cmake -S "$mlx_source" -B "$build_directory" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="$deployment_target" \ + -DMLX_METAL_JIT=OFF \ + -DMLX_BUILD_TESTS=OFF \ + -DMLX_BUILD_EXAMPLES=OFF \ + -DMLX_BUILD_BENCHMARKS=OFF \ + -DMLX_BUILD_PYTHON_BINDINGS=OFF +cmake --build "$build_directory" --target mlx-metallib -j "$(sysctl -n hw.ncpu)" + +mkdir -p "$(dirname "$output")" +cp "$build_directory/mlx/backend/metal/kernels/mlx.metallib" "$output" + +symbols=$(xcrun -sdk macosx metal-nm "$output" | wc -l | tr -d ' ') +bytes=$(stat -f %z "$output") +echo "Wrote $output: $symbols symbols, $bytes bytes" +if (( symbols < minimum_symbols )); then + echo "The library has fewer than $minimum_symbols symbols. It is a JIT-mode or incomplete build." >&2 + exit 1 +fi diff --git a/scripts/run-nested-suite.sh b/scripts/run-nested-suite.sh new file mode 100755 index 0000000000..c8f1b20493 --- /dev/null +++ b/scripts/run-nested-suite.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Run one test suite with `swift test --skip-build --filter `. +# +# The script fails when the run executed zero tests or skipped a test. +# `swift test` exits with 0 when the filter matches no test, so the exit code +# alone does not show that the suite ran. The suites that use this script need +# no model weights. The caller sets any environment variable that a test +# needs: scripts/run-paged-kernel-tests.sh sets +# DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1 for one test. A skipped test means +# that a precondition is broken, for example a missing Metal library. +# +# Usage: scripts/run-nested-suite.sh [more swift test arguments] +set -euo pipefail + +if [[ $# -lt 1 ]]; then + echo "usage: $0 [more swift test arguments]" >&2 + exit 2 +fi +filter=$1 +shift + +log=$(mktemp -t nested-suite) + +# tee keeps the test output in the job log. pipefail keeps the exit code of +# swift test. +swift test --skip-build --filter "$filter" "$@" 2>&1 | tee "$log" + +# XCTest prints "Executed 3 tests". Swift Testing prints "Test run with 3 tests". +if ! grep -qE 'Test run with [1-9][0-9]* test|Executed [1-9][0-9]* test' "$log"; then + echo "::error::$filter executed zero tests." + exit 1 +fi + +# XCTest prints "with 1 test skipped". Swift Testing prints one line for each +# skipped test, for example "✘ Test name() skipped: reason", and counts the +# skipped test as passed. The symbol at the start of that line is different +# in different Swift versions, so the pattern accepts any symbol there. +if grep -qE '^[^A-Za-z0-9]*(Test|Suite) .+ skipped[.:]|with [1-9][0-9]* tests? skipped|skipped [1-9][0-9]* test' "$log"; then + echo "::error::$filter skipped one or more tests." + exit 1 +fi diff --git a/scripts/run-paged-kernel-tests.sh b/scripts/run-paged-kernel-tests.sh new file mode 100755 index 0000000000..99627dd062 --- /dev/null +++ b/scripts/run-paged-kernel-tests.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Run CBv2PagedKernelTests in two test processes. +# +# decodeBatchCompositionInvariance compares GPU results bit for bit. It runs +# only when DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, and it must run alone in +# its process. The first process runs all other tests in the suite with the +# variable unset. The second process runs that one test with the variable set. +# The second process runs even when the first one fails. +set -uo pipefail +script_directory=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +status=0 + +env -u DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST \ + "$script_directory/run-nested-suite.sh" CBv2PagedKernelTests --no-parallel \ + --skip decodeBatchCompositionInvariance || status=$? + +env DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1 \ + "$script_directory/run-nested-suite.sh" decodeBatchCompositionInvariance \ + --no-parallel || status=$? + +exit "$status" diff --git a/scripts/stage-test-metallib.sh b/scripts/stage-test-metallib.sh new file mode 100755 index 0000000000..df877692ac --- /dev/null +++ b/scripts/stage-test-metallib.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Copy mlx.metallib to the places where the tests look for it. +# +# MLX first looks for mlx.metallib in the folder of the binary that contains +# MLX. For the tests, that binary is in the .xctest bundle, in Contents/MacOS. +# This script copies the library into every .xctest bundle in the bin folder, +# and into the bin folder for the other binaries. +# +# Usage: scripts/stage-test-metallib.sh +set -euo pipefail + +if [[ $# -ne 2 || ! -f "$1" || ! -d "$2" ]]; then + echo "usage: $0 " >&2 + exit 2 +fi +metallib=$1 +bin_directory=$2 + +cp "$metallib" "$bin_directory/mlx.metallib" +echo "Staged $bin_directory/mlx.metallib" + +found=0 +for bundle in "$bin_directory"/*.xctest; do + [[ -d "$bundle" ]] || continue + mkdir -p "$bundle/Contents/MacOS" + cp "$metallib" "$bundle/Contents/MacOS/mlx.metallib" + echo "Staged $bundle/Contents/MacOS/mlx.metallib" + found=1 +done +if [[ "$found" -ne 1 ]]; then + echo "No .xctest bundle in $bin_directory. Run swift build --build-tests first." >&2 + exit 1 +fi