Skip to content

Serialize integration tests and their model loading. - #760

Merged
davidkoski merged 3 commits into
mainfrom
integration-memory
Nov 16, 2026
Merged

davidkoski merged 3 commits into
mainfrom
integration-memory

Conversation

@davidkoski

Copy link
Copy Markdown
Member

Proposed changes

  • many models were loaded at once
  • while interesting, this easily overwhelms memory

Tests should be inner types of ModelLoadingSuite:

extension ModelLoadingSuite {
    @Suite(.serialized) struct Qwen35CheckpointIntegrationTests {
        private let downloader = #hubDownloader()
        private let tokenizerLoader = #huggingFaceTokenizerLoader()
    }
}

extension ModelLoadingSuite.Qwen35CheckpointIntegrationTests {
    @Test(arguments: qwenMTPReferences)
    func publishedStandaloneHeadsLoad(reference: QwenMTPReference) async throws {

and should coordinate loading through the TestModelManager:

    private func loadDrafter(_ reference: QwenMTPReference) async throws -> MTPDrafterContext {
        try await TestModelManager.shared.load(
            "mtp-drafter-context:\(reference.id)@\(reference.revision)"
        ) {
            try await loadDrafterUncached(reference)
        }
    }

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: claude used to help with refactoring

@Suite(.serialized) struct MalformedSchemaErrorParityTests {}
}

extension ModelLoadingSuite.MalformedSchemaErrorParityTests {

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.

All of the tests are restructured like this -- previously each test may have been serialized, but each suite was able to run simultaneously. Locally this made the run peak at ~32G of memory (mlx-community/gemma-4-31b-it-8bit) and it completed in ~10 minutes. Previously I would get warnings that I was out of virtual memory!

Comment on lines -25 to -31
do {
try await ChatSessionTests.planetsCoherence(container: container)
} catch {
await releaseModel(configuration)
throw error
}
await releaseModel(configuration)

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.

Everything runs like this now so we can just use the shared infrastructure.

- many models were loaded at once
- while interesting, this easily overwhelms memory

- gate largest model on actually having enough memory to run it
@nwh

nwh commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Review: #760 — Serialize integration tests and their model loading

  • Author: davidkoski
  • Head: integration-memory @ dea49dc (3 commits), base main @
    4c91662
  • Size: 71 files, +858 / −377
  • PR CI: all green (lint, mac_build_and_test). The PR workflow does
    not build the IntegrationTesting Xcode project, so I checked that part
    locally (see Verification).

Summary

The PR fixes the integration suite running out of memory. Before, each suite
serialized its own tests, but different suites ran in parallel, so many large
models were loaded at once. The PR changes two things:

  1. ModelLoadingSuite: an empty @Suite(.serialized) parent. Every
    model-loading suite becomes a nested type
    (extension ModelLoadingSuite { @Suite struct X {} }), so .serialized
    applies to the whole tree.
  2. TestModelManager (new public actor in IntegrationTestHelpers): a
    process-global, single-slot cache.
    • Asking for the resident key returns the cached value.
    • Asking for any other key first unloads the resident value: it drops the
      reference, runs onUnload, then calls synchronize() and clearCache().
    • A FIFO async lock makes "unload + load" one step.
    • IntegrationTestModels becomes a thin struct wrapper around the manager.
    • The ad-hoc caches (evictLLM, _rung4Cache nonisolated(unsafe),
      per-file private let models) are removed.

The author reports the full run now peaks around 32 GB (Gemma 4 31B 8-bit) and
finishes in about 10 minutes, where before it hit VM exhaustion.

Verdict: approve, with a few suggestions. The design is simple and a clear
improvement. It also deletes a fair amount of fragile code
(nonisolated(unsafe) cache, manual evict/clear pairs). The lock and
cancellation logic looks correct. My main concerns:

  • The new global cache key ignores the downloader and tokenizer loader.
  • The change to the public IntegrationTestHelpers API is not mentioned in the
    PR.
  • Some composite cache keys leave out inputs, which is a latent hazard.

Verification

  • xcodebuild build-for-testing -project IntegrationTesting/IntegrationTesting.xcodeproj -scheme IntegrationTesting
    on Xcode 27.1 / macOS 27.2.1: TEST BUILD SUCCEEDED. No new warnings in the
    touched files.
  • I ran the -only-testing path that the PR documents in CONTRIBUTING.md and
    the README:
    IntegrationTestingTests/ModelLoadingSuite/ToolCallIntegrationTests/qwen35FormatAutoDetection()
    + qwen35EndToEnd(). Both passed (24.8 s). The log shows a single
    loading llm:mlx-community/Qwen3.5-2B-4bit@main [ModelContainer], so the
    second test reused the resident container as intended.
  • I did not run the full suite: it needs about 35 GB of downloads plus a
    large-memory machine.

Findings

1. (Medium) Global cache key ignores the downloader and tokenizer loader

IntegrationTestModels used to be an actor with its own per-instance cache. Now
every instance shares TestModelManager.shared, and the key is only
kind:id@revision [Type]. If two instances with different
Downloader/TokenizerLoader load the same model in the same process, the
second one silently gets the first one's container, built with the other
tokenizer.

The library README says IntegrationTestHelpers is "designed to be used by
integration packages that supply their own Downloader and TokenizerLoader".
Comparing two tokenizer back-ends in one test target is a plausible use, and it
would now pass for the wrong reason.

The same applies to the public EmbedderTests.* and
RerankerIntegrationTests.* helpers, which now route through the singleton.

Suggestion: include loader identity in the key. For example, give each
IntegrationTestModels instance a UUID, or use
"\(type(of: tokenizerLoader))/\(type(of: downloader))" in the kind prefix.

2. (Medium) Public API change in IntegrationTestHelpers is not called out

IntegrationTestHelpers is a library product (Package.swift:44). The PR
changes it in three ways:

  • IntegrationTestModels changes from actor to struct. This is mostly
    source-compatible, because the methods are still async.
  • evictLLM(_:) is removed. It was added in Integration tests: scope down heavy suites, fix flakes and memory pressure #480, and any external caller will
    now fail to compile.
  • Public helpers now depend on a global singleton whose docs say callers "are
    required to run serialized under ModelLoadingSuite". Downstream packages
    don't have ModelLoadingSuite. If their tests run in parallel:
    • Tests evict each other's models, which causes reload thrash.
    • The "one model in memory" guarantee no longer holds, because the evicted
      container is still referenced by the running test.
    • The Box: @unchecked Sendable rationale ("only serialized tests") no longer
      holds either.

Suggestions:

  • Keep a @available(*, deprecated) evictLLM that forwards to
    TestModelManager.shared.unload().
  • Add a README note that downstream test targets should serialize model-loading
    tests.
  • Mention the API change in the PR description.

3. (Low) Some composite keys leave out inputs

  • MTPIteratorEndToEndDiagnosticTests.loadTargetAndDrafter: the key is
    TestModelManager.key("pair", target) and ignores
    drafterModelId/drafterRevision. All current callers pass the same drafter
    for a given target, so this works today. A future test that pairs the same
    target with a different drafter (or drafter revision) would silently get the
    wrong pair. Add the drafter to the key, as MTPGreedyVerification
    (mtp-pair:<target>+<drafter>) and Qwen35Checkpoint already do.
  • Qwen35CheckpointIntegrationTests: the pair key appends reference.id
    but not reference.revision. The standalone loadDrafter key does include
    the revision.
  • The "pair" kind is also used for drafter-only values
    (Gemma4AssistantIntegrationTests.loadDrafter31B,
    MTPDrafterModelFactoryIntegrationTests). The [Type] suffix prevents
    collisions, but the name is misleading; "drafter" would read better.
  • Key construction is inconsistent. Some sites use
    TestModelManager.key(...), others build raw strings
    ("vlm-context:\(dir.path)", "mtp-drafter-context:…"). A small helper for
    multi-model keys would make this uniform.

4. (Low) FoundationModels onUnload can cancel the load that triggered it

testLoad() registers
onUnload: { await makeTestModel(configuration.name).evict() }.
ModelCache.remove(modelID:) cancels any in-flight load task for that model
ID
. If the resident entry has the same base key but a different
ModelConfiguration, the sequence is:

  1. A new FM load for the same ID enters the manager.
  2. The manager sees the configurations differ and unloads the resident entry.
  3. onUnload evicts that model ID, which cancels the current in-flight
    ModelCache task.

This can happen with MultiTurnToolCallingTests, which uses
LLMRegistry.qwen3_4b_4bit (it has extraEOSTokens), while makeTestModel
uses the plain ModelConfiguration(id:).

It is usually masked, because ModelCache is keyed only by modelID and returns
the plain-config container before the manager is consulted. That masking is a
separate, pre-existing problem: MultiTurn's extraEOSTokens are silently
ignored when another test loaded Qwen3 first.

The race becomes reachable after a ModelCache-only eviction, such as
ColdHubClientFetchTests' evictAll().

Suggestion: have onUnload evict only if the cached container is the one
being unloaded. Alternatively, document that FM configurations for the same ID
must be identical.

5. (Low) Unstructured evictAll in ColdHubClientFetchTests

This is pre-existing, but the PR makes it more relevant.
defer { Task { await MLXLanguageModel.evictAll() } } runs after the test
returns, concurrently with the next serialized test. It can cancel that test's
in-flight FM load. Replace it with a structured await releaseAllGPUMemory() at
the end of the test, which now also unloads the manager. The suite is env-gated
(MLX_RUN_COLD_FETCH), so the impact is limited.

6. (Low) gemma31BEnabled() gates on Memory.memoryLimit

MLX sets memoryLimit to min(1.5 × recommendedMaxWorkingSetSize, 0.95 × RAM)
(allocator.cpp:63), which is an oversubscription ceiling, not wired GPU
capacity.

  • 32 GB and 36 GB Macs come out at about 30 GB and 34 GB, so they are correctly
    disabled.
  • A 48 GB Mac reports about 45.6 GB and is enabled, even though its
    recommended working set is about 36 GB. The 31B 8-bit target (about 33 GB)
    plus the drafter plus KV cache is likely to page there.
  • Any test that changes Memory.memoryLimit also changes the gate.

Consider gating on GPU.deviceInfo().maxRecommendedWorkingSetSize (or physical
RAM ≥ 64 GB) instead.

7. (Low) The guarantees depend on conventions that nothing enforces

  • Suite placement: a new suite added outside ModelLoadingSuite silently
    runs in parallel with it. This is cheap to detect. Under correct use, lock()
    should never be contended, because tests are serialized and loaders must not
    re-enter the manager. Logging a warning (or Issue.record) when
    busy == true on entry would catch a misplaced suite immediately.
  • Lingering references: "one model resident" only holds if the previous test
    dropped its references. The manager can't free a container that is still held
    elsewhere, for example by
    CoherenceIntegrationTests.weightProgressLoadsAndGenerates' out-of-manager
    load or by a future global. The unloaded … active NNNM log line helps; a doc
    note would too.
  • Hung loaders: the lock has no timeout. The doc comment says cancellation
    means "one stuck load doesn't hold every later test", but that is only true
    for waiters with a .timeLimit, and ModelLoadingSuite has none. Consider
    adding a suite-level .timeLimit, or rewording the comment.

8. (Nit) Side effects and churn

  • unloadResident() sets Memory.peakMemory = 0 globally. A test that measures
    peak memory across two different loads will be reset partway through. This is
    reasonable, but document it on load.
  • ToolCallIntegrationTests.swift adds import MLX and import MLXLLM, but
    neither appears to be used.
  • Changes unrelated to the PR's purpose that should be mentioned or split out:
    • .gitignore adds .worktrees.
    • ModelComponent.swift switches Logger to MLXLogger.
    • project.pbxproj re-sorts keys.
    • The .xcscheme is rewritten, including a version = "1.7" → "1.3"
      downgrade, which looks like Xcode churn.
  • Swift Testing doesn't guarantee that tests sharing a model run next to each
    other. Also, fm:X and llm:X are different keys, so FM and non-FM tests of
    the same model reload it. This only affects speed, not correctness.

Things done well

  • The FIFO lock with a cancellation-aware wait is implemented carefully:
    • Task.isCancelled is checked inside the continuation body.
    • cancelWaiter handles a waiter that was already handed the lock.
    • checkCancellation() runs after the lock is acquired.
    • defer { unlock() } is registered only after a successful lock().
  • resident = nil runs before onUnload and clearCache(), so ARC can
    actually free the weights.
  • TestModelManager.key(_:_:) uses a precondition to reject configurations
    with overrides, which prevents a stale-config hit.
  • Tests that need a fresh, cold load call unload() first and/or use unique
    keys: StaleWeightIndex, LFM2-VL lazy components, EmbeddingGemma2 memory
    comparison, and ColdHub's UUID key.
  • Target+drafter pairs are loaded as a single entry, so the manager doesn't
    evict half of a pair.
  • The 31B tests are now gated on available memory.
  • The -only-testing: paths in the docs were updated for the new
    ModelLoadingSuite/ prefix.

Suggested follow-ups (priority order)

  1. Include downloader/tokenizer-loader identity in IntegrationTestModels keys
    (don't need ninja as we don't have a cmake build #1).
  2. Add a deprecation shim for evictLLM and a README/PR note about the public
    API change (Nits in README #2).
  3. Add the drafter id+revision to the MTP pair keys (Fix broken link in README.md #3).
  4. Warn when the manager lock is contended, to catch suites placed outside
    ModelLoadingSuite (Embedding gemma #7).
  5. Gate the 31B tests on the recommended working set instead of memoryLimit
    (Consider alternative methods for deriving mlx-swift-lm repo #6).

@davidkoski
davidkoski merged commit dbee7be into main Nov 16, 2026
4 checks passed
@davidkoski
davidkoski deleted the integration-memory branch November 16, 2026 17:14
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 21, 2026
Apply the upstream commits dbee7be..cb59e9a (the 18 after 6352907) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- dbee7be Serialize integration tests and their model loading. (ml-explore#760)
- 7dde329 GLM-OCR: count the temporal patch in the pixel budget (ml-explore#783)
- f0d6150 fix: render null tool-call arguments in chat history (ml-explore#780)
- c6c6556 Base Gemma diffusion implementation (ml-explore#352)
- 5ecb13b Add LiquidAI LFM3 text support with extended validation and regression tests (ml-explore#756)
- 7e2c90f Match the DeepSeek-V3 MoE gate to mlx-lm (ml-explore#795)
- 700d8e2 Read r/u prefixes and adjacent string literals in PythonLiteralParser (ml-explore#799)
- c75b537 Keep the DeepSeek-V3 MoE output in the activation dtype (ml-explore#793)
- bc4746e Fix GLM-OCR small images; match smart_resize rounding in QwenVL.targetSize (ml-explore#764)
- b55217c Keep Qwen2-VL vision attention inside each image (ml-explore#755)
- dcfcf79 steering follow up and chat interrupt API (ml-explore#798)
- e589f33 Load Hadamard-rotated ternary checkpoints (prism_hadamard_qwen35) (ml-explore#630)
- cb2bd77 GPT-OSS: clip the SwiGLU with plain Float bounds (ml-explore#792)
- bf5a5d4 Declare measured budget transitions for Muse Glimmer and Qwen3.5 (ml-explore#734)
- 7517abc Let guided generation use the caller's sampler and logit processor (ml-explore#733)
- 5a14024 Refuse LoRA/DoRA on layers the adapters cannot reproduce (ml-explore#800) (ml-explore#803)
- ca661dc Size five float32 test comparisons for TF32 matmuls (ml-explore#802)
- cb59e9a Batching: Apply a per-row mask to each row of Gemma 2's grouped-query scores (ml-explore#772)

Conflict resolutions:
- ml-explore#760: the fork's MTPGreedyVerificationIntegrationTests keeps its fixture
  and moves under ModelLoadingSuite; the fixture loads the target and the
  drafter as one TestModelManager entry. The fork-only MiniMax M3 suites
  drop their private `models` for the shared one. .gitignore keeps both.
- ml-explore#352 diffusion: the edits to the monolithic Evaluate.swift and KVCache.swift
  go into the fork's split files (GenerateParameters, TokenIterators,
  GenerateTokens, GenerationLoop; KVCacheSimple/Chunked, RotatingKVCache,
  QuantizedKVCache). MTPSpeculation.makeTokenIterator builds the
  BlockDiffusionTokenIterator for a diffusion model, and throws
  unsupportedSpeculativeDecoding when a speculation is asked for, so every
  package path (FM executor, recording generate) takes it. ChatSession takes
  the diffusion branch before the fork's MTP eligibility check, with the
  pass's prompt token count; it takes no prompt-end checkpoint. The
  blockDiffusion guard is in the fork's shared private MTP init.
  TurboQuantKVCache saves the head width as a sixth meta-state value; the
  fork's strict prompt-cache validation accepts 5 (old files) or 6 values.
  The upstream KVCacheTests additions go into KVCacheTests and
  KVCacheQuantizationTests; MockMainModel (MLXLMTestSupport) gets
  `capabilities:`. New tests await the fork's async loadWeights.
- ml-explore#756 LFM3: model.validate(tokenizer:) runs before the fork's closed-
  reasoning end guard. The upstream LFM3CheckpointTests await loadWeights.
- ml-explore#755: the doc edit goes into the fork's PromptCacheFile.swift.
- ml-explore#798 interrupt: `.interrupted` and the steering boundary go into the fork's
  GenerationLoop and GenerationResults; TokenLoopHandler keeps
  emitOrCancel with `hasOutput`. Both reasoning-history tests are kept.
- ml-explore#734: the fork's QwenReasoningProtocol.qwen35 (history replay, closed
  thinking-off block) also declares the `.immediate` budget transition;
  upstream's second `qwen35` is folded into it. The family-delta test
  resets the fork's replay and prompt-strategy fields too.
- ml-explore#733: ported into the fork's GuidedDecoder/GuidedGenerationLoop split. A
  caller processor or sampler decodes plainly: guided MTP speculation stays
  greedy-only, so its output stays that of plain greedy decoding.
- ml-explore#802: the speculative log-probability test stays out (ml-explore#774 was dropped).

After the merge (CLAUDE.md):
- No manual `offset +=` after `advance(` in the merged models.
- HybridRecurrentCacheOffsetTests adds prism_hadamard_qwen35 (LLM and VLM
  classes), whose Qwen 3.5 caches include MambaCache.
- LFM3ReferenceTests.testLongContextChunking (gated by
  MLX_LFM3_LONG_CONTEXT) moves ungated to IntegrationTesting as
  LFM3LongContextProfileTests. The env-gated upstream IntegrationTesting
  suites LFM3CheckpointTests and LFM3TokenizerIntegrationTests stay gated.

Tests: MLXLMTests 1227 XCTest and 2459 Swift Testing (3 known issues),
MLXGuidedGenerationTests 85, MLXFoundationModelsTests 537, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 11 pass. Release, IntegrationTesting:
Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests,
PromptCacheSpoolCostAssessmentTests and LFM3LongContextProfileTests pass.

Co-Authored-By: Claude Opus 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.

2 participants