Repository navigation
Conversation
Added tokenId: Int parameter to Generation.chunk(String, tokenId: Int). This enables downstream consumers to detect special tokens at the token ID level (e.g. gpt-oss channel markers: <|channel|>=200005, <|start|>=200006, <|end|>=200007, <|message|>=200008) without relying on text matching. The detokenizer strips special tokens before text reaches consumers, so token IDs are the only reliable way to detect channel boundaries.
- New LayerPartitioning.swift: LayerPartitionable protocol and partitionedLayerCall() helper that routes individual transformer layers to CPU via Device.withDefaultDevice(.cpu). Zero overhead when gpuLayerCount is nil (default behavior unchanged). - Model conformance for 5 architectures: - Qwen2ModelInner - Qwen35TextModelInner (SSM/attention hybrid) - LlamaModelInner (also covers Mistral) - GemmaModelInner - GPTOSSModelInner (sliding/full attention) - ModelContainer.setGPULayers(Int?) API: Recursive module tree search finds the LayerPartitionable inner model and configures the GPU layer count. Returns actual count after clamping. On Apple Silicon with UMA, CPU<->GPU data transfer is zero-copy. The compute engine is the only difference — CPU layers run ~5-8x slower but free GPU command buffer capacity for the remaining layers.
Phase 3c — mechanical expansion of GPU/CPU layer partitioning to all major model architectures with the standard layer loop: Phi3, Cohere, Starcoder2, Olmo2, Olmo3, InternLM2, Gemma2, Qwen3, Qwen3MoE, Phi, MiniCPM, GLM4, Granite, OpenELM, SmolLM3 Total coverage: 20 of ~50 architectures (covers all popular models). Each model gets +4 lines: LayerPartitionable conformance, gpuLayerCount property, totalLayerCount computed property, and partitionedLayerCall() wrapper around the layer forward pass. Backward compatible — default gpuLayerCount=nil means all GPU.
The protocol was incorrectly on ApertusModel (outer), but gpuLayerCount was referenced in ApertusModelInner (inner). Fixed by placing the conformance on the inner class, matching the pattern of all other models.
…ested LayerPartitionables
…nguage.Model to support memory offloading for Qwen3.5 VLMs
…erator.tokenCount to detect maxTokens length stopReason in generateLoopTask
…to enforce memory limits
…b to fix garbage output
Replace private let EXPERIMENTAL_TURBOQUANT = false with public var turboQuantEnabled: Bool = false so callers (Server.swift) can activate 3-bit KV compression at runtime without recompiling.
- TurboQuant now activates correctly at 512 context tokens instead of 8192 - Bounded history segment to previous/2 instead of hard 4096 - Suppress noisy 1s-interval Swift-level SSD stream log
KVCacheSimple now: - Tracks compressedOffset (tokens in polarKeys/polarValues) - Actually truncates self.keys/values to hot window after compression - Accumulates polarKeys across multiple compression events AttentionUtils now: - Detects KVCacheSimple with compressed history - Calls MLXFast.turboDecodeK/V to batch-decode packed history - Concatenates decoded history + hot window before SDPA This activates actual RAM savings: history tokens live in 3-bit packed form; only the recent hot window stays in fp16.
…log aggregation - KVCache.swift: compress every incoming token immediately (no hot-window split) matches TurboQuantKVCacheV3.update_and_fetch() reference design - AttentionUtils.swift: TurboKV stats now feed C atomic in moe_stream_op.cpp appear in the 10s SSD Stream log as '| 🗜 TurboKV 4244t 4.3x' zero per-event log spam
…ore SDPA Bug: polarKeys contains compressedOffset tokens including the current batch. Decoding all polarKeys + concatenating with cachedKeys → current batch appears twice. Fix: only prepend the first (compressedOffset - numNew) decoded tokens. SDPA now sees exactly [prior_history | current_raw] with no duplication.
- KVCache: always write to fp16 buffer first; compress cold tokens (>256 old) only when a full step's worth accumulate. Evict compressed tokens from fp16. - AttentionUtils: cachedKeys = fp16 hot window, polarKeys = prior history. Disjoint by construction — no histLen slicing needed. Benefits: Short prompts (<256t) → zero compression, full fp16 quality → fixes 0/3 Context Preprocessing Long context (>512t) → older history compressed at 4.3x Prompt-cache restore → restored fp16 stays in hot window, not silently lost
Compression now only triggers at offset > 1024 tokens (512 hot + 512 step). Context Preprocessing tests (<1000 tokens) run entirely in fp16 — no 3-bit quantization noise. Long-context compression behaviour unchanged.
- state getter: when TurboKV active, decode polarKeys + hot window → full fp16. Prompt cache saves the complete context, not just the 256-token hot window. - state setter: clear all TurboKV state on restore. Full fp16 context lands in self.keys and compression resumes naturally as new tokens arrive. Root cause of progressive benchmark degradation (Topic Classification 0/4, Knowledge Distillation 0/2): prompt cache was saving only the hot window, causing every subsequent request to see a truncated system prompt. Also reverts hot window from 512 back to 256 tokens.
TurboKV compression now only activates when total context > 2048 tokens. All shorter requests (tool-use, Q&A, short context) run at full fp16. Fixes: Context Preprocessing 4/6 → 5/6 (551-token test no longer compressed) Tool Use 0/4 → should recover (800-1500t tool schemas no longer compressed) Hot window stays at 256 tokens for genuinely long contexts (>2048t).
- Speculative decoding (Evaluate.swift) - copy() protocol added to KVCache - RoPEApplication refactor across all models (46 files, minor boilerplate) - Decouple from tokenizer/downloader (new BenchmarkHelpers, IntegrationTestHelpers) - chatSession multiple tool calls, embedding pooling fixes - skills/ references added Conflicts resolved in favour of our fork: - Package.swift: kept local mlx-swift path + swift-transformers (not upstream remote URL) - ModelConfiguration.swift: kept our preparePrompt/lazyLoad params
Feature/gemma 4 inference aha moment
- Slice attention mask to match physical KV cache dimensions after cache.update() to prevent broadcast_shapes crashes - Apply safeMask logic to both quantized and dense KV cache paths - Handle 2D and 4D mask dimensionality - Fixes fatal crash on 1370+ token tool-use prompts with Gemma4-26B Benchmark: 87/96 (90%) on HomeSec-Bench with zero server crashes
… 8-bit model quantization
…ng mixed-precision load
Feature/gemma 4 inference aha moment
feat: permanently disable PAPPS N+1 heuristic to restore native Apple TPS
…r downstream SPM resolution
fix: Swap local path mlx-swift dependency for remote URL
Qwen3.5-122B-A10B-4bit on M1 Ultra 64GB: - Batch eval: collapse ~1400 per-expert eval calls to ~48/token - Cross-projection batching: orchestrate gate/up/down in SwitchGLU - Eval reduction: skip redundant partitionedLayerCall eval (KV cache forced transitively via lazy dependency chain) - Concurrent pread: DispatchQueue.concurrentPerform for QD=24 NVMe SwitchLayers.swift: - ExpertRange struct for cross-projection expert tracking - allocateExpertBuffers/loadExpertWeights/computeExperts helpers - SwitchGLU cross-projection SSD path with merged eval - concurrentPerform replaces sequential pread (8x3=24 parallel reads) LayerPartitioning.swift: - Skip per-layer eval when isSsdStream (next layer forces via chain) - Remove Stream.gpu.synchronize() for SSD path Benchmark: 200 tokens generation, M1 Ultra 64GB Baseline: 0.58 tok/s (1720ms/tok) This: 4.95 tok/s (202ms/tok) — 8.5x improvement Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Overlaps NVMe I/O with GPU compute using persistent expert buffers and previous-token routing prediction. ~5.04 tok/s (+4% over v1). - Persistent buffers: allocated once per SwitchGLU, reused across tokens - asyncEval(idx) starts GPU work (prev layer compute + attention/router) - Speculative pread loads predicted experts during GPU async window - Only miss experts (~30%) need on-demand pread after routing sync - Cold path (first token) falls back to baseline merged eval
Allows reducing the number of active experts per token at runtime without model recompilation. Benchmarked on Qwen3.5-122B-A10B-4bit: top-k=8 (default): 4.84 tok/s baseline top-k=4: 5.91 tok/s (+22%) top-k=2: 6.52 tok/s (+35%, still coherent) top-k=1: garbage output Recommended: SWIFTLM_TOP_K=4 for best quality/speed tradeoff.
…ybrid models Add DraftModelRef wrapper and speculative generate path to ModelContainer. Enable speculative decoding on hybrid Attention+Mamba architectures by implementing checkpoint-based rollback on MambaCache (recurrent state cannot be trimmed like attention KV caches). ModelContainer.swift: - DraftModelRef: @unchecked Sendable wrapper for LanguageModel refs - extractDraftModel(): extract model ref from loaded container - generate(speculative): routes to SpeculativeTokenIterator via context KVCache.swift: - MambaCache.checkpoint(): deep-copies recurrent state before speculation - MambaCache.trim(n): restores checkpoint on rejection (n>0), clears on full acceptance (n==0) - MambaCache.isTrimmable: now returns true Evaluate.swift: - SpeculativeTokenIterator.speculateRound(): checkpoints MambaCache layers before each draft generation round Tested with Qwen3.5-122B (hybrid Attention+Mamba+MoE). Note: speculative decoding is counterproductive for SSD-streaming MoE models where the bottleneck is I/O not compute. Works correctly for in-RAM models.
Feat/ssd streaming 10x
…back on dense main branch
davidtai
added a commit
to davidtai/mlx-swift-lm
that referenced
this pull request
Oct 6, 2026
…ore#210) Materialize broadcast retained KV into a complete contiguous destination while preserving bit values, ownership validation, and reservation bounds. Focused differential paging, lifetime, and bit-exact validation completed during review.
davidtai
added a commit
to davidtai/mlx-swift-lm
that referenced
this pull request
Oct 6, 2026
ml-explore#289) * fix(cache): preserve demanded fork checkpoints and bound short capture * test: let expected paged work refusals reach the caller (ml-explore#209) PagedWorkFixture.prepare wrapped prepareAttentionWork in XCTUnwrap. XCTUnwrap records a test failure when its expression throws, also when the caller expects the throw with XCTAssertThrowsError. Three tests expect prepare to refuse, so each expected refusal was recorded as a failure. prepare now throws the refusal to the caller and fails only when prepareAttentionWork returns nil. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit b7bbdc2) * fix(paged): write a full destination for broadcast direct KV (ml-explore#210) Materialize broadcast retained KV into a complete contiguous destination while preserving bit values, ownership validation, and reservation bounds. Focused differential paging, lifetime, and bit-exact validation completed during review. (cherry picked from commit 3799b11) * test(mimo): skip native-lane tests on machines without the lane (ml-explore#192) Since eeba2af (ml-explore#178), 31 XCTest cases in five MiMo suites throw nativeLaneRequired on the hosted CI runner, so every run of Fork Tests on main fails. The tests need the exclusive native GPU lane, which the runner does not have. This change turns each of those throws into an XCTSkipUnless on the same environment variables. The tests now skip, with the reason, on a machine without the lane, and run as before where the variables are set. The unused nativeLaneRequired enum case is removed from each suite. Tests only. No production code change. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit c288f53) * test(mimo): assert the MiMo contracts that ml-explore#171 shipped (ml-explore#211) Three assertions in the MiMo tests disagree with the code that the same PR (ml-explore#171) added: - The MiMo cache conforms to CBv2MTPRectangularSerializing, and MiMoV26RectangularVerifyTests asserts that the bank supports rectangular MTP verification. The test asserted the opposite. - CBv2PrefillRequirement.evaluationOnly returns a [B, 1] handle (EngineLoopV2.prefillOutput). The test expected shape [1]. - MiMoV26MTPAssistant conforms to CBv2HistoricalMTPPrefixCheckpointCoding (MiMoV26MTPPrefixCheckpoint). The test asserted that it is not a prefix checkpoint drafter. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 5e9d268) * test: run bit-exact reference tests only on reference hardware (ml-explore#174) * style: format DiffusionGemmaVisionOracleTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: format DiffusionGemmaFactoryTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: run bit-exact reference tests only on reference hardware Nine DiffusionGemma tests compare float bits with frozen references. On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits, with no change in shape, dtype or sign. Add a `.referenceHardware` Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1, and mark the nine tests with it. Elsewhere they report as skipped with the reason. No assertion, tolerance or reference changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the bit comparisons of mixed DiffusionGemma tests Three gated tests also held checks that pass on any hardware. Split them so only the bit-for-bit comparison is gated: - prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its fail-closed probes on all hardware. The donor-logits bit comparison moves to failClosedProbesLeaveDonorLogitsBitExact(). - nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and model-release checks on all hardware. The logits bit comparison moves to nativeFactoryDenoiseMatchesReferenceBits(). - The two parameterized vision tests run their bf16 case on all hardware. The fp32 case moves to a separate gated test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the reference comparisons of three more DiffusionGemma tests Split the three tests that were still gated whole, so their checks that pass on any hardware run everywhere: - chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the prefill bounds, the complete flag, the counters, cancel, the emitted checkpoint and the released cache for widths 1, 3 and 7. The KV and logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference(). - sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture checks, both cache positions and the unchanged encoder KV after the provisional canvas. The reference comparisons stay in sharedWeightsConditioningAndCommittedCacheMatchReference(). - committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the token count, retained bytes, donor release and both positions. The reference comparisons stay in committedPrefixRestoreIsExactAfterDonorAppendAndRetirement(). Each pair shares one helper. The fixture reference, case-count and parameter-count checks of the block and fp32 vision fixtures also run everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned(). CONTRIBUTING.md says which comparisons the gate covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit a046367) * docs: describe demanded checkpoints and their shared fixture * fix(cache): honor request participation in short checkpoint scheduling * Preserve demanded checkpoint eligibility through preemption and packing * test: size the slot-cap request from what the ledger accepts slotCapLeavesRoomForServing() sized its request from bytesReserved. bytesReserved includes the paged pool's physical-floor overhead, which a request's target KV replaces when it reserves. The overhead depends on the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a 49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide cache. When earlier work left 64 KiB buffers in the cache, the capped arm left more than 5.5 windows of real slack instead of half a window, and the uncapped arm's reservation fit. Find the largest request the ledger accepts beside the capped set with trial reservations, then take half a window off it. The assertions do not change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 06224a8) * Retain demanded native frontiers and preserve observed prefill endpoints * Document current SDK parameters and generation links * Disambiguate the task generation documentation link --------- Co-authored-by: David Tai <dtaipublic@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.