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
10 changes: 10 additions & 0 deletions changelog.d/nemotron-draft-calls-stay-reasoning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Nemotron 3.5 Lightning no longer repeats parallel tool calls

- With reasoning on, Lightning sometimes closes its thought early to sketch the
calls it plans, keeps reasoning, closes the thought a second time and then
writes the real calls. The sketched calls were returned as well, so a
request for two parallel calls got four. Tool calls written before that
second close now stay in the reasoning, and only the final calls are
returned.
- When reasoning is on, Lightning's tool calls (and any text after them) now
reach a streaming client when generation ends, not while they are written.
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
modelType: modelType,
allowInternalSchemaMetadata: allowInternalToolSchemaMetadata,
glm5PairPostValidation: glm5PairPostValidation)
policy.declaredTools = templateControls.declaredTools
policy = policy.withDeclaredTools(templateControls.declaredTools, modelType: modelType)
// The coordinator path serves every request as a stream; the body
// says whether the client streams (`StrictToolCallPolicy`).
policy.clientStreams = templateControls.clientStreams ?? (request.stream == true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ enum ToolChoicePromptPolicy {
/// (`ToolSchemaNormalization`) filled in render types. Validation of
/// `auto` calls reads these; nil falls back to `tools`.
var declaredTools: [OpenAITool]? = nil
/// The declarations the call parser reads arguments with
/// (`ToolArgumentSchemas.reading`): `tools`, each with the caller's
/// parameters instead of their render types. Nil reads `tools`.
var argumentTools: [OpenAITool]? = nil
/// An answer the engine cut at the token limit ends as a normal
/// `length` finish, as generated (`TokenLimitCutPolicy`).
var cutAnswersEndAtLength = TokenLimitCutPolicy.endsAtLength
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import MLXLMServer
/// Content-state `</think>` handling follows the vendor-documented Nemotron
/// parser (vLLM `nemotron_v3`, which reuses the qwen3 parser-engine config):
/// when explicitly enabled, a close already in content is absorbed and the text
/// before it stays content. It is never reinterpreted as a reasoning boundary.
/// before it stays content. It is never reinterpreted as a reasoning boundary,
/// except for frames held after a closed thought (`holdsFramesAfterThought`).
struct NativeChannelSplitter {
private enum State { case content, reasoning, tool(end: String) }
private var state: State
Expand All @@ -25,6 +26,11 @@ struct NativeChannelSplitter {
private var flintScanner: FlintToolFrameScanner?
private let preserveInnerReasoningSpans: Bool
private let absorbStrayThinkClose: Bool
/// `heldFrames`: content from the first tool frame after a closed
/// thought, held until a stray `</think>` or the end of output.
private let holdsFramesAfterThought: Bool
private var closedThought = false
private var heldFrames: String?
private var promotesTrailingCalls: Bool
/// The open thought's text (kept only with `promotesTrailingCalls`).
private var openThought = ""
Expand All @@ -43,10 +49,17 @@ struct NativeChannelSplitter {
/// so they parse as calls. A frame followed by more thought, or by
/// `</think>`, stays reasoning, and so does a thought the token limit cut
/// off (`outputReachedTokenLimit`).
///
/// `holdsFramesAfterThought` (with `absorbStrayThinkClose`): a model that
/// closes its thought, writes tool frames as a draft, keeps thinking and
/// closes the thought again was still thinking. Content from the first
/// frame after a closed thought is held; a stray `</think>` makes the held
/// text reasoning, so its frames never become calls. At the end of the
/// output the held text is content.
init(prefix: String, protectToolFrames: Bool, qwenStructuredFrames: Bool = false, flintFrames: Bool = false,
glmFrames: Bool = false, tools: [[String: any Sendable]]? = nil,
preserveInnerReasoningSpans: Bool = false, absorbStrayThinkClose: Bool = false,
promotesTrailingCalls: Bool = false) {
holdsFramesAfterThought: Bool = false, promotesTrailingCalls: Bool = false) {
state = prefix == "<think>" ? .reasoning : .content
self.protectToolFrames = protectToolFrames
self.qwenStructuredFrames = qwenStructuredFrames
Expand All @@ -55,6 +68,7 @@ struct NativeChannelSplitter {
self.tools = tools
self.preserveInnerReasoningSpans = preserveInnerReasoningSpans
self.absorbStrayThinkClose = absorbStrayThinkClose
self.holdsFramesAfterThought = holdsFramesAfterThought && absorbStrayThinkClose
self.promotesTrailingCalls = promotesTrailingCalls
}

Expand All @@ -67,6 +81,10 @@ struct NativeChannelSplitter {
mutating func finish() -> [ParsedReasoning] {
guard !reasoningNestingLimitExceeded else { return [] }
var pieces = drain(final: true)
if let held = heldFrames {
heldFrames = nil
append(held, reasoning: false, to: &pieces)
}
toolScanner = nil
flintScanner = nil
if promotesTrailingCalls, case .reasoning = state,
Expand Down Expand Up @@ -224,7 +242,12 @@ struct NativeChannelSplitter {
else if marker == "</think>" {
// Stray close after a prompt-side `<think></think>` (or a
// duplicate close): drop the marker, stay in content.
if let held = heldFrames {
heldFrames = nil
append(held, reasoning: true, to: &result)
}
} else {
if holdsFramesAfterThought, closedThought, heldFrames == nil { heldFrames = "" }
append(marker, reasoning: false, to: &result)
state = .tool(end: marker == "<tool_call>" ? "</tool_call>" : "</function>")
if qwenStructuredFrames && marker == "<tool_call>" {
Expand All @@ -251,6 +274,7 @@ struct NativeChannelSplitter {
append(String(buffer[..<range.lowerBound]), reasoning: true, to: &result)
state = .content
openThought = ""
closedThought = true
}
case .tool:
append(String(buffer[..<range.upperBound]), reasoning: false, to: &result)
Expand Down Expand Up @@ -279,6 +303,10 @@ struct NativeChannelSplitter {

private mutating func append(_ text: String, reasoning: Bool, to result: inout [ParsedReasoning]) {
guard !text.isEmpty else { return }
if !reasoning, heldFrames != nil {
heldFrames! += text
return
}
if reasoning && promotesTrailingCalls { openThought += text }
result.append(.init(content: reasoning ? "" : text, reasoningContent: reasoning ? text : nil))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ struct NativeToolStreamRouter {
tools: tools,
preserveInnerReasoningSpans: preserveInnerReasoningSpans,
absorbStrayThinkClose: absorbStrayThinkClose,
// Nemotron 3.5 drafts calls after an early `</think>`, then closes again.
holdsFramesAfterThought: handler?.format == .nemotron,
promotesTrailingCalls: promotesTrailingReasoningCalls)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ enum ToolStreamPreparation {
try ToolChoiceEnforcementPolicy.validateParser(
format, strategy: strategy, modelContext: context)
return BatchedToolStreamHandler(format: format,
tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.tools)?.map { $0.toolSpec() },
tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.argumentTools ?? prepared.tools)?
.map { $0.toolSpec() },
strictGemma: modelType == "diffusion_gemma",
streaming: streamToolCalls && exposesCallsWhileGenerated(request: request, prepared: prepared,
context: context, strategy: strategy, format: format, forced: streamForcedToolCalls,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,10 @@ enum QwenStrictToolGrammar {
guard runsTokenConstraints else { return declined("the engine does not run token constraints") }
let schema: QwenStrictToolSchema
do {
schema = try QwenStrictToolSchema(declared: prepared.declaredTools ?? rendered, rendered: rendered,
// The grammar spells each value as the parser reads it
// (`ToolStreamPreparation.makeHandler`).
schema = try QwenStrictToolSchema(declared: prepared.declaredTools ?? rendered,
rendered: prepared.argumentTools ?? rendered,
forbidding: family.forbiddenMarkers, family: family.profile.family,
lenient: family.allTools)
} catch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ struct QwenStrictToolSchema: Sendable {
let tools: [Tool]

/// `declared`: the caller's declarations as sent, which `strict` calls are
/// validated against. `rendered`: the same tools after ingress
/// normalization, which the call parser reads. `markers`: spellings no
/// validated against. `rendered`: the same tools as the call parser reads
/// them (`Prepared.argumentTools`, else after ingress normalization).
/// `markers`: spellings no
/// value may contain. `lenient` (every `auto` call of a family whose calls
/// are returned as generated): a tool whose schema the subset cannot hold
/// still has its name, its parameter names and its required parameters
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright © 2026 Eigen Labs.

import MLXLMCommon
import MLXLMServer

/// The tool declarations a call's arguments are read with
/// (`ToolChoicePromptPolicy.Prepared.argumentTools`): the caller's own
/// parameters, as sent, rather than the render types the ingress repair
/// (`ToolSchemaNormalization`) wrote for the chat template. The repair gives
/// every node one `type`, so a union, `not` or `if`/`then`/`else` node reads as
/// its first or default member, and the parser converted text to a type the
/// caller never declared (`"2.5"` stayed text under `oneOf: [integer, number]`
/// read as `integer`). The template still renders the repaired declarations.
///
/// A typeless `enum` or `const` node gets the JSON types of its values as its
/// `type`, the one change made: it accepts exactly the instances the node
/// accepts already, and lets the parser read `"2"` as `2` under `enum: [1, 2]`
/// as it did under the repair's inferred type.
enum ToolArgumentSchemas {
/// The repair's own depth bound (`maxToolSchemaDepth` on the coordinator).
static let maximumDepth = 64

/// `rendered` with each tool's parameters replaced by its declaration in
/// `declared` (by name), typed by `typingFiniteValues`. Nil when either is
/// unknown, so the parser keeps reading `rendered`. A rendered tool with
/// no declaration keeps its rendered parameters.
static func reading(rendered: [OpenAITool]?, declared: [OpenAITool]?) -> [OpenAITool]? {
guard let rendered, let declared else { return nil }
let byName = Dictionary(declared.map { ($0.function.name, $0) }, uniquingKeysWith: { first, _ in first })
return rendered.map { tool in
guard let declaration = byName[tool.function.name] else { return tool }
var copy = tool
copy.function.parameters = declaration.function.parameters.map { typingFiniteValues($0, depth: 0) }
return copy
}
}

private static let schemaMapKeywords = [
"properties", "patternProperties", "$defs", "definitions", "dependentSchemas",
]
private static let schemaKeywords = [
"items", "additionalItems", "additionalProperties", "contains", "propertyNames", "not",
"if", "then", "else", "unevaluatedItems", "unevaluatedProperties",
]
private static let schemaListKeywords = ["anyOf", "oneOf", "allOf", "prefixItems", "items"]

/// `node` with every typeless `enum`/`const` schema typed by its values.
/// Only schema positions are walked, never `enum`, `const`, `default` or
/// `examples` values; past `maximumDepth` the node is returned as written.
static func typingFiniteValues(_ node: MLXLMCommon.JSONValue, depth: Int) -> MLXLMCommon.JSONValue {
guard depth < maximumDepth, case .object(var object) = node else { return node }
for key in schemaMapKeywords {
if case .object(let map)? = object[key] {
object[key] = .object(map.mapValues { typingFiniteValues($0, depth: depth + 1) })
}
}
for key in schemaKeywords {
if let child = object[key], case .object = child {
object[key] = typingFiniteValues(child, depth: depth + 1)
}
}
for key in schemaListKeywords {
if case .array(let members)? = object[key] {
object[key] = .array(members.map { typingFiniteValues($0, depth: depth + 1) })
}
}
if object["type"] == nil, let type = finiteValueType(object) {
object["type"] = type
}
return .object(object)
}

private static let typeOrder = ["null", "boolean", "integer", "number", "string", "array", "object"]

/// The `type` naming exactly the JSON types of a node's `const`, or of its
/// non-empty `enum`; nil when it declares neither.
private static func finiteValueType(_ object: [String: MLXLMCommon.JSONValue]) -> MLXLMCommon.JSONValue? {
let values: [MLXLMCommon.JSONValue]
if let constant = object["const"] {
values = [constant]
} else if case .array(let members)? = object["enum"], !members.isEmpty {
values = members
} else {
return nil
}
var names = Set(values.map(typeName))
// `number` admits every integer.
if names.contains("number") { names.remove("integer") }
let ordered = typeOrder.filter(names.contains)
return ordered.count == 1 ? .string(ordered[0]) : .array(ordered.map { .string($0) })
}

private static func typeName(_ value: MLXLMCommon.JSONValue) -> String {
switch value {
case .null: "null"
case .bool: "boolean"
case .int: "integer"
case .double: "number"
case .string: "string"
case .array: "array"
case .object: "object"
}
}
}

extension ToolChoicePromptPolicy.Prepared {
/// The prepared request with the caller's declarations as sent
/// (`declaredTools`), which `auto` calls are validated against, and the
/// parser's reading of them (`argumentTools`). GLM renders and reads its
/// declarations as sent already.
func withDeclaredTools(_ declared: [OpenAITool]?, modelType: String?) -> Self {
var copy = self
copy.declaredTools = declared
if !GLM5NextPromptPolicy.applies(modelType: modelType) {
copy.argumentTools = ToolArgumentSchemas.reading(rendered: tools, declared: declared)
}
return copy
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,56 @@ struct NativeChannelSplitterTests {
#expect(pieces.map(\.content).joined() == "answer more")
}

static func frame(_ text: String) -> String {
"<tool_call>\n<function=post>\n<parameter=text>\n\(text)\n</parameter>\n</function>\n</tool_call>"
}

/// Lightning's shape: the thought closes early, draft frames and more
/// thought follow, a second `</think>` closes it, then the real calls.
static let draftThenCalls = "Same two calls as before. Probably something like:\n\n</think>\n\n"
+ frame("A") + "\n" + frame("B") + "\n\n\n\nBut keep each value exact.\n\nThus two calls.\n\n</think>\n\n"
+ frame("A") + "\n" + frame("B")

@Test func framesBeforeASecondCloseStayReasoning() {
let draft = Self.frame("A") + "\n" + Self.frame("B") + "\n\n\n\nBut keep each value exact.\n\nThus two calls.\n\n"
for width in [1, 3, 7, 64, 4096] {
var splitter = NativeChannelSplitter(prefix: "<think>", protectToolFrames: true,
absorbStrayThinkClose: true, holdsFramesAfterThought: true)
var pieces: [ParsedReasoning] = []
let characters = Array(Self.draftThenCalls)
for start in stride(from: 0, to: characters.count, by: width) {
pieces += splitter.parse(String(characters[start..<min(characters.count, start + width)]))
}
pieces += splitter.finish()
#expect(pieces.compactMap(\.reasoningContent).joined()
== "Same two calls as before. Probably something like:\n\n" + draft)
#expect(pieces.map(\.content).joined() == "\n\n\n\n" + Self.frame("A") + "\n" + Self.frame("B"))
}
}

@Test func framesAfterAClosedThoughtAreContentWithoutASecondClose() {
let text = "thought</think>\n" + Self.frame("A") + "\nDone."
var splitter = NativeChannelSplitter(prefix: "<think>", protectToolFrames: true,
absorbStrayThinkClose: true, holdsFramesAfterThought: true)
let pieces = splitter.parse(text) + splitter.finish()
#expect(pieces.compactMap(\.reasoningContent).joined() == "thought")
#expect(pieces.map(\.content).joined() == "\n" + Self.frame("A") + "\nDone.")
}

@Test func framesStayContentWhereNoFrameIsHeld() {
// Without the hold (other families), or without a closed thought
// (a closed prompt), a stray close keeps the frames before it.
let text = "</think>\n" + Self.frame("A") + "\nmore</think>\n" + Self.frame("B")
for (prefix, holds) in [("<think>", false), ("<think></think>", true)] {
var splitter = NativeChannelSplitter(prefix: prefix, protectToolFrames: true,
absorbStrayThinkClose: true, holdsFramesAfterThought: holds)
let pieces = splitter.parse(text) + splitter.finish()
let content = "\n" + Self.frame("A") + "\nmore\n" + Self.frame("B")
#expect(pieces.map(\.content).joined() == content)
#expect(pieces.compactMap(\.reasoningContent).joined().isEmpty)
}
}

@Test func closeMarkerInsideToolFrameStaysOpaque() {
var splitter = NativeChannelSplitter(prefix: "<think></think>", protectToolFrames: true,
absorbStrayThinkClose: true)
Expand Down
Loading
Loading