Skip to content

idea for doing synchronous evals but _not_ holding evalLock - #474

Merged
davidkoski merged 6 commits into
mainfrom
multithreaded-eval
Oct 15, 2026
Merged

davidkoski merged 6 commits into
mainfrom
multithreaded-eval

Conversation

@davidkoski

Copy link
Copy Markdown
Member

Proposed changes

  • do the synchronous mutation under lock with asyncEval
  • synchronous eval then does not need lock

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
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

Comment thread Source/MLX/Transforms+Eval.swift Outdated
Comment on lines +125 to +142
mlx_eval(vector_array)
mlx_async_eval(vector_array)
}
mlx_eval(vector_array)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the heart of the change. we need the evalLock to guard against mutation of shared state. python uses thread-local streams to scope this, but we can't do that on the swift side (at least not in the same way).

But what if we did the mutation part under lock and then just wait for the arrays to be ready outside the lock? The MLXArray instances are still not thread safe, so they can't escape to other threads where the mutation could be observed, so I think this is safe.

See #472 and #62

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI @aleroot -- I got this idea from the concurrent read work you did and this might be generally useful.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work.


@testable import MLX

// MARK: - Support

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now this is just some tests that I had claude throw together.

@davidkoski davidkoski mentioned this pull request Sep 15, 2026
1 task done
@davidkoski davidkoski mentioned this pull request Sep 28, 2026
7 tasks done
@davidkoski
davidkoski changed the base branch from main to fix-lock-inversion October 9, 2026 21:35
```swift
let g = grad { (x: MLXArray) -> MLXArray in
let y = x * x
print(y.asArray(Float.self)) // OK: synchronous eval of an intermediate

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clarify that this case is explicitly allowed -- not all transforms prohibit evaluation:

Comment on lines +217 to +218
@Suite("eval inside function transformations")
struct EvalInTransformsTests {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on PR feedback this tests and asserts the different evaluations inside of transforms that are allowed vs not.

Comment thread Source/MLX/Export.swift
Comment on lines -148 to +150
mlx_export_function_kwargs(url.path, closure, positionalArgs, kwargs, shapeless)
withEvalLock {
mlx_export_function_kwargs(url.path, closure, positionalArgs, kwargs, shapeless)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While investigating #499 found these spots that also require the evalLock

Comment on lines +190 to +202
let waitOutsideLock = withEvalLockState { state in
switch state {
case .nested:
// cannot release the lock to wait, and async eval rejects
// vjp/jvp tracers
_ = mlx_eval(vectorArray)
return false

case .outermost:
// schedule under the lock, wait (below) outside it
return mlx_async_eval(vectorArray) == 0
}
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handling fixes the issues found in review, see also EvalInTransformsTests

@nwh nwh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Base automatically changed from fix-lock-inversion to main October 9, 2026 22:51
@davidkoski
davidkoski merged commit 2f96983 into main Oct 15, 2026
7 checks passed
@davidkoski
davidkoski deleted the multithreaded-eval branch October 15, 2026 16:36
eejd pushed a commit to eejd/mlx-swift that referenced this pull request Oct 18, 2026
Brings in ml-explore#474 (synchronous evals without holding evalLock), ml-explore#499 (evalLock /
dispatch_once lock inversion), ml-explore#495 (xcframework builds) and ml-explore#489 (workflows).
No conflicts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
jonathan308 added a commit to Layr-Labs/mlx-swift that referenced this pull request Oct 26, 2026
…ack (#56)

Forward merge of the refreshed #54 (main 6959486 merged into the JACCL fixes
pin) into this branch. This branch already carried main up to the #58 squash
67dc752, so the new main content is the upstream ml-explore/mlx-swift merge
ce46846 (#59, with #60 and #62), the core and C repin with regenerated sources
(#63) and the wrapped external buffer test (#64).

Conflicts:
- Source/Cmlx/mlx and Source/Cmlx/mlx-c (gitlinks): kept this branch's pins,
  core 360d11b9 and mlx-c 8a50797b. They are restitched to the merged core and
  C heads separately.
- fork.yaml, "Submodule pins": one paragraph that states main's pins (mlx
  ff4bb35b, mlx-c 004c735f, merges of upstream main) and then what the
  cluster core and C add on top. Every other section merged without conflict;
  the cluster's startup-wait section is kept.

Merged without conflict and checked: the mirrored fast.h keeps the fenced
kernel and prepared launch declarations next to main's math-mode entry point,
distributed_group.h keeps the bootstrap, startup-wait and sealed-codec
declarations, and MLXArray.sharingArray() still calls copyContext(), which
main keeps. The tree is main plus this branch's own delta: the two gitlinks,
those two headers, MLXArray.swift, MLXFastKernel.swift,
docs/startup-wait-budget.md and fork.yaml.

Main's Transforms+Eval.swift now schedules under evalLock and waits outside
it (upstream ml-explore#474). withSerializedEvaluation still runs its body under
evalLock, so native evaluation, fences and collectives stay serialized against
scheduling; a Swift eval's wait no longer excludes them.

Tests (Ultra A, Xcode 27.1). These ran on this merge with the two follow-up
commits on top (swift-format and fork.yaml). The committed gitlinks are not
changed. For the build, the nested repos were checked out at merged heads:
core 2b5253ad (the core merge into mlx#35; 69c0a0f6 gave the same results)
and a temporary merge of mlx-c main 004c735f into 8a50797b. Its C sources
merge cleanly; CMakeLists.txt and fork.yaml are taken from 8a50797b.
- swift build --build-tests: complete.
- Fork Tests, all 3 shards of the CI plan, with an AOT mlx.metallib from
  that core:
  - XCTest: 852 listed, 848 passed, and the 2 permitted skips.
  - The fresh-process allocation-cap test and both multi-process ring
    suites passed.
  - Swift Testing: 749 of 749 passed.
  - test-shards.py verify: every test ran exactly once.
- check-generated-metal-sources.py passes against that core.
- The mirrored mlx/c headers are byte-identical to the merged C headers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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