Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/test-shards.json
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,21 @@
],
"strict": true,
"own_process": true
},
{
"name": "gemma-reopened-thought-enabled",
"strict": true,
"extra": true,
"metallib": false,
"filters": [
"GemmaReopenedThoughtConformanceTests",
"Gemma4NonStreamingTests",
"Gemma4StreamingTests"
],
"env": {
"DARKBLOOM_GEMMA_REOPENED_THOUGHTS": "1"
},
"timeout_minutes": 5
}
],
"shards": [
Expand Down Expand Up @@ -1016,6 +1031,11 @@
"tests": [
"MLXLMTests.CBv2PagedKernelTests/decodeBatchCompositionInvariance()"
]
},
{
"groups": [
"gemma-reopened-thought-enabled"
]
}
]
},
Expand Down
35 changes: 26 additions & 9 deletions Libraries/MLXLMCommon/Tool/GemmaToolFrameScanner.swift
Original file line number Diff line number Diff line change
@@ -1,25 +1,38 @@
/// Incremental native Gemma framing: an end tag inside a marker-quoted or
/// JSON-quoted argument is data, not a frame terminator.
struct GemmaToolFrameScanner {
private enum Quote { case none, json, native(String) }
package struct GemmaToolFrameScanner: Sendable {
private enum Quote: Sendable {
case none, json
case native(String)
}
private var quote = Quote.none
private var escaped = false
private var candidate = ""
private let end = "<tool_call|>"
private let markers = ["<|\"|>", "<escape>"]

mutating func consume(_ scalar: Unicode.Scalar) -> Bool {
package init() {}

package mutating func consume(_ scalar: Unicode.Scalar) -> Bool {
let character = String(scalar)
switch quote {
case .json:
if escaped { escaped = false }
else if character == "\\" { escaped = true }
else if character == "\"" { quote = .none }
if escaped {
escaped = false
} else if character == "\\" {
escaped = true
} else if character == "\"" {
quote = .none
}
return false
case .native(let marker):
candidate += character
if candidate.hasSuffix(marker) { quote = .none; candidate = "" }
else if candidate.count > marker.count { candidate = String(candidate.suffix(marker.count)) }
if candidate.hasSuffix(marker) {
quote = .none
candidate = ""
} else if candidate.count > marker.count {
candidate = String(candidate.suffix(marker.count))
}
return false
case .none:
if candidate.isEmpty && character != "<" {
Expand All @@ -28,7 +41,11 @@ struct GemmaToolFrameScanner {
}
candidate += character
if candidate == end { return true }
if markers.contains(candidate) { quote = .native(candidate); candidate = ""; return false }
if markers.contains(candidate) {
quote = .native(candidate)
candidate = ""
return false
}
if ([end] + markers).contains(where: { $0.hasPrefix(candidate) }) { return false }
candidate = character == "<" ? "<" : ""
if character == "\"" { quote = .json }
Expand Down
8 changes: 8 additions & 0 deletions Libraries/MLXLMServer/Parsing/ReasoningParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@ public struct ReasoningParser: Sendable {
}

private func parseGemma4(_ text: String) -> ParsedReasoning {
if StreamingGemma4ReasoningParser.reopenedThoughtsEnabled {
var parser = StreamingGemma4ReasoningParser()
let pieces = parser.parse(text) + parser.finish()
let reasoning = pieces.compactMap(\.reasoningContent).joined().trimmedForReasoning
return .init(
content: pieces.map(\.content).joined().trimmedForReasoning,
reasoningContent: reasoning.isEmpty ? nil : reasoning)
}
let channelOpen = "<|channel>"
let channelClose = "<channel|>"
let thoughtPrefix = "thought\n"
Expand Down
89 changes: 86 additions & 3 deletions Libraries/MLXLMServer/Parsing/StreamingGemma4ReasoningParser.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
// Copyright © 2026 Eigen Labs Inc.

import Foundation
import MLXLMCommon

struct StreamingGemma4ReasoningParser: Sendable {
static let reopenedThoughtsEnabled =
ProcessInfo.processInfo.environment["DARKBLOOM_GEMMA_REOPENED_THOUGHTS"] == "1"

private enum State: Sendable {
case undecided
case thinking
case content
case toolCall
}

private let openTag = "<|channel>"
Expand All @@ -15,6 +22,7 @@ struct StreamingGemma4ReasoningParser: Sendable {
private var state: State = .undecided
private var buffer = ""
private var strippedThoughtPrefix = false
private var toolFrame = GemmaToolFrameScanner()

mutating func parse(_ chunk: String) -> [ParsedReasoning] {
buffer += chunk
Expand All @@ -37,6 +45,8 @@ struct StreamingGemma4ReasoningParser: Sendable {
drainThinking(final: final, output: &output, shouldContinue: &shouldContinue)
case .content:
drainContent(final: final, output: &output, shouldContinue: &shouldContinue)
case .toolCall:
drainToolCall(output: &output, shouldContinue: &shouldContinue)
}
}

Expand All @@ -48,9 +58,22 @@ struct StreamingGemma4ReasoningParser: Sendable {
output: inout [ParsedReasoning],
shouldContinue: inout Bool
) {
if Self.reopenedThoughtsEnabled {
// Decide the optional bare prefix once, before emitting any content.
if !final && thoughtPrefix.hasPrefix(buffer) && buffer != thoughtPrefix {
shouldContinue = false
return
}
if buffer.hasPrefix(thoughtPrefix) {
buffer = String(buffer.dropFirst(thoughtPrefix.count))
}
state = .content
drainChannelContent(final: final, output: &output, shouldContinue: &shouldContinue)
return
}
if let openRange = buffer.range(of: openTag) {
appendContent(String(buffer[..<openRange.lowerBound]), to: &output)
buffer.removeSubrange(buffer.startIndex..<openRange.upperBound)
buffer.removeSubrange(buffer.startIndex ..< openRange.upperBound)
state = .thinking
strippedThoughtPrefix = false
return
Expand Down Expand Up @@ -84,7 +107,14 @@ struct StreamingGemma4ReasoningParser: Sendable {
) {
// Strip "thought\n" prefix once after entering thinking state
if !strippedThoughtPrefix {
if buffer.hasPrefix(thoughtPrefix) {
let emptyThought = "thought" + closeTag
if Self.reopenedThoughtsEnabled && buffer.hasPrefix(emptyThought) {
buffer = String(buffer.dropFirst("thought".count))
strippedThoughtPrefix = true
} else if Self.reopenedThoughtsEnabled && !final && emptyThought.hasPrefix(buffer) {
shouldContinue = false
return
} else if buffer.hasPrefix(thoughtPrefix) {
buffer = String(buffer.dropFirst(thoughtPrefix.count))
strippedThoughtPrefix = true
} else if !final && buffer.count < thoughtPrefix.count {
Expand All @@ -98,7 +128,7 @@ struct StreamingGemma4ReasoningParser: Sendable {

if let closeRange = buffer.range(of: closeTag) {
appendReasoning(String(buffer[..<closeRange.lowerBound]), to: &output)
buffer.removeSubrange(buffer.startIndex..<closeRange.upperBound)
buffer.removeSubrange(buffer.startIndex ..< closeRange.upperBound)
state = .content
return
}
Expand All @@ -117,6 +147,10 @@ struct StreamingGemma4ReasoningParser: Sendable {
output: inout [ParsedReasoning],
shouldContinue: inout Bool
) {
if Self.reopenedThoughtsEnabled {
drainChannelContent(final: final, output: &output, shouldContinue: &shouldContinue)
return
}
if final {
// Clean trailing markers
for marker in trailingMarkers {
Expand All @@ -137,4 +171,53 @@ struct StreamingGemma4ReasoningParser: Sendable {
appendContent(content, to: &output)
shouldContinue = false
}

private mutating func drainChannelContent(
final: Bool,
output: inout [ParsedReasoning],
shouldContinue: inout Bool
) {
let toolStart = "<|tool_call>"
let markers = [openTag, closeTag, toolStart] + trailingMarkers
if let range = firstRange(
ofAny: markers, in: buffer, range: buffer.startIndex ..< buffer.endIndex)
{
let opensThought = buffer[range] == openTag
let opensTool = buffer[range] == toolStart
appendContent(String(buffer[..<range.lowerBound]), to: &output)
buffer.removeSubrange(buffer.startIndex ..< range.upperBound)
if opensThought {
state = .thinking
strippedThoughtPrefix = false
} else if opensTool {
appendContent(toolStart, to: &output)
toolFrame = GemmaToolFrameScanner()
state = .toolCall
}
return
}
appendContent(
consumeSafePrefix(from: &buffer, preservingPotentialPrefixOfAny: markers, final: final),
to: &output)
shouldContinue = false
}

/// Tool payloads are opaque to channel routing, including marker-looking
/// strings and quoted tool-end tags.
private mutating func drainToolCall(
output: inout [ParsedReasoning], shouldContinue: inout Bool
) {
for index in buffer.unicodeScalars.indices {
if toolFrame.consume(buffer.unicodeScalars[index]) {
let end = buffer.unicodeScalars.index(after: index)
appendContent(String(buffer[..<end]), to: &output)
buffer.removeSubrange(buffer.startIndex ..< end)
state = .content
return
}
}
appendContent(buffer, to: &output)
buffer.removeAll(keepingCapacity: true)
shouldContinue = false
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import Foundation
import MLXLMServer
import Testing

extension UnitTests {
@Suite
struct GemmaReopenedThoughtConformanceTests {
// A process-level switch keeps these tests independent of parallel suites.
private let enabled =
ProcessInfo.processInfo.environment["DARKBLOOM_GEMMA_REOPENED_THOUGHTS"] == "1"

@Test(
"a reopened Gemma thought and stray close never become answer text",
arguments: [1, 2, 7, 1000])
func reopenedThought(width: Int) {
let first = "<|channel>thought\nFirst.<channel|>Answer."
let reopened = "<|channel>thought\nSecond.<channel|>Done.<channel|>"
let result = parse(first + reopened, width: width)
#expect(result.content == (enabled ? "Answer.Done." : "Answer." + reopened))
#expect(result.reasoningContent == (enabled ? "First.Second." : "First."))
}

@Test("collected output routes every thought and suppresses a stray close")
func collectedThoughts() {
let reopened = "<|channel>thought\nSecond.<channel|>Done.<channel|>"
let result = ReasoningParser(format: .gemma4).parse(
"<|channel>thought\nFirst.<channel|>Answer." + reopened)
#expect(result.content == (enabled ? "Answer.Done." : "Answer." + reopened))
#expect(result.reasoningContent == (enabled ? "First.Second." : "First."))
}

@Test("a stray close before any thought is absorbed", arguments: [1, 4, 1000])
func strayClose(width: Int) {
let text = "Hello<channel|> world"
let result = parse(text, width: width)
#expect(result.content == (enabled ? "Hello world" : text))
#expect(result.reasoningContent == nil)
}

@Test(
"channel markers in native tool strings remain argument data", arguments: [1, 3, 1000])
func toolArgumentMarkers(width: Int) {
guard enabled else { return }
let frame =
#"<|tool_call>call:save{text:<|"|><|channel>thought<channel|><turn|><tool_call|><|"|>}<tool_call|>"#
let result = parse("<|channel>thought\nFirst.<channel|>" + frame, width: width)
#expect(result.content == frame)
#expect(result.reasoningContent == "First.")
}

@Test("reopened unclosed and empty thoughts stay out of the answer")
func unfinishedThoughts() {
guard enabled else { return }
for width in [1, 2, 1000] {
let unfinished = parse(
"<|channel>thought\nOne<channel|>A<|channel>thought\nTwo", width: width)
#expect(unfinished.content == "A")
#expect(unfinished.reasoningContent == "OneTwo")
let empty = parse(
"<|channel>thought\nOne<channel|>A<|channel>thought<channel|>B", width: width)
#expect(empty.content == "AB")
#expect(empty.reasoningContent == "One")
}
}

@Test(
"bare thought prefixes are stripped across chunk boundaries", arguments: [1, 2, 1000])
func barePrefix(width: Int) {
guard enabled else { return }
let text = "thought\nHello"
#expect(parse(text, width: width).content == "Hello")
#expect(ReasoningParser(format: .gemma4).parse(text).content == "Hello")
}

@Test("tool strings stay opaque before reopening a channel", arguments: [1, 2, 1000])
func quoteForms(width: Int) {
guard enabled else { return }
for value in [
#""<|channel>thought<channel|><tool_call|>""#,
#"<escape><|channel>thought<channel|><tool_call|><escape>"#,
] {
let frame = "<|tool_call>call:save{text:" + value + "}<tool_call|>"
let text = frame + "<|channel>thought\nNext<channel|>Answer"
let streamed = parse(text, width: width)
let collected = ReasoningParser(format: .gemma4).parse(text)
#expect(streamed.content == frame + "Answer")
#expect(streamed.reasoningContent == "Next")
#expect(collected.content == streamed.content)
#expect(collected.reasoningContent == streamed.reasoningContent)
}
}

@Test("truncated channel prefixes remain literal at EOS", arguments: [1, 2, 1000])
func partialMarkers(width: Int) {
guard enabled else { return }
for suffix in ["<|chan", "<chann", "<|tool_ca"] {
let text = "Answer" + suffix
#expect(parse(text, width: width).content == text)
#expect(ReasoningParser(format: .gemma4).parse(text).content == text)
}
}

private func parse(_ text: String, width: Int) -> ParsedReasoning {
var parser = StreamingReasoningParser(format: .gemma4)
let characters = Array(text)
var pieces: [ParsedReasoning] = []
for start in stride(from: 0, to: characters.count, by: width) {
pieces += parser.parse(
String(characters[start ..< min(start + width, characters.count)]))
}
pieces += parser.finish()
let reasoning = pieces.compactMap(\.reasoningContent).joined()
return .init(
content: pieces.map(\.content).joined(),
reasoningContent: reasoning.isEmpty ? nil : reasoning)
}
}
}
5 changes: 5 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,10 @@ def:
`response_format` (`json_object` / `json_schema`); streaming reasoning parsers (think tags,
Gemma 4, Harmony); streamed tool-call handling; a batched engine adapter over CBv2 and a
runtime `setMaxNumSeqs` for adaptive concurrency.
`DARKBLOOM_GEMMA_REOPENED_THOUGHTS=1` routes reopened Gemma thought spans into reasoning,
absorbs stray channel-close markers, and preserves opaque tool payloads in streamed and
collected output. Default-off retains the existing parsing behavior; the Gemma conformance
unit suite runs in separate enabled and disabled processes.
Responses input replay retains reasoning and adjacent function calls in one assistant turn,
preserving tool arguments and explicit message/result boundaries.
Collected think-tag parsing keeps unclosed generated or prompt-seeded blocks in reasoning;
Expand All @@ -870,6 +874,7 @@ def:
- "Executables/mlx-server/**"
- "Tests/MLXLMServerTests/**"
- "docs/server-request-validation.md"
- "skills/mlx-swift-lm/references/generation.md"
- title: "Benchmarks and measurement"
description: |
Nothing here ships to users; it is how the fork proves its numbers. `BenchCBv2` (real-weights
Expand Down
Loading
Loading