Skip to content

Declare the fused GDN projection as compile state so it frees with the model - #631

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
spokvulcan:upstream/fused-projection-compile-state
Oct 2, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
spokvulcan:upstream/fused-projection-compile-state

Conversation

@spokvulcan

Copy link
Copy Markdown
Contributor

Proposed changes

Unloading a Qwen3.5 model that ran the compiled decode path leaves its fused GDN input projections resident, so memory grows on every reload.

The fused projection prepare() builds is not a registered child of Qwen35GatedDeltaNet, so CompiledTrace's default state does not include it and the per-layer and decode-segment traces read its arrays as tape constants. MLX keeps a constant captured by a compiled function whose tape holds a multi-output primitive alive after the function is erased (ml-explore/mlx#3932). The fix declares the fused module as compile state wherever a trace runs a GDN layer, which is what the compile-state contract from #589 intends anyway.

testCompiledDecodeReleasesFusedProjectionWithTheModel runs three compiled decode steps, drops the model and asserts active memory returns to within 64 bytes of the baseline: 18,848 bytes retained on main, 4 with this change.

Measured in the app that embeds this library, Qwen3.5-27B 4-bit, MLX active memory in GB:

phase before after
resident at load begin, reload 1 / 2 / 3 3.0 / 5.3 / 7.6 0.76 / 0.76 / 0.76 (a second small model the app keeps)
resident after load 17.86 17.86

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)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: The leak was traced with an AI agent (heap and leaks tooling, then unit-level probes of which drop paths release a multi-output graph). The fix, the test and this description were drafted by the agent and reviewed by me.

…e model

The fused projection `prepare()` builds is not a registered child of
`Qwen35GatedDeltaNet` (the checkpoint topology stays the four projections),
so a trace's default state, the owner's `innerState()`, does not include
it, and the per-layer and decode-segment traces read its arrays as tape
constants. MLX keeps a constant captured by a compiled function whose tape
holds a multi-output primitive alive after the function is erased
(ml-explore/mlx#3932), so every load of a fused Qwen3.5 model left its GDN
projections resident: about 2.3 GB per load of the 27B, growing on every
reload.

Every trace that runs a GDN layer now declares the fused module as compile
state next to the layer, which is what the compile-state contract intends:
a trace's weights are inputs, not constants.

`testCompiledDecodeReleasesFusedProjectionWithTheModel` builds a quantized
fused model, runs three compiled decode steps, drops the model and asserts
active memory returns to within 64 bytes of the baseline. It fails before
this change and retains 4 bytes after (the kernel's scalar step count).

@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.

Change looks good, thank you!

@davidkoski
davidkoski merged commit 1830ae4 into ml-explore:main Oct 2, 2026
4 checks passed
spokvulcan added a commit to spokvulcan/mlx-swift-lm that referenced this pull request Oct 3, 2026
…rify traces

Upstream ml-explore#631 declares the fused four-way projection as compile state in
the decode and segment traces. The DFlash2 verify traces read it the same
way, so they take the same state (traceState(forLayers:)).
SiblingCycleTests probes the two mlx causes: an erased compiled function
that splits a captured constant keeps it alive (ml-explore/mlx#3932), and
assigning over a multi-output sibling skips the cycle break in ~array
(ml-explore/mlx#4453).

(rebased from 9ad90d7; the decode and segment halves merged upstream as ml-explore#631)
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Oct 3, 2026
Apply the upstream commits ee673d6..55db721 as a 3-way patch. CLAUDE.md is
excluded.

- c043fb3 pick up mlx-swift 0.32.2 (ml-explore#646)
- 0493daf Named image attachments in MLXLMCommon and the Foundation Models adapter (ml-explore#535)
- 0dcfe2f Convert the booleans in tool parameter schemas to Swift Bool values (ml-explore#653)
- 37dab60 be able to trigger workflows on main. notes about upcoming releases. (ml-explore#647)
- 390c5fd require mlx-swift-0.32.3 for SDK issue (ml-explore#657)
- 3b339ad adjustments for running tests on NAX/TF32 hardware (ml-explore#649)
- ac6f565 update documentation and skills (ml-explore#489)
- ce3950e Drop MTP weights from converted Qwen 3.5 VLM checkpoints (ml-explore#642)
- 9112fae Synchronize cross-SIMD WHT reads before shared-memory writes (ml-explore#650)
- 7e4024e NemotronH: MoE keys are optional, so dense checkpoints load (ml-explore#635)
- 1830ae4 Declare the fused GDN projection as compile state so it frees with the model (ml-explore#631)
- 6e0a0b2 Synchronize Metal before checking cached buffer memory (ml-explore#667)
- 9afc3b5 Recommend upToNextMinor in installation instructions (ml-explore#668)
- 55db721 Reduce Qwen3 reranking memory by projecting final tokens only (ml-explore#621)

Conflict resolutions:

- MLXLanguageModel.swift: keep the drain coordinator and runRespond of
  stable, and keep historyMessages. Add the upstream attachment label
  validation before resolveConfiguration. historyMessages now throws,
  because TranscriptConverter.mlxMessages now throws.
- TranscriptConverter.swift: keep the mlxMessages(for:replayReasoning:) and
  convert(entry:) form of stable. Apply the upstream changes in
  convert(entry:): it throws, an instructions entry drops its images, and
  extractImages(from:in:) applies the orientation and rejects content that
  is not an image.
- Chat.swift: keep the doc comments of stable, and add the upstream
  MessageContentLayout and contentParts(for:layout:).
- TurboQuantKernels.swift: keep stable. Stable already fixed the same
  cross-SIMD WHT race with two barriers per stage.
- KVCacheTests.swift: take the upstream file (upstream changed it to a
  suite). Delete the upstream ArraysCache.advance test, because in this fork
  advance(_:) also moves offset. Add the fork tests for advance and the
  trim-then-continue test at file scope.
- Qwen35FusedGDNProjectionTests.swift: keep the deletion of the opt-in
  benchmark (it skips unless an environment variable is set). Add the new
  upstream memory test.
- model-container.md: take upstream (llama3_2_3B_4bit and the macros are
  the real API).
- TranscriptConverterTests.swift: the replayReasoning calls now use try.

Tests: MLXGuidedGenerationTests 70, MLXFoundationModelsTests 349,
CXGrammarTests 7, MLXHuggingFaceMacrosTests 5 pass. MLXLMTests: 1287 Swift
Testing tests pass, and 699 of 700 XCTest tests pass. The failure is the
wall-clock limit of EvalTests
testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmoke (0.29 s,
limit 0.25 s) in the full run. The test passes alone two times, and this
merge does not change EvalTests.swift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Augustas11 pushed a commit to Augustas11/mlx-swift-lm that referenced this pull request Oct 9, 2026
…e model (ml-explore#631)

Fix memory leak from unregistered fused GDN projections in Qwen3.5

Because `prepare()` does not register the fused projection as a child of `Qwen35GatedDeltaNet`, traces treated its arrays as tape constants rather than state. Due to ml-explore/mlx#3932, these constants remained resident after function erasure, leaking ~2.3 GB per reload on 27B.

Traces running GDN layers now explicitly declare the fused module as compile state. Verified with `testCompiledDecodeReleasesFusedProjectionWithTheModel`.

(cherry picked from commit 1830ae4)
Augustas11 added a commit to Augustas11/mlx-swift-lm that referenced this pull request Oct 9, 2026
The compiled MTP verification segments (1007bc6) declared the segment's
layers, embedding and final norm, but a GDN layer's fused input
projection is not a registered child, so the verify traces read its
arrays as tape constants, exactly like the decode and per-layer traces
before ml-explore#631. They now declare the same state as the decode segments
(`traceState(forLayers:)`), so every weight a Qwen3.5 trace reads is a
compile input.

A tape constant is not only a leak. MLX keeps compiled traces in a
per-thread cache keyed by the CompiledFunction's address, and mlx-swift
erases a freed function only from the cache of the thread that frees
it. Every other thread keeps the dead function's trace, and a new
function allocated at the same address replays it on that thread: the
declared inputs are the new model's, the constants are the old trace's.
Two GDN layers (or two middle segments) share an input signature, so a
reload can run one layer with another layer's fused projection. On the
Studio A3B harness, 24 in-process reloads (with allocation churn) of the 3.32.3-macprovider.3
build left about 200 orphaned trace entries per reload, replayed 32 of
them, and 4 replays of GDN layer traces differed from a fresh trace (max
abs diff 8-19); that request's native output diverged from the ordinary
arm in s1-p4096-o512. Forcing every same-signature trace to share one
cache entry fails the startup batched-isolation gate on the old build
and leaves all 24 matrix outputs bit-identical on this one.

The fused-MoE cache holds the block's own parameter objects, which the
block's or layer's trace already declares. A module replacement or a
parameter update now drops it, so it can never hold arrays a trace does
not declare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
slamfinger pushed a commit to slamfinger/mlx-swift-lm that referenced this pull request Oct 14, 2026
…e model (ml-explore#631)

Fix memory leak from unregistered fused GDN projections in Qwen3.5

Because `prepare()` does not register the fused projection as a child of `Qwen35GatedDeltaNet`, traces treated its arrays as tape constants rather than state. Due to ml-explore/mlx#3932, these constants remained resident after function erasure, leaking ~2.3 GB per reload on 27B.

Traces running GDN layers now explicitly declare the fused module as compile state. Verified with `testCompiledDecodeReleasesFusedProjectionWithTheModel`.
spokvulcan added a commit to spokvulcan/mlx-swift-lm that referenced this pull request Oct 27, 2026
…rify traces

Upstream ml-explore#631 declares the fused four-way projection as compile state in
the decode and segment traces. The DFlash2 verify traces read it the same
way, so they take the same state (traceState(forLayers:)).
SiblingCycleTests probes the two mlx causes: an erased compiled function
that splits a captured constant keeps it alive (ml-explore/mlx#3932), and
assigning over a multi-output sibling skips the cycle break in ~array
(ml-explore/mlx#4453).

(rebased from 9ad90d7; the decode and segment halves merged upstream as ml-explore#631)
ximyro pushed a commit to ximyro/mlx-swift-lm that referenced this pull request Nov 4, 2026
…ft-lm

Real merge (--no-ff), no cherry-picks. Brings in upstream UserInput
Audio/Video/Image structs with Source enums, contentParts(for:layout:),
removingSpecialTokenLabels, MatmulPrecision.splitTolerance, the WHT
barrier fix (ml-explore#650), fused GDN projection compile state (ml-explore#631), MTP
weights dropped from converted Qwen3.5 VLM checkpoints (ml-explore#642), NemotronH
optional MoE keys (ml-explore#635), Metal sync before cached buffer memory (ml-explore#667),
reranker changes (ml-explore#621/ml-explore#651) and the mlx-swift 0.32.3 requirement (ml-explore#657).

Conflict resolutions (fork behavior kept on purpose):
- Package.swift: keep the local path dependency on ../mlx-swift.
- UserInput.Audio: upstream's struct + Source enum, plus the fork-only
  .data(Data, format:) source; UserInput+Audio.swift handles it.
- Qwen2VL / Gemma4 message generators: upstream contentParts(for:layout:)
  plus the fork-only audio placeholders; Gemma4 keeps its plain-string
  early return for non-user messages without media.
- Qwen35 (VLM) sanitize: keep the MTPConfig.retainMTPWeights guard.
- TurboQuantKernels: upstream's WHT barrier fix.
- ContinuationAssertions: noise-floor tolerances combined with
  MatmulPrecision.splitTolerance.
- KVCacheTests: 3-way merged after wrapping the fork side in
  @suite(.serialized) like upstream; upstream's eval(arrays) fixes kept.
  The fork-only `extension MLXTestingSuite { ... }` block stays at file
  scope after the wrapped struct.
- MediaProcessing.extractAudioSamples (fork-only): switch on
  `audio.source` now that UserInput.Audio is a struct.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants