Skip to content

Fix Metal buffer leak (PyObjC ownership of MTLDevice new* methods) - #45

Open
neurolabusc wants to merge 2 commits into
dipy:masterfrom
neurolabusc:metal_fix
Open

neurolabusc wants to merge 2 commits into
dipy:masterfrom
neurolabusc:metal_fix

Conversation

@neurolabusc

Copy link
Copy Markdown
Contributor

Problem

Every per-batch MTLBuffer on the Metal backend leaked for the life of the process. Tracking 300k HARDI seeds reached 16.5 GB peak memory footprint (9.8 GB max RSS); the same leak was reported against the dipy port in dipy/dipy#4033 (19.4 GB peak, 16.2 GB retained for 588k seeds).

Cause

PyObjC's Metal bindings carry no ownership metadata for the MTLDevice protocol's new* selectors (newBufferWithLength:options:, newBufferWithBytes:length:options:, etc.). PyObjC therefore treats the +1 return as autoreleased, retains it once more, and never releases it. device.currentAllocatedSize() never drops after del buf + gc.collect(); autorelease pools make no difference.

Fix

Register already_retained metadata for the six new* selectors at import of cuslines/metal/mutils.py. registerMetaDataForSelector replaces the inferred metadata, so the pointer and error out-arguments are restated.

Results (M-series, 300k seeds, HARDI)

max RSS peak footprint track time
before 9.8 GB 16.5 GB 85.6 s
after 5.3 GB 6.1 GB 61.6 s

Fixed-seed runs produce identical streamline counts before and after.

🤖 Generated with Claude Code

neurolabusc and others added 2 commits September 22, 2026 20:06
…ethods

PyObjC's Metal bindings have no ownership metadata for the MTLDevice
protocol's new* selectors, so the +1 return was treated as autoreleased and
never released. Every per-batch MTLBuffer leaked for the life of the process
(300k seeds: 16.5 GB peak footprint -> 6.1 GB, 9.8 GB max RSS -> 5.3 GB).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Fork PRs have no write token for the org GHCR package, so the pull_request
build always failed at the push step (see dipy#43 as well).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant