Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions .github/workflows/fork-tests.yml
Original file line number Diff line number Diff line change
@@ -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 }}
80 changes: 52 additions & 28 deletions Tests/MLXLMTests/CBv2SchedulerLoopTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 12 additions & 1 deletion fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"

Expand Down
Loading
Loading