Skip to content

Synchronize streams before the allocator statistics baseline - #33

Merged
jjang-ai merged 1 commit into
osaurus-ai:mainfrom
rcfa:fix/allocator-stats-sync
Nov 22, 2026
Merged

jjang-ai merged 1 commit into
osaurus-ai:mainfrom
rcfa:fix/allocator-stats-sync

Conversation

@rcfa

@rcfa rcfa commented Oct 30, 2026

Copy link
Copy Markdown

What fails

With Metal, test concurrent allocator statistics fails in most runs of the allocator tests alone, and in some runs of the whole suite. Line numbers below are at main = 4a22e4fed.

  • The case (tests/allocator_tests.cpp:143-194) calls clear_cache() and reads its baseline, initial_active = get_active_memory() (:147), without waiting for any stream. At its end it checks CHECK_EQ(get_active_memory(), initial_active) (:190).
  • An earlier case, test array buffer size (:72-88), evaluates a reshape of a 16-byte array on the default stream.
  • On Metal, gpu::eval keeps the inputs of each primitive in a completion handler of the command buffer (mlx/backend/metal/eval.cpp:47-67). eval returns when the stream's event signals (mlx/transforms.cpp:345-353, :386; array::wait, mlx/array.cpp:145-153), and that can be before the handler runs.
  • So the 16-byte buffer can still be live at :147 and be freed before :190:
tests/allocator_tests.cpp:190: ERROR: CHECK_EQ( get_active_memory(), initial_active ) is NOT correct!
  values: CHECK_EQ( 0, 16 )

Without Metal it passed in every run on record, each a single run: the whole Metal-build suite with DEVICE=cpu at d6dab016b, whose test and allocator sources are the same as main's (308 | 308 passed, mf-qmv-mbasecpu-macmetal.tests.log), and the CPU-only builds' whole suites at main (macOS 280 of 280, Linux 264 of 264, bf-ar-base-{mac,arm,x86}.tests.log).

How often

The allocator tests alone (-sf=*allocator_tests.cpp), 50 runs in a row on macOS with Metal at main: 39 failed, each as above (bf-as-red-macmetal.loop.log). Earlier runs of the same test source gave 21, 34 and 40 of 50, and 9 of 20. The whole Metal suite at main failed this one case in this run (308 | 307 passed | 1 failed).

The fix

Only the test changes. Before it clears the cache and reads the baseline, the case now:

  • synchronizes this thread's default GPU stream, if there is a GPU and that stream exists (peek_default_stream, so no stream is made). This is the step that removes the failure (see the mutation check);
  • synchronizes every CPU stream from get_streams(), as the CPU allocator's synchronize_cpu_streams() does (mlx/backend/no_gpu/allocator.cpp:26-32). This step is defensive: without a GPU, clear_cache() already synchronizes the CPU streams when its cache is not empty (no_gpu/allocator.cpp:162-172).

CommandEncoder::synchronize (mlx/backend/metal/device.cpp:581-591) commits the stream's open command buffer and waits for it to complete. Upstream's test_active_memory_count (python/tests/test_memory.py:87-99) uses the same order: mx.synchronize(), mx.clear_cache(), then mx.get_active_memory().

That this wait also covers the earlier command buffer's completion handler, and the release of what it holds (eval.cpp:66-67), is observed, not documented. Apple documents that a queue runs its command buffers in order. It does not document that a later buffer's waitUntilCompleted returns only after an earlier buffer's completion handlers have run and been released. The evidence here is 0 failures in 500 runs (below).

Why only the default GPU stream

A GPU stream made on another thread cannot be synchronized from this one: metal::get_command_encoder (device.cpp:954-967) throws "There is no Stream(gpu, N) in current thread." Such a stream needs no synchronize here, for two reasons:

  • Its own thread synchronizes it. test new stream in threads (tests/scheduler_tests.cpp:92) makes one and then calls clear_streams() (:98). That destroys the thread's command encoders, and ~CommandEncoder synchronizes (device.cpp:326-332).
  • doctest sorts the cases by file, so only this file's cases come before this one, and they use only the default stream. Without a GPU there is also one new CPU stream (:111), which the CPU loop covers. Under ctest, each discovered case also runs in its own process (doctest_discover_tests, tests/CMakeLists.txt:54), and the whole-binary test (:55) runs in file order.

Not covered: --order-by=rand, streams from new_thread_unsafe_stream, and non-default GPU streams made on the main thread. If an earlier case left buffers in one of these, the race could come back.

CPU streams can be synchronized from any thread: Scheduler::get_thread (mlx/scheduler.cpp:148-162) finds or makes the stream's thread.

The final check (:190, now :204) is unchanged.

Verification

On macOS. Each Metal run held vmlx's Metal test lock.

Run Result Log
Allocator tests alone, Metal, 50 runs, at main 39 of 50 failed, each at :190 with CHECK_EQ( 0, 16 ) bf-as-red-macmetal.loop.log
The same at this branch, 50 runs 0 of 50 failed bf-as-green-macmetal.loop.log
The same at this branch, 500 runs 0 of 500 failed bf-as-green500-macmetal.loop.log
This branch without the GPU synchronize (the CPU loop kept), 50 runs 36 of 50 failed, with CHECK_EQ( 0, 16 ) bf-as-mut-macmetal.loop.log
Whole Metal suite at main 307 of 308 cases passed (this case failed); 5004 of 5005 assertions bf-as-suitebase-macmetal.tests.log
Whole Metal suite at this branch 308 of 308 passed; 5005 of 5005 assertions bf-as-suitefix-macmetal.tests.log
Allocator tests, CPU-only build (Metal off) 7 of 7 passed; 21 of 21 assertions bf-as-cpu2-mac.tests.log
  • 0 of 500 puts the remaining failure rate under about 0.6 % (95 % confidence), against about 6 % from 0 of 50.
  • The one-minute load was 13 to 17 for the runs at 50, and 21 to 23 for the 500 runs.
  • The 500 runs and the CPU-only run are at the final commit. The other runs are at its first version, which differed only in its comments: one line changed, one added (so the mutation's check was at :197).
  • So nothing newly fails. clang-format passes, and the build has no warnings.

Upstream

ml-explore/mlx main (1ba7f969a) has no test concurrent allocator statistics: its tests/allocator_tests.cpp ends with test clear cache synchronizes cpu streams. The case came with #16, so this is fork-only, and there is no upstream report.

🤖 Generated with Claude Code

"test concurrent allocator statistics" took get_active_memory() as its
baseline without waiting for the streams, and checked at its end that
the active memory came back to it. With Metal, a buffer of an earlier
case can still be live when the baseline is read: "test array buffer
size" evaluates a reshape of a 16-byte array, and Metal keeps the
inputs of each evaluated primitive until its command buffer's
completion handler runs, which can be after the evaluation returns.
The buffer is then freed during the case, and the final check sees 0
against 16. Run alone with Metal on macOS, the allocator tests failed
39 times in 50, each as:

    tests/allocator_tests.cpp:190: ERROR: CHECK_EQ( get_active_memory(), initial_active ) is NOT correct!
      values: CHECK_EQ( 0, 16 )

The case now synchronizes every CPU stream and this thread's default
GPU stream, then clears the cache and reads the baseline, the order
python/tests/test_memory.py uses for its active memory count. A GPU
stream made on another thread cannot be synchronized from this one,
so only the default one is. The final check is unchanged. With this,
the allocator tests passed 50 times in 50; without the GPU synchronize
they failed 36 times in 50.
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.

2 participants