Skip to content

Fix leak when _updateInternal replaces an array with siblings - #501

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
ShankyShako:fix-update-internal-leak
Oct 16, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
ShankyShako:fix-update-internal-leak

Conversation

@ShankyShako

Copy link
Copy Markdown
Contributor

MLXArray._updateInternal puts the new array over the old one with mlx_array_set, which is a C++ copy assignment. That never runs array::~array(), and the destructor is what breaks the reference cycle between sibling outputs of a multi-output primitive (mlx/array.cpp, array::~array). If the replaced array is an unevaluated sibling, its whole graph is orphaned.

Module.update(parameters:) goes through _updateInternal, so this happens on every quantized model load: a freshly built QuantizedLinear holds random-init weights that are unevaluated outputs of a multi-output Quantize, and loading the checkpoint replaces them.

This change frees the old handle instead of assigning over it, so the destructor runs.

Reproduction

I loaded and unloaded a 4-bit model 10 times in one process (Cohere Transcribe through mlx-audio-swift, which loads with fromDirectory → update(parameters:)), then counted live objects with heap <pid> -s:

ArrayDesc after 0 reloads after 10 reloads footprint
0.32.3 7,785 85,445 49 → 120 MB
with this change 19 19 32 → 34 MB

That's about 7–12 MB leaked per load. The leftover objects are ArrayDesc, Quantize, RandomBits, AsType and Broadcast nodes plus Metal buffers. Inference speed is unchanged.

Calling MLX.quantized() on its own and dropping, replacing or evaluating the results leaks nothing, so the leak comes from the assignment, not from Quantize.

(Separately, model construction draws ~900 keys from MLXRandom.globalState lazily; apps that load repeatedly should eval(MLXRandom.globalState) afterwards or the key chain grows too. That one isn't a bug, so this PR doesn't change it.)

🤖 Generated with Claude Code

_updateInternal assigned the new array over the old one with
mlx_array_set, a C++ copy assignment. That skips array::~array(), which
is where the cycle between sibling outputs of a multi-output primitive
is broken. Module.update(parameters:) goes through _updateInternal, so
loading weights into a freshly built QuantizedLinear (whose random
init weight is an unevaluated output of a multi-output Quantize)
orphaned the whole init graph on every model load.

Free the old handle instead, so the destructor runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nice find -- that has been there roughly forever! Thank you!

@davidkoski

Copy link
Copy Markdown
Member

Just waiting on CI.

Clearing self.ctx before copying from array.ctx emptied the array on
a._updateInternal(a), which the sharding path reaches through
Module.update(parameters:) (DistributedNNTests.testShardPredicate
aborted with "expected a non-empty mlx_array"). Copy into a new handle,
then free the old one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ShankyShako

Copy link
Copy Markdown
Contributor Author

The macOS failure was this change: a._updateInternal(a) cleared self.ctx before copying from array.ctx, so the array came out empty (testShardPredicate reaches that through Module.update(parameters:)). d424c1c copies into a new handle before freeing the old one and adds testUpdateInternalWithItself, which aborts without the fix. Full suite passes locally on the branch merged with current main (385 tests, 2 skipped).

Comment thread Source/MLX/MLXArray.swift
Comment on lines +572 to +575
var new = mlx_array_new()
mlx_array_set(&new, array.ctx)
mlx_array_free(self.ctx)
self.ctx = new

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

testShardPredicate() reveals an issue here: a._updateInternal(a) crashes.

Maybe something like this:

var new = mlx_array_new()                                                                        
mlx_array_set(&new, array.ctx)                                                                   
let old = self.ctx                                                                               
self.ctx = new                                                                                   
mlx_array_free(old)                                                                              

or maybe just check for pointer equality (we are tightly coupled to mlx so this is ok):

        if self.ctx.ctx == array.ctx.ctx {
            return
        }

@davidkoski

Copy link
Copy Markdown
Member

The macOS failure was this change: a._updateInternal(a) cleared self.ctx before copying from array.ctx, so the array came out empty (testShardPredicate reaches that through Module.update(parameters:)). d424c1c copies into a new handle before freeing the old one and adds testUpdateInternalWithItself, which aborts without the fix. Full suite passes locally on the branch merged with current main (385 tests, 2 skipped).

Cool, your solution looks good -- I made a comment on this same thing. CI running again.

@davidkoski
davidkoski merged commit f93decf into ml-explore:main Oct 16, 2026
7 checks passed
eejd pushed a commit to eejd/mlx-swift that referenced this pull request Oct 18, 2026
Brings in ml-explore#501 (leak when _updateInternal replaces an array with siblings),
ml-explore#502 (enable JACCL) and ml-explore#486 (asArray crash on zero-size arrays). No conflicts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
rcfa added a commit to osaurus-ai/vmlx-swift that referenced this pull request Oct 30, 2026
quantized(w) builds one Quantize primitive with three outputs. Until
they are evaluated, each output holds its siblings, and through the
primitive the input w. ml-explore/mlx#4453 moved the destructor's
break of that cycle into array::release(), which the copy assignment
now runs too; vmlx's mlx pin has it. _updateInternal replaces an array
with mlx_array_set, a copy assignment, as Module.update(parameters:)
does for each parameter of a freshly built QuantizedLinear. Before
ml-explore/mlx#4453 that assignment was a plain descriptor copy, so
the last replacement left the cycle alive, and with it w's buffer.
ml-explore/mlx-swift#501 fixed the same leak on the Swift side, for an
mlx without ml-explore/mlx#4453.

No vmlx test covers either path. Two tests measure the active memory
left once every handle is gone: after the three outputs are dropped
(the destructor), and after each is replaced through _updateInternal
(the assignment). Each first synchronizes the GPU stream, since CI
runs the whole MLXTests bundle in one process. Each also asserts that
w's buffer is still active once w's own handle is gone, so the graph
holds it and the measurement can fail. Both pass, alone and with the
whole bundle. With mlx-c's mlx_array_set_ changed to a plain
descriptor copy, as before ml-explore/mlx#4453, the second test fails
by w's 4 MiB buffer.
xocialize added a commit to xocialize/mlx-engine-swift that referenced this pull request Nov 5, 2026
…ternal sibling-leak fix (AB-A-0249, AB-D-0208)

mlx-swift ≤0.32.3's MLXArray._updateInternal assigns over the old array
(mlx_array_set = C++ copy assignment), skipping ~array()'s sibling-cycle break.
Module.update(parameters:) goes through it, so every quantized load leaks 4
scalar Metal buffers per quantized layer; LTX 2.5 reloads its Gemma 4 encoder
per run and hits MLX's 499,000-buffer limit after ~379 runs (AB-T-0429,
AB-L-0330).

Upstream fixed it (ml-explore/mlx-swift#501) in 0.33.0, which the fleet can't
resolve yet (mlx-swift-lm 3.32.3 and ltx-2-mlx-swift cap <0.33.0). The engine
now takes the fleet fork xocialize/mlx-swift from: "0.32.4". Its 0.32.4 tag is
upstream 0.32.3 + #501's commit, nothing else. Every admitted version carries
the fix (fork 0.32.4, or upstream ≥0.33.0 when a root names ml-explore's URL).

docs/architecture.md: where mlx-swift comes from, SwiftPM's same-identity rules
(root wins; transitive is last-met, silent), and what a consumer declares.
getting-started.md points there. README status block v0.74.1; contract
unchanged (1.59.0).

Verified: engine build + tests green on fork 0.32.4 and 0.33.0. gaea-plugin-ltx
ltx-inproc through this engine + fork: GAEA_PROBE_SIBLINGS flat at 8 B a
round (+1,600 unpatched); Gemma 4 q4 load ×3 flat at 8 B (+5,248 a load
unpatched).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
xocialize added a commit to xocialize/mlx-engine-swift that referenced this pull request Nov 19, 2026
mlx-swift-lm 3.33.0 requires mlx-swift 0.33, so the fleet can take
upstream's _updateInternal leak fix (ml-explore/mlx-swift#501, in 0.33.0)
directly. Retires the xocialize/mlx-swift 0.32.4 fork (AB-D-0208).
Consumers drop their root fork line; a graph that still caps mlx-swift
<0.33 resolves v0.81.0 or older. Contract unchanged (1.66.0).

Full swift test (swiftbuild) passes on 0.33.0; the only skips are the
env-gated live tests.

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.

2 participants