Skip to content

fix(provider): Gemma 4 VLM continuous-batched decode — no more repetition - #369

Merged
Gajesh2007 merged 2 commits into
masterfrom
fix/gemma4-vlm-batched-decode
Jun 16, 2026
Merged

Gajesh2007 merged 2 commits into
masterfrom
fix/gemma4-vlm-batched-decode

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

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-26b declares vision_config, so providers load it via VLMModelFactory and serve text through the VLM model's continuous-batched path. That path had two bugs that compound on 4-bit builds:

  1. Scalar RoPE offset — used cache.offset (max across rows), mis-positioning shorter rows in a mixed-length batch.
  2. Explicit-mask fused-kernel divergence (ml-explore/mlx#3384) — MLXFast.scaledDotProductAttention numerically 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 in MLXVLM/Models/Gemma4.swift; .none decode mask in BatchKVCache). See fix(gemma4-vlm): correct continuous-batched decode (per-row RoPE + mask kernel) mlx-swift-lm#41.
  • ContinuousBatchingLiveTests.gemma4VLMMixedLengthCoherent — loads gemma-4-26B-A4B-it-qat-4bit via VLMModelFactory (the production path; the existing runDiffTest used LLMModelFactory, which is why it never caught this) and asserts a mixed-length B=2 greedy batch is coherent. Gated by DARKBLOOM_LIVE_MLX_TESTS=1 + DARKBLOOM_LIVE_MLX_GEMMA=1.
  • BatchKVCacheTests — adds a case asserting .none mask for unpadded n==1 decode and .array when any row is left-padded.

Verification

On gemma-4-26B-A4B-it-qat-4bit via VLMModelFactory, mixed-length B=2 greedy:

  • Before: "...the era of the era of the era of the era of..."
  • After: coherent (full "Shortcut Learning" answer + a coherent renewable-energy essay).

A/B verified by reverting the submodule fix (repetition returns → test fails) and re-applying (coherent → test passes). All BatchKVCache unit tests pass.

Merge order

Merge the submodule PR (Layr-Labs/mlx-swift-lm#41) first, then re-point libs/mlx-swift-lm here 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 (LatestProviderVersion gate).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

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

vercel Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 16, 2026 6:29pm
d-inference-console-ui-dev Ready Ready Preview Jun 16, 2026 6:29pm
d-inference-landing Ready Ready Preview Jun 16, 2026 6:29pm

Request Review

@github-actions

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

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 touched

None of the changed files are listed under any affected_files entry in the threat model. The closest relevant boundaries are TB-007 (provider inference engine) and TB-003 (provider operator vs process), both of which list BatchScheduler.swift, LocalMLXModelFoundation.swift, and WeightHasher.swift — but not the test files or the libs/mlx-swift-lm submodule path.


Per-threat assessment

No existing T-xxx entry is directly triggered. Closest adjacencies for awareness:

Threat Relevance Verdict
T-028 (GPU residual data) BatchKVCacheTests.swift exercises KV-cache lifecycle; if new test scaffolding allocates/frees Metal buffers it could paper over the open gap ℹ️ Neutral — tests don't change production buffer-zeroing behaviour
T-041 (cross-tenant prefix-cache timing oracle) ContinuousBatchingLiveTests.swift exercises the batching path that feeds the shared prefix cache ℹ️ Neutral — live tests exercise existing behaviour, no new sharing policy introduced
T-027 / T-007 (weight hash / model substitution) libs/mlx-swift-lm is a submodule bump; if this changes tokeniser or weight-loading code it affects the hash surface ℹ️ Neutral pending submodule content review (see note below)

New attack surface not covered by an existing threat

libs/mlx-swift-lm submodule change — this is the one item that deserves a threat-model annotation. The submodule provides the MLX tokeniser, model-loader, and generation primitives used inside TB-007. Changes here can:

  • Alter which files WeightHasher must cover (new weight-file extensions or layout changes → hash silently misses new files, worsening SEC-007 / T-027).
  • Introduce new memory-allocation patterns for KV-cache or activations that affect the T-028 GPU residual-data gap.
  • Change tokeniser behaviour in ways that affect prompt-content handling in the inference path (A-001).

Recommended action: add libs/mlx-swift-lm (or its resolved path under provider-swift/) to the affected_files lists of T-027, T-028, and T-007 so future submodule bumps are automatically flagged by this pipeline. Until then, any PR touching this submodule should include a manual review of (a) whether new weight-file extensions are loaded without being hashed, and (b) whether new buffer-allocation APIs are used without explicit zeroing.


SEC-* findings resolved

None — this PR does not resolve any open SEC-* finding.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +126 to +130
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +158 to +162
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +164 to +170
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 }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +89 to +110
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.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +158 to +175
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +111 to +157
"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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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 ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +126 to +130
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +158 to +174
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +126 to +150
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))"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +158 to +174
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@Gajesh2007
Gajesh2007 merged commit 6f51cc9 into master Jun 16, 2026
25 of 26 checks passed
@Gajesh2007
Gajesh2007 deleted the fix/gemma4-vlm-batched-decode branch June 16, 2026 18:41
jonathan308 added a commit that referenced this pull request Oct 28, 2026
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>
jonathan308 added a commit that referenced this pull request Oct 28, 2026
#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>
jonathan308 added a commit that referenced this pull request Oct 28, 2026
…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>
jonathan308 added a commit that referenced this pull request Oct 29, 2026
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>
Gajesh2007 pushed a commit that referenced this pull request Oct 29, 2026
…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>
Gajesh2007 pushed a commit that referenced this pull request Oct 29, 2026
…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>
davidtai added a commit that referenced this pull request Oct 30, 2026
libs/mlx-swift-lm conflicted: master pins 2beb401f (mlx-swift-lm main,
#368/#369), dev pins f98ced91 (#373's head). It takes 7933a0fa, the
#373 merge commit on mlx-swift-lm main, whose parents are both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CertifiedCryp pushed a commit to CertifiedCryp/d-inference that referenced this pull request Oct 31, 2026
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>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 9fcc7834 Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 9fcc7834 Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-landing — 9fcc7834 Deployed Jun 16, 2026 by vercel[bot]
benchmarks — 9fcc7834 Deployed Jun 16, 2026 by Gajesh2007 via E2E Benchmarks #1007
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants