Repository navigation
Reduce Qwen3 reranking memory by projecting final tokens only - #621
Conversation
e053213 to
3756f8e
Compare
| /// Causal rerankers that can project only the final valid token of each right-padded row. | ||
| package protocol CausalRerankerModel: LanguageModel { | ||
| /// Returns `[batch, vocabulary]` logits for nonempty rows with the given valid lengths. | ||
| func lastTokenLogits(_ inputs: MLXArray, sequenceLengths: [Int]) -> MLXArray |
There was a problem hiding this comment.
This reminds me a bit of #387. Ultimately that was special purpose in that the caller needed to peer inside the model in a way that required knowing how the model worked. The particular caller matched something else which had this inner knowledge so it was important. In particular handling of masks, etc. was (IIRC) unusual but had to match other code.
Anyway, this looks a bit different (more generic), but I wanted to point that out as something in this area.
Is this reranker protocol suitable for all (or many) LLM models?
Is there a use for hidden states apart from projections? e.g. spitting this into:
func hiddenStates(_ inputs: MLXArray, sequenceLengths: [Int], cache: [KVCache]?) -> MLXArray
func projectLogits(_ hidden: MLXArray) -> MLXArrayThere was a problem hiding this comment.
Thanks, @davidkoski. Yes, this should apply to many causal decoder models, though I’d keep it an optional capability.
Splitting hidden states from projection makes sense for other scoring heads too, provided normalization, masking, and cache behavior remain model-owned. Unlike #387, this uses the existing forward pass and only selects states before projection.
I’d land this focused optimization first and explore the broader interface separately with another concrete consumer, I can probably prepare a follow up during the week end.
There was a problem hiding this comment.
OK, sounds good -- this is still package scoped so not committing to any visible API yet.
davidkoski
left a comment
There was a problem hiding this comment.
Looks good and I think ready to merge -- one question/rambling, see if there is anything to that, otherwise let's merge it.
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>
|
@davidkoski as promised open the refactoring in #672 , let me know if all good. |
…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>
Proposed changes
Reduce Qwen3 reranking computation and memory by projecting only each passage’s final valid token. Preserve the public API, singleton prefill, and fallback behavior for other models.
Benchmark
Apple M2, 16 GiB unified memory; Qwen3-Reranker-0.6B-4bit; 19 passages; maximum batch size 16.
Three warm repetitions, excluding model loading and tokenization. Controlled prototype measurements using Debug dependency builds not a Release benchmark of this commit or end-to-end application latency. Memory represents active MLX allocations(not process RSS).
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.