Repository navigation
fix(provider): Gemma 4 VLM continuous-batched decode — no more repetition - #369
Conversation
…tion Bumps mlx-swift-lm to the per-row RoPE + mask-kernel fix (Layr-Labs/mlx-swift-lm#41) and adds regression coverage. Gemma 4 loads via VLMModelFactory (it declares vision_config); the VLM model's batched text path used a scalar RoPE offset (wrong positions for shorter rows in mixed-length batches) and the mlx#3384 explicit-mask fused kernel, together causing token-repetition loops on 4-bit builds. See the submodule PR for the root-cause writeup. Tests: ContinuousBatchingLiveTests.gemma4VLMMixedLengthCoherent loads the 4-bit QAT build via VLMModelFactory and asserts a mixed-length B=2 greedy batch is coherent (fails pre-fix with 'the era of the era of...', passes post-fix). BatchKVCacheTests adds a case asserting .none mask for unpadded n==1 decode and .array when any row is padded.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No threat-model-mapped files were changed; however, two of the three changed paths touch security-adjacent inference engine code and warrant a brief note. Trust boundaries touchedNone of the changed files are listed under any Per-threat assessmentNo existing T-xxx entry is directly triggered. Closest adjacencies for awareness:
New attack surface not covered by an existing threat
Recommended action: add SEC-* findings resolvedNone — this PR does not resolve any open SEC-* finding. 🔐 Threat model: |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 3 finding(s) (1 blocking)
- 🟡 [MEDIUM]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:126-130— Redundant tokenizer.applyChatTemplate calls in map - could pre-compute template once- Suggestion: Extract chat template application outside the map or cache the template format to avoid repeated template processing for each prompt
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:158-162— O(n²) nested loop in hasDegenerateRepetition for pattern matching- Suggestion: Consider using a rolling hash or KMP algorithm for pattern detection, especially for longer token sequences
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:164-170— Array slice allocations in tight loop without pre-allocation- Suggestion: Pre-allocate gram array outside the loop and reuse it, or use array indices instead of creating new slices
Type_diligence — ✅ No issues found
Additive_complexity — 3 finding(s) (1 blocking)
- 🟡 [MEDIUM]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:89-110— Complex test setup duplicates production loading logic unnecessarily- Suggestion: Extract a shared helper for VLM container loading or use dependency injection to avoid duplicating production code paths in tests
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:158-175— Degenerate repetition detection could be extracted to shared utility- Suggestion: Move hasDegenerateRepetition to a shared test utility module since this pattern detection logic could be useful across multiple test files
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:111-157— Test has multiple environment variable dependencies and hardcoded values- Suggestion: Consolidate environment checks into a single test enablement flag and extract hardcoded values (maxTokens=110, minReps thresholds) to constants
6 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| container: container, prompts: encoded, maxTokens: maxTokens) | ||
|
|
||
| // The batched engine honors EOS, so coherent rows terminate cleanly. | ||
| // This is the path under test (per-row offset + manual masked attention); | ||
| // it must not degenerate into repetition. |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Redundant tokenizer.applyChatTemplate calls in map - could pre-compute template once
💡 Suggestion: Extract chat template application outside the map or cache the template format to avoid repeated template processing for each prompt
📊 Score: 3×4 = 12 · Category: Repeated work
| static func hasDegenerateRepetition(_ tokens: [Int]) -> Bool { | ||
| for n in 1 ... 4 { | ||
| let minReps = n == 1 ? 8 : (n == 2 ? 6 : 4) | ||
| var i = 0 | ||
| while i + n * minReps <= tokens.count { |
There was a problem hiding this comment.
🔵 [INFO] ⚡ O(n²) nested loop in hasDegenerateRepetition for pattern matching
💡 Suggestion: Consider using a rolling hash or KMP algorithm for pattern detection, especially for longer token sequences
📊 Score: 2×3 = 6 · Category: Inefficient data structures
| var reps = 1 | ||
| var j = i + n | ||
| while j + n <= tokens.count && Array(tokens[j ..< j + n]) == gram { | ||
| reps += 1 | ||
| j += n | ||
| } | ||
| if reps >= minReps { return true } |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Array slice allocations in tight loop without pre-allocation
💡 Suggestion: Pre-allocate gram array outside the loop and reuse it, or use array indices instead of creating new slices
📊 Score: 2×3 = 6 · Category: Unbounded allocations
| func gemma4VLMMixedLengthCoherent() async throws { | ||
| try ensureMetallibAvailable() | ||
| MLX.GPU.set(memoryLimit: 96 * 1024 * 1024 * 1024) | ||
|
|
||
| let modelID = ProcessInfo.processInfo.environment["DARKBLOOM_GEMMA_MODEL"] | ||
| ?? "mlx-community/gemma-4-26B-A4B-it-qat-4bit" | ||
| guard let modelDir = ModelScanner.resolveLocalPath(modelID: modelID) else { | ||
| Issue.record("model '\(modelID)' is not in the local cache") | ||
| return | ||
| } | ||
|
|
||
| // Production loads vision checkpoints through VLMModelFactory. | ||
| let container = try await VLMModelFactory.shared.loadContainer( | ||
| from: modelDir, using: LocalTokenizerLoader()) | ||
|
|
||
| // Deliberately different lengths so the shorter row carries left-padding | ||
| // (the case the scalar-offset bug mis-positions). Row 0 is the shorter, | ||
| // higher-entropy prompt — open-ended continuations have close argmax | ||
| // calls, so wrong RoPE positions / mask-kernel drift flip the top token | ||
| // and trap it in a loop (the "One of of of of" failure mode). | ||
| let prompts = [ | ||
| "Tell me something interesting about machine learning.", |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Complex test setup duplicates production loading logic unnecessarily
💡 Suggestion: Extract a shared helper for VLM container loading or use dependency injection to avoid duplicating production code paths in tests
📊 Score: 3×4 = 12 · Category: over-abstraction
| static func hasDegenerateRepetition(_ tokens: [Int]) -> Bool { | ||
| for n in 1 ... 4 { | ||
| let minReps = n == 1 ? 8 : (n == 2 ? 6 : 4) | ||
| var i = 0 | ||
| while i + n * minReps <= tokens.count { | ||
| let gram = Array(tokens[i ..< i + n]) | ||
| var reps = 1 | ||
| var j = i + n | ||
| while j + n <= tokens.count && Array(tokens[j ..< j + n]) == gram { | ||
| reps += 1 | ||
| j += n | ||
| } | ||
| if reps >= minReps { return true } | ||
| i += 1 | ||
| } | ||
| } | ||
| return false | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Degenerate repetition detection could be extracted to shared utility
💡 Suggestion: Move hasDegenerateRepetition to a shared test utility module since this pattern detection logic could be useful across multiple test files
📊 Score: 2×3 = 6 · Category: duplicate logic
| "Write a detailed multi-paragraph essay about the history, present state, " | ||
| + "and likely future of renewable energy technologies across the world.", | ||
| ] | ||
| let encoded: [[Int]] = try await container.perform { ctx in | ||
| try prompts.map { | ||
| try ctx.tokenizer.applyChatTemplate( | ||
| messages: [["role": "user", "content": $0]], | ||
| tools: nil, additionalContext: nil) | ||
| } | ||
| } | ||
| let maxTokens = 110 | ||
|
|
||
| let batched = try await runBatchedEngine( | ||
| container: container, modelID: modelID, prompts: encoded, maxTokens: maxTokens) | ||
| let single = await singleStreamGreedy( | ||
| container: container, prompts: encoded, maxTokens: maxTokens) | ||
|
|
||
| // The batched engine honors EOS, so coherent rows terminate cleanly. | ||
| // This is the path under test (per-row offset + manual masked attention); | ||
| // it must not degenerate into repetition. | ||
| for (k, toks) in batched.enumerated() { | ||
| let text = await container.decode(tokenIds: toks) | ||
| print("[gemma4-vlm-mixed] batched row \(k): \(text)") | ||
| #expect( | ||
| !Self.hasDegenerateRepetition(toks), | ||
| Comment(rawValue: "batched row \(k) degenerates into repetition: \(toks)")) | ||
| } | ||
| // The short, low-entropy row 0 is the one mis-positioned by the | ||
| // scalar-offset bug. Compare batched vs single-stream up to the natural | ||
| // end-of-turn (the fixed-length single-stream helper force-generates | ||
| // past EOS, so only the pre-EOS prefix is meaningful). With per-row | ||
| // offsets the two agree on the opening tokens. | ||
| let eos = 106 | ||
| let singleHead = Array(single[0].prefix(while: { $0 != eos })) | ||
| let batchedHead = Array(batched[0].prefix(while: { $0 != eos })) | ||
| let shortMatch = zip(batchedHead, singleHead).prefix(while: ==).count | ||
| #expect( | ||
| shortMatch >= 3, | ||
| Comment(rawValue: | ||
| "short row diverges immediately (batched=\(batchedHead) single=\(singleHead))")) | ||
| } | ||
|
|
||
| /// Detects degenerate generation: an n-gram (n = 1...4) repeated | ||
| /// consecutively many times — the signature of decode loops like | ||
| /// "of of of", "you've you've", or "the era of the era of the era of". | ||
| /// Coherent prose never trips this; the batching bug produces exactly | ||
| /// these cycles. |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Test has multiple environment variable dependencies and hardcoded values
💡 Suggestion: Consolidate environment checks into a single test enablement flag and extract hardcoded values (maxTokens=110, minReps thresholds) to constants
📊 Score: 2×3 = 6 · Category: over-configuration
Picks up Layr-Labs/mlx-swift-lm@f2f40e5 (Codex review hardening: only skip the decode mask when retained KV fits the window). No behavior change for Gemma; keeps #369 in sync with mlx-swift-lm#41.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 2 finding(s) (1 blocking)
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:126-130— Redundant tokenizer.applyChatTemplate calls in map - could pre-compute template- Suggestion: Consider caching the chat template result or restructuring to avoid repeated template application if the template format is identical across prompts
- 🟡 [MEDIUM]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:158-174— Nested loops in hasDegenerateRepetition create O(n²×k) complexity for token analysis- Suggestion: Use a sliding window approach or KMP-style pattern matching to reduce complexity from O(n²×k) to O(n×k) where n is token count and k is max n-gram size
Type_diligence — ✅ No issues found
Additive_complexity — 3 finding(s)
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:126-150— Complex test setup with multiple environment variables and fallback logic- Suggestion: Consider simplifying the test configuration - the nested environment variable checks and fallback model ID logic could be streamlined into a helper function or consolidated into fewer configuration points
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:158-174— Hardcoded test data that could be parameterized or shared- Suggestion: The prompt construction and encoding logic is specific but could potentially be extracted to a test helper if similar patterns emerge in other tests
- 🔵 [INFO]
provider-swift/Tests/ProviderCoreTests/ContinuousBatchingLiveTests.swift:176-200— Test method doing multiple validation steps that could be clearer as separate assertions- Suggestion: Consider breaking the coherence validation and token matching validation into separate, more focused test methods for better failure isolation
5 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| container: container, prompts: encoded, maxTokens: maxTokens) | ||
|
|
||
| // The batched engine honors EOS, so coherent rows terminate cleanly. | ||
| // This is the path under test (per-row offset + manual masked attention); | ||
| // it must not degenerate into repetition. |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Redundant tokenizer.applyChatTemplate calls in map - could pre-compute template
💡 Suggestion: Consider caching the chat template result or restructuring to avoid repeated template application if the template format is identical across prompts
📊 Score: 2×3 = 6 · Category: repeated_work
| static func hasDegenerateRepetition(_ tokens: [Int]) -> Bool { | ||
| for n in 1 ... 4 { | ||
| let minReps = n == 1 ? 8 : (n == 2 ? 6 : 4) | ||
| var i = 0 | ||
| while i + n * minReps <= tokens.count { | ||
| let gram = Array(tokens[i ..< i + n]) | ||
| var reps = 1 | ||
| var j = i + n | ||
| while j + n <= tokens.count && Array(tokens[j ..< j + n]) == gram { | ||
| reps += 1 | ||
| j += n | ||
| } | ||
| if reps >= minReps { return true } | ||
| i += 1 | ||
| } | ||
| } | ||
| return false |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Nested loops in hasDegenerateRepetition create O(n²×k) complexity for token analysis
💡 Suggestion: Use a sliding window approach or KMP-style pattern matching to reduce complexity from O(n²×k) to O(n×k) where n is token count and k is max n-gram size
📊 Score: 3×4 = 12 · Category: inefficient_algorithm
| container: container, prompts: encoded, maxTokens: maxTokens) | ||
|
|
||
| // The batched engine honors EOS, so coherent rows terminate cleanly. | ||
| // This is the path under test (per-row offset + manual masked attention); | ||
| // it must not degenerate into repetition. | ||
| for (k, toks) in batched.enumerated() { | ||
| let text = await container.decode(tokenIds: toks) | ||
| print("[gemma4-vlm-mixed] batched row \(k): \(text)") | ||
| #expect( | ||
| !Self.hasDegenerateRepetition(toks), | ||
| Comment(rawValue: "batched row \(k) degenerates into repetition: \(toks)")) | ||
| } | ||
| // The short, low-entropy row 0 is the one mis-positioned by the | ||
| // scalar-offset bug. Compare batched vs single-stream up to the natural | ||
| // end-of-turn (the fixed-length single-stream helper force-generates | ||
| // past EOS, so only the pre-EOS prefix is meaningful). With per-row | ||
| // offsets the two agree on the opening tokens. | ||
| let eos = 106 | ||
| let singleHead = Array(single[0].prefix(while: { $0 != eos })) | ||
| let batchedHead = Array(batched[0].prefix(while: { $0 != eos })) | ||
| let shortMatch = zip(batchedHead, singleHead).prefix(while: ==).count | ||
| #expect( | ||
| shortMatch >= 3, | ||
| Comment(rawValue: | ||
| "short row diverges immediately (batched=\(batchedHead) single=\(singleHead))")) |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Complex test setup with multiple environment variables and fallback logic
💡 Suggestion: Consider simplifying the test configuration - the nested environment variable checks and fallback model ID logic could be streamlined into a helper function or consolidated into fewer configuration points
📊 Score: 2×3 = 6 · Category: over-configuration
| static func hasDegenerateRepetition(_ tokens: [Int]) -> Bool { | ||
| for n in 1 ... 4 { | ||
| let minReps = n == 1 ? 8 : (n == 2 ? 6 : 4) | ||
| var i = 0 | ||
| while i + n * minReps <= tokens.count { | ||
| let gram = Array(tokens[i ..< i + n]) | ||
| var reps = 1 | ||
| var j = i + n | ||
| while j + n <= tokens.count && Array(tokens[j ..< j + n]) == gram { | ||
| reps += 1 | ||
| j += n | ||
| } | ||
| if reps >= minReps { return true } | ||
| i += 1 | ||
| } | ||
| } | ||
| return false |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Hardcoded test data that could be parameterized or shared
💡 Suggestion: The prompt construction and encoding logic is specific but could potentially be extracted to a test helper if similar patterns emerge in other tests
📊 Score: 2×2 = 4 · Category: duplicate logic
libs/mlx-swift-lm moves to main 25bcd63f, the squash merge of Layr-Labs/mlx-swift-lm#369 (the Harmony final-channel stop scope this PR depends on). SDK main calls mlx-swift APIs newer than the pinned M5 hotfix (MLXFast fencedInputs), so the stack moves with it to the revision SDK main declares, as #1596 did: libs/mlx-swift c633d221 (nested mlx 72dffa2d, mlx-c 2ac897e3) and libs/mlx 72dffa2d. All three are on their repos' main. 72dffa2d carries the NAX head-dim split attention JIT fix (mlx main 6bc9de5b), the same get_steel_attention_nax_kernel change as the 0.10.3 hotfix 31f550af. Provider adaptations for the new SDK enum cases, behavior-preserving: - MLXServerGenerationEvent.logprobs is token metadata, handled like .info by the GLM and JSON answer-format observers (the provider streams logprobs through its own channel and emits no such events today). - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens is the case the SDK split out of invalidResponseFormatOutput for a structured answer cut off by max_tokens; it keeps that case's 422 and retryable classification. Verified on M5 Max: Gemma 4 26B QAT serves an 8,204-token prompt (the 0.10.2 crash path) with an 8,192-token prefix hit on repeat; gpt-oss-20b stop ["."] still returns "The capital of Australia is Canberra". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#1645 now pins mlx-swift-lm 25bcd63f (#369 merged on SDK main), mlx-swift c633d221 and mlx 72dffa2d. The only conflict was the mlx-swift-lm pin. The two engine commits of this PR (95e1d2b9, b5d4c754 on branch fix/reasoning-stop-scope-exclude) are replayed onto 25bcd63f as 50ee329a and 25e65afc (branch fix/reasoning-stop-scope-exclude-on-25bcd63f), with an identical diff, and the pin moves there. Verified on the merged tree: SDK CBv2Sampling 55/55 (stop holdback 27/27); provider swift-testing 469 tests in 68 suites, XCTest 37/38 with the one failure only needing MIMO_PROMPT_ARTIFACT_DIRECTORY, which passes with the CI fixture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ares Layr-Labs/mlx-swift-lm#368 was squash-merged as 2beb401f, so this branch's former SDK pin 76ff231b (#368's head) is not on SDK main. Every gitlink now points at a commit on its fork's main: - libs/mlx-swift-lm 76ff231b -> 2beb401f, the tip of SDK main and the #368 squash. Merging 76ff231b into the previous main (25bcd63f) gives exactly 2beb401f's tree, so #368 (demandedLatestCheckpointMinimumTokens) is unchanged. The pin also brings what SDK main gained since master's aee6ebb6: the tensor-parallel engine (#308), Qwen tensor batching (#352) and the optional stop-string scope (#369). - libs/mlx-swift 4926d3d9 -> c633d221, the revision 2beb401f's Package.swift declares; mlx-swift main (52c36f86) has the same tree. SDK main calls mlx-swift APIs that 4926d3d9 lacks (MLXArray.sharingArray, the fencedInputs argument of MLXFast.metalKernel). The nested mlx-c moves from 004c735f to 2ac897e3 with it. - libs/mlx 31f550af -> 72dffa2d, the nested copy that Cmlx compiles at c633d221 (Source/Cmlx/mlx); mlx main (f24d7e63) has the same tree. 72dffa2d keeps the 0.10.3 M5 NAX head-dim split JIT fix: 31f550af is not its ancestor, but that fix's squash on mlx main (6bc9de5b, Layr-Labs/mlx#48, identical patch ID) is, and its jit_kernels.cpp change is intact. #1645 pins the same mlx-swift and mlx commits. Provider follow-ups for the SDK's new enum cases, identical to #1645's (46f7ae9 and 2185dfe) so the two branches merge without conflicts: - MLXServerGenerationEvent.logprobs is token metadata. The GLM and JSON answer-format observers and seven test helpers treat it like .info. No SDK engine or provider bridge emits it today; the provider sends logprobs through EngineV2LogprobsChannel. - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens, which the SDK split from invalidResponseFormatOutput for a structured answer cut off by max_tokens, keeps that case's 422 and retryable classification. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SDK main moved from the #369 squash (25bcd63f) to 2beb401f (#368). #368 only adds demandedLatestCheckpointMinimumTokens, which is nil by default and unset by this PR, so behaviour here is unchanged. With the same SDK pin as #1643, the two PRs merge cleanly in either order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y (fixes reasoning-only empty answers) (#1645) * GPT-OSS: match client stop sequences in the Harmony final message only The engine matched `stop` against every generated character, including the private Harmony analysis. A sequence that appeared while gpt-oss reasoned ended the request before any answer: finish_reason "stop", reasoning only, empty content. On provider 0.10.4 with production gpt-oss-20b weights, stop ["."] did this to 36/36 requests and ["\n\n"] to 14/36 (0/36 without a stop); each cut reasoning is an exact prefix of its same-seed no-stop twin, which went on to answer. ModelEOSPolicy.stopStringScope gives GPT-OSS the Harmony final-channel scope (<|channel|>final ... <|message|> up to <|end|>/<|return|>/<|call|>/<|start|>). It travels with the EOS policy: EngineV2SlotFactory -> makeBridge -> EngineV2Bridge -> CBv2Request.stopStringScope, and the matched-sequence replay uses the same scope. Other models keep whole-output matching. Bumps libs/mlx-swift-lm to 38b90ed1 (fix/harmony-final-stop-scope), which adds the scope to StopHoldback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Pin the merged mlx-swift-lm (#369) and the MLX stack it builds on libs/mlx-swift-lm moves to main 25bcd63f, the squash merge of Layr-Labs/mlx-swift-lm#369 (the Harmony final-channel stop scope this PR depends on). SDK main calls mlx-swift APIs newer than the pinned M5 hotfix (MLXFast fencedInputs), so the stack moves with it to the revision SDK main declares, as #1596 did: libs/mlx-swift c633d221 (nested mlx 72dffa2d, mlx-c 2ac897e3) and libs/mlx 72dffa2d. All three are on their repos' main. 72dffa2d carries the NAX head-dim split attention JIT fix (mlx main 6bc9de5b), the same get_steel_attention_nax_kernel change as the 0.10.3 hotfix 31f550af. Provider adaptations for the new SDK enum cases, behavior-preserving: - MLXServerGenerationEvent.logprobs is token metadata, handled like .info by the GLM and JSON answer-format observers (the provider streams logprobs through its own channel and emits no such events today). - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens is the case the SDK split out of invalidResponseFormatOutput for a structured answer cut off by max_tokens; it keeps that case's 422 and retryable classification. Verified on M5 Max: Gemma 4 26B QAT serves an 8,204-token prompt (the 0.10.2 crash path) with an 8,192-token prefix hit on repeat; gpt-oss-20b stop ["."] still returns "The capital of Australia is Canberra". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Handle the SDK's .logprobs event in provider test switches The re-pinned mlx-swift-lm adds MLXServerGenerationEvent.logprobs. Seven test helpers switch exhaustively over events; each treats it like its existing non-content cases (.info / skipped). No assertion changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: fresh run for Release Integrity Attempt 2 of run 40756992782 failed test_cli_result_write_failure_preserves_original_error_and_findings: the test inherits the runner's GITHUB_RUN_ATTEMPT=2, so the budget runner reports MANUAL_SCAN_RERUN_DISABLED. Attempt 1 on the same tree passed. No code change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(provider): pin SDK main 2beb401f, the same pin as #1643 SDK main moved from the #369 squash (25bcd63f) to 2beb401f (#368). #368 only adds demandedLatestCheckpointMinimumTokens, which is nil by default and unset by this PR, so behaviour here is unchanged. With the same SDK pin as #1643, the two PRs merge cleanly in either order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…prompt end (−16.5% follow-up TTFT) (#1643) * perf(provider): restore dense Qwen conversations from just below the prompt end A dense Qwen 3.5/3.8 request served alone prefills in 4,096-token stripes, so its deepest SSD checkpoint was the last full stripe end, up to 4,095 tokens before the prompt end. The next turn of the conversation re-prefilled that gap. With its paged complete store, the engine now sets the SDK's demandedLatestCheckpointMinimumTokens to the store floor. A request the store would write then also ends a prefill range at the deepest 256-aligned boundary at least 64 tokens below its prompt end, when that saves at least the floor. Busy providers, which prefill in 512-token chunks beside decoding requests, keep the ordinary geometry. Six-turn conversation from 30K to 55K tokens, Qwen3.5-9B, M3 Ultra, two runs per arm: the mean summed time to first token of the five follow-up turns fell from 57.38 s to 47.88 s (-16.5%), with outputs identical to master on every turn. SSD bytes rose 2.6% (2.71 GB to 2.78 GB) for the same 7 files. Requires mlx-swift-lm 05c7ca7e (feat/demanded-latest-checkpoint). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(provider): pin mlx-swift-lm 76ff231b (docs for the end-of-prompt boundary) The SDK change adds demandedLatestCheckpointMinimumTokens to the retention doc and shortens its code comments. No code changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Repin the SDK to the merged #368 (2beb401f) and the MLX stack it declares Layr-Labs/mlx-swift-lm#368 was squash-merged as 2beb401f, so this branch's former SDK pin 76ff231b (#368's head) is not on SDK main. Every gitlink now points at a commit on its fork's main: - libs/mlx-swift-lm 76ff231b -> 2beb401f, the tip of SDK main and the #368 squash. Merging 76ff231b into the previous main (25bcd63f) gives exactly 2beb401f's tree, so #368 (demandedLatestCheckpointMinimumTokens) is unchanged. The pin also brings what SDK main gained since master's aee6ebb6: the tensor-parallel engine (#308), Qwen tensor batching (#352) and the optional stop-string scope (#369). - libs/mlx-swift 4926d3d9 -> c633d221, the revision 2beb401f's Package.swift declares; mlx-swift main (52c36f86) has the same tree. SDK main calls mlx-swift APIs that 4926d3d9 lacks (MLXArray.sharingArray, the fencedInputs argument of MLXFast.metalKernel). The nested mlx-c moves from 004c735f to 2ac897e3 with it. - libs/mlx 31f550af -> 72dffa2d, the nested copy that Cmlx compiles at c633d221 (Source/Cmlx/mlx); mlx main (f24d7e63) has the same tree. 72dffa2d keeps the 0.10.3 M5 NAX head-dim split JIT fix: 31f550af is not its ancestor, but that fix's squash on mlx main (6bc9de5b, Layr-Labs/mlx#48, identical patch ID) is, and its jit_kernels.cpp change is intact. #1645 pins the same mlx-swift and mlx commits. Provider follow-ups for the SDK's new enum cases, identical to #1645's (46f7ae9 and 2185dfe) so the two branches merge without conflicts: - MLXServerGenerationEvent.logprobs is token metadata. The GLM and JSON answer-format observers and seven test helpers treat it like .info. No SDK engine or provider bridge emits it today; the provider sends logprobs through EngineV2LogprobsChannel. - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens, which the SDK split from invalidResponseFormatOutput for a structured answer cut off by max_tokens, keeps that case's 422 and retryable classification. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brings the 13 changes that landed on master only into dev, so the next dev release and the move to master contain them: SSD cache work (Layr-Labs#1641, Layr-Labs#1642, Layr-Labs#1643, Layr-Labs#1647, Layr-Labs#1648, Layr-Labs#1649, Layr-Labs#1651, Layr-Labs#1657 and the test fixture fix 093aaf3), overlapped weight hashing (Layr-Labs#1638), GPT-OSS stop sequences in the Harmony final message (Layr-Labs#1645), faster reconnects (Layr-Labs#1613) and the provider 0.10.5 preparation (Layr-Labs#1678). Layr-Labs#1659 is master's copy of dev's Layr-Labs#1658. Conflicts: the reconnect loop keeps dev's cluster-member handling and takes master's reconnect policy (the member-aware delay now starts from the policy's range, and the session is marked open after registration for both roles). The bridge passes both dev's default max-token context limit and master's stop-string scope. WeightHasher takes master's overlapped reads with dev's reason for reading uncached. Four case lists were the same set in a different order, a test-budget line differed only in wrapping, and two docs needed both sides. libs/mlx-swift-lm moves to mlx-swift-lm main 2beb401f, which contains dev's d5bd32b8 and master's Layr-Labs#368 and Layr-Labs#369. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Fixes the Gemma 4 token-repetition loops users hit on the chat console (e.g.
"...the era of the era of...","One of of of of","you've you've you've...").gemma-4-26bdeclaresvision_config, so providers load it viaVLMModelFactoryand serve text through the VLM model's continuous-batched path. That path had two bugs that compound on 4-bit builds:cache.offset(max across rows), mis-positioning shorter rows in a mixed-length batch.MLXFast.scaledDotProductAttentionnumerically diverges with an explicit array mask on 4-bit Gemma 4, flipping top-1 logits.The earlier v0.6.9 NaN fix targeted
MLXLLM/Gemma4Text.swift— a class providers don't load for vision checkpoints — which is why it didn't help.The actual code fix is in the submodule: Layr-Labs/mlx-swift-lm#41. This PR bumps the submodule pointer to that fix and adds regression coverage.
Changes
libs/mlx-swift-lm:404afee → 429d83c(per-row RoPE offset + NaN-guarded manual masked attention inMLXVLM/Models/Gemma4.swift;.nonedecode mask inBatchKVCache). See fix(gemma4-vlm): correct continuous-batched decode (per-row RoPE + mask kernel) mlx-swift-lm#41.ContinuousBatchingLiveTests.gemma4VLMMixedLengthCoherent— loadsgemma-4-26B-A4B-it-qat-4bitviaVLMModelFactory(the production path; the existingrunDiffTestusedLLMModelFactory, which is why it never caught this) and asserts a mixed-lengthB=2greedy batch is coherent. Gated byDARKBLOOM_LIVE_MLX_TESTS=1+DARKBLOOM_LIVE_MLX_GEMMA=1.BatchKVCacheTests— adds a case asserting.nonemask for unpaddedn==1decode and.arraywhen any row is left-padded.Verification
On
gemma-4-26B-A4B-it-qat-4bitviaVLMModelFactory, mixed-lengthB=2greedy:"...the era of the era of the era of the era of..."A/B verified by reverting the submodule fix (repetition returns → test fails) and re-applying (coherent → test passes). All
BatchKVCacheunit tests pass.Merge order
Merge the submodule PR (Layr-Labs/mlx-swift-lm#41) first, then re-point
libs/mlx-swift-lmhere to the merged SHA if it differs (squash-merge changes the hash). After merge, bump the provider version so the fleet picks up the fix (LatestProviderVersiongate).Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.