Skip to content

test: make the capacity-loser scheduler test deterministic - #164

Merged
Gajesh2007 merged 11 commits into
mainfrom
test/scheduler-capacity-loser-deterministic
Sep 28, 2026
Merged

Gajesh2007 merged 11 commits into
mainfrom
test/scheduler-capacity-loser-deterministic

Conversation

@davidtai

@davidtai davidtai commented Sep 26, 2026 •

Copy link
Copy Markdown

Proposed changes

CBv2SchedulerLoopTests.testCapacityLoserIsRequeuedNotErrored fails now and then with this message:

CBv2SchedulerTestSupport.swift:533: error: -[MLXLMTests.CBv2SchedulerLoopTests testCapacityLoserIsRequeuedNotErrored] : failed: caught error: "CancellationError()"

Cause

  1. The test minted its two requests inside two async let children (CBv2SchedulerLoopTests.swift:130-135 before this PR). Each child calls CBv2SchedFixtures.request, which does nextID += 1 on a nonisolated(unsafe) static var (CBv2SchedulerTestSupport.swift:442 and :448-450). The two children run at the same time on different threads, so both requests can get the same id.
  2. The second submit with that id then throws CBv2SchedulerError.duplicateRequestID (EngineV2.swift:662-664). The test rethrows it at try await (a, b).
  3. The message does not name that error. XCTest reports the last Swift error thrown anywhere during the test, not the error that the test threw. The first request still finishes after the second submit throws. Its cbv2SchedCollect then cancels its watchdog, and the watchdog's try? await Task.sleep (CBv2SchedulerTestSupport.swift:533) throws a CancellationError, which try? swallows. That error is the last one thrown, so XCTest reports it. The run took about 1 s because XCTest symbolicates the stack.

No product code throws CancellationError on this path. The synchronous EngineV2.submit throws only capacity, multimodal and duplicate-id errors.

Probes (not in this PR) confirm steps 1 and 3:

  • Eight tasks that each minted 20,000 ids got 143,206 distinct ids out of 160,000. The counter loses updates when threads run it at the same time.
  • A test where an async let child throws ProbeError, then a separate task's try? await Task.sleep is cancelled, then the test rethrows the child's error, fails with caught error: "CancellationError()" at the sleep line. XCTest names the wrong error.

The test had a second race, which did not fail in any run here. If the second child submitted late, the first request could finish before the second arrived. Then nothing is requeued, and the capacityRequeueCount >= 1 assertion fails.

Fix

This PR changes only testCapacityLoserIsRequeuedNotErrored:

  • The test mints and submits both requests on its own task, so the ids are always different.
  • Before it submits, the test holds the step loop with suspendStepExecutionAtCountForTesting = 0, set on the engine queue, as other CBv2 tests do. It checks that both requests are in the waiting queue, then releases the loop. The first step admits both requests. One gets the only KV slot, and the other trips capacityExhausted and is requeued. The requeue always happens.
  • A defer releases the hold on the engine queue, so a submit that throws cannot leave the step loop held (commit cf975bf).
  • Then the test collects both streams. The assertions are the same: both requests finish with .length, and capacityRequeueCount >= 1.

The file stays formatted with swift format format --configuration .swift-format. The diff holds only this change.

Test plan

Local runs on a laptop with 10 CPU cores (Apple silicon). Each run executed the whole CBv2SchedulerLoopTests class (37 tests) with Xcode's xctest -XCTest MLXLMTests.CBv2SchedulerLoopTests. During the runs, 8 yes > /dev/null loops kept 8 cores busy, which leaves about 3 cores for the tests, like the hosted macos-26 runner. I stopped the loops after each set and confirmed that none were left.

Test file Runs Suite passed Suite failed Capacity-loser test failed Backstop test failed Other tests failed
ci/fork-tests (526161b, unfixed) 30 29 1 1 (run 17) 0 0
#163 (ce39176) 30 30 0 0 0 0
This PR (4de5082, before the defer) 30 30 0 0 0 0
  • The unfixed file reproduced the capacity-loser failure once, with the same message as before: caught error: "CancellationError()" at CBv2SchedulerTestSupport.swift:533.
  • test: hold the hog in the waiting-queue backstop test #163 has the same capacity-loser test as the unfixed file, and it passed 30 of 30. The failure rate is low, so 0 failures in 30 runs does not prove the fix. The fix rests on the cause above: the test no longer mints ids at the same time on two threads, and it no longer depends on when the second request arrives.
  • The load did not reproduce the backstop failure that test: hold the hog in the waiting-queue backstop test #163 fixes: 0 failures in 30 runs of the unfixed file.
  • Build: swift build --build-tests with the Xcode 27.0 toolchain (Swift 6.4), --build-system native, the Xcode XCTest search paths, and -Xbuild-tools-swiftc -target -Xbuild-tools-swiftc arm64-apple-macosx14.0 (without that flag, the BenchRevisionStamp plugin does not compile for the default macOS 12 host target). The full build took 2.3 min. The rebuild for each test file took 12 to 24 s.
  • The suite needs a Metal library. I staged work/mlx-metallib-aot with scripts/stage-test-metallib.sh, as in test: hold the hog in the waiting-queue backstop test #163.
  • scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main passes. fork.yaml covers Tests/MLXLMTests/CBv2*.
  • The table above was measured on commit 4de5082. That commit and cf975bf (the defer cleanup) were rebased onto test: hold the hog in the waiting-queue backstop test #163's head 26f54f2 without change and are now 49e35f6 and acc541d. test: hold the hog in the waiting-queue backstop test #163's head adds a gated Fork Tests step for CBv2SchedulerLoopTests.
  • CI run of acc541d, which contains both scheduler fixes and the defer cleanup: https://github.com/Layr-Labs/mlx-swift-lm/actions/runs/36284663877, success on the first attempt. The CBv2SchedulerLoopTests step executed 37 tests with 0 failures and 0 skips. testCapacityLoserIsRequeuedNotErrored passed in 0.022 s and testWaitingQueueBackstopEmitsCanonicalQueueFullMarker in 0.068 s. This is one CI run, not a repeated-run result.
  • In that run, the Metal library was built with cmake from the resolved mlx-swift checkout at MLX commit 3fa8f25e6451174d7b06be372c3a24272b77d88e (17,326 symbols), not from the local library.
  • Earlier CI evidence of the flake: the failure in the table's control row was reproduced only locally. In CI, the capacity-loser test has not failed; the CI failure on record is the backstop test in ci: run the SDK and MTP suites on pull requests #161's run 36182132297, attempt 1.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes: the changed file is formatted with swift format format and .swift-format
  • I have added tests that prove my fix is effective or that my feature works: not applicable, this PR fixes one test and adds none
  • I have updated the necessary documentation (if needed): not applicable, no document describes this test

Dependencies

This PR is stacked on #163 (base test/scheduler-backstop-deterministic), because both change the same file. Merge it after #163 and before #166, #167 and #161. #166 is stacked on this PR.

Merge order: #160, then #159, then delete ci/fork-tests so GitHub retargets the stacked PRs to main, then #162, then #163, then #164, then #166, then #167, then #161.

Authorship

The commits were written by Claude Opus 5.5.

🤖 Generated with Claude Code

davidtai and others added 8 commits September 25, 2026 12:58
Add the Fork Tests workflow. It builds the package on a macos-26
runner, builds the full MLX Metal library with cmake, copies it next
to the test binaries, and runs six CBv2 paged suites one step each.
A suite step fails when the suite executes zero tests or skips a test.

Port the scripts from d-inference and add them to fork.yaml.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
system_profiler SPDisplaysDataType prints nothing on the hosted
macos-26 VM. The CPU, memory and disk lines stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Pick the newest Xcode_26.x app whose name is only a version number.
Beta and release candidate apps are left out, so a new beta on the
runner image cannot change CI without a pull request. The step still
fails when the selected Swift is older than 6.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
swift build makes no Metal library. The pinned mlx-swift excludes the
MLX kernel sources and nojit_kernels.cpp from Cmlx, so SwiftPM builds
MLX in JIT mode, and every MLX operation traps without a staged
mlx.metallib. The partial 459-symbol library comes from xcodebuild,
which this workflow does not use.

State that the 10,000-symbol floor rejects a JIT-mode or incomplete
cmake build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
End the cache key with the commit SHA, as d-inference does, so each
push to main saves a new entry. The prefix restore key still restores
the newest entry for the same Xcode.

Before the save, delete the staged mlx.metallib copies and the
coverage data, so the cache keeps only SwiftPM output.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- run-nested-suite.sh: the suites need no model weights, but one test
  needs DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, which the caller sets.
- fork-tests.yml: runs on main are not cancelled once they start.
- Say "self-contained" instead of "hermetic" in the workflow and in
  fork.yaml.
- fork.yaml: write the Fork Tests paragraph as one sentence per line,
  so later pull requests can add a sentence without touching the same
  lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
testWaitingQueueBackstopEmitsCanonicalQueueFullMarker polled every
5 ms for the hog request to show as running, but the hog finished its
60 scripted tokens in milliseconds. A late poll missed the window and
the test failed after 10 s (Fork Tests run 36182132297, attempt 1).

Set eventBufferCapacity to 4, as testDuplicateSubmitThrowsAndFirst-
StreamStillDelivers does. The unread hog stream hits backpressure, so
the hog pauses with its slot retained until the test drains it. The
wait now also requires the hog to be paused. Only this test changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Run swift format format with .swift-format on the whole file, so the
format check of #160 passes. It changes four places outside the
backstop test: two nested CBv2Request calls and three comment
alignments in CBv2EngineLoopConfig arguments. No code changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@jonathan308

Copy link
Copy Markdown

Validation follow-up for head cf975bf: before approval, please run CBv2SchedulerLoopTests in CI with both #163 and this fix included, using a Metal library built from the resolved dependency sources. Add a gating suite step or link an equivalent CI run that executes the changed tests, rather than only compiling them.

Please include validation of the latest cf975bf head, including its defer cleanup; the documented repeated-run table is for the earlier 4de5082 revision. Keep the assertions for both successful completions and capacityRequeueCount >= 1 intact. Retain the negative-control evidence and report all attempts rather than treating a green rerun alone as proof that the flake is gone.

This is a validation request based on the documented CI gap, not a claim of a newly reproduced product defect.

davidtai and others added 3 commits September 26, 2026 20:08
Add a Fork Tests step that runs CBv2SchedulerLoopTests with
scripts/run-nested-suite.sh, after the six Metal suites. The step
fails when the class executes zero tests or skips a test, so CI runs
the backstop fix instead of only compiling it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
testCapacityLoserIsRequeuedNotErrored minted its two requests inside
two async let children. Both children increment the unsynchronized
CBv2SchedFixtures.nextID at the same time, so both requests can get
the same id. The second submit then throws duplicateRequestID. XCTest
reports the last error thrown during the test, which is the
CancellationError from the cbv2SchedCollect watchdog sleep, so the
failure showed as "CancellationError" at CBv2SchedulerTestSupport.swift:533.

The test now mints and submits both requests on its own task. It also
holds the step loop until both requests wait, so both requests compete
for the single KV slot in the same step and the requeue always happens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A defer releases suspendStepExecutionAtCountForTesting on the engine
queue, so a throwing submit in testCapacityLoserIsRequeuedNotErrored
cannot leave the step loop held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davidtai

Copy link
Copy Markdown
Author

Reply written by Claude (agent) on David Tai's behalf.

Done. Rebased onto #163's head; the head is now acc541d with the defer cleanup. Run https://github.com/Layr-Labs/mlx-swift-lm/actions/runs/36284663877 executed the class with both fixes: 37 tests, 0 failures, 0 skips, on the metallib built from the resolved dependency. The local 30-run table stays labelled as the 4de5082 measurement, and the negative-control result is kept. Assertions for both completions and capacityRequeueCount >= 1 are unchanged.

Base automatically changed from test/scheduler-backstop-deterministic to main September 28, 2026 21:33
@Gajesh2007
Gajesh2007 merged commit be87a63 into main Sep 28, 2026
5 checks passed
@Gajesh2007
Gajesh2007 deleted the test/scheduler-capacity-loser-deterministic branch September 28, 2026 21:34
javiech1 pushed a commit to javiech1/mlx-swift-lm that referenced this pull request Oct 24, 2026
…follow-up) (Layr-Labs#471)

feat(paroquant): MoE architecture support, prepared checkpoint caching, and rotation kernel optimizations

### MoE Support & Architecture
- **PairwiseRotation & RotateSwitchGLU:** Extracted standalone `PairwiseRotation` module and implemented `RotateSwitchGLU` to support MoE PARO models (e.g., Qwen3.6-35B-A3B).
- **MoE Loader Pipeline:** Added passes to stack per-expert AWQ weights, remap shared rotations, and patch switch GLU layers without mutating dense paths.
- **Conversion Robustness:** Dropped theta-filter to convert un-partnered expert weights, match scales/biases to checkpoint float dtype, and optimized prefix matching from $O(N \cdot M)$ to $O(1)$.

### Performance
- **Pre-Gather MoE Rotation:** Moved `gate_up` rotation before expert gather/sort, reducing row-rotation overhead by $1/\text{topK}$.
- **Simdgroup Rotation Kernel:** Rewrote the Metal rotation kernel for `groupSize == 128` to execute in a single simdgroup with `simdgroup_barrier` (with generic fallback for other sizes), delivering up to 2x speedup.
- **GatedDelta Fusion:** Compile-fused the 6-kernel elementwise decay gate chain into a single dispatch.
- **Prepared Checkpoints:** Added background caching of converted weights to `prepared_checkpoint.safetensors` with self-healing validation manifests, cutting warm-load times significantly.

### Fixes & Cleanups
- Unified `RotationDerivedState` and batched GPU evaluation across all rotation modules at load time.
- Froze `PairwiseRotation` parameters to allow fused weighted reduction in `SwitchGLU`.
- Fixed tool-call format and chat convention resolution in `loadParoQuantModel`.
- Fixed volume free-space detection for disk persistence on CI runners.

Refs Layr-Labs#208, Layr-Labs#209, Layr-Labs#220, Layr-Labs#424, Layr-Labs#471
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants