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
9 changes: 9 additions & 0 deletions changelog.d/gptoss-stop-in-final-channel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### GPT-OSS stop sequences apply to the answer only

- A client `stop` sequence on GPT-OSS models such as `gpt-oss-20b` now
matches only the Harmony `final` message, the text returned as `content`.
It used to match the private analysis too, so a sequence that appeared
while the model reasoned (for example `"\n\n"` or `"."`) ended the request
before any answer: `finish_reason` `stop`, reasoning only, empty content.
Tool-call arguments are never cut either. Other models keep whole-output
matching.
2 changes: 1 addition & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,7 @@ disabled for this hybrid model.
| `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` |
| `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` |
| `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 |
| `stop` | `stopStrings`, matched on held-back detokenised text (`EngineV2Bridge+StopSequence.swift`) | `[]` |
| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` |
| `min_p`, `priority` | **Ignored**: always `0` | — |
| `n`, `best_of` | **Not represented**: one alternative | — |

Expand Down
2 changes: 1 addition & 1 deletion libs/mlx
Submodule mlx updated 74 files
+52 −1 .github/workflows/fork-tests.yml
+33 −0 docs/src/usage/distributed.rst
+69 −0 docs/src/usage/environment_variables.rst
+23 −0 docs/src/usage/using_streams.rst
+357 −1 fork.yaml
+38 −5 mlx/array.cpp
+10 −0 mlx/backend/common/command_buffer_limits.h
+269 −55 mlx/backend/common/metal_kernel.cpp
+3 −2 mlx/backend/cuda/custom_kernel.cpp
+6 −0 mlx/backend/cuda/fence.cpp
+4 −2 mlx/backend/metal/allocator.cpp
+88 −13 mlx/backend/metal/custom_kernel.cpp
+34 −8 mlx/backend/metal/device.cpp
+173 −7 mlx/backend/metal/device.h
+19 −20 mlx/backend/metal/eval.cpp
+136 −25 mlx/backend/metal/fence.cpp
+32 −0 mlx/backend/metal/fenced_input.h
+4 −0 mlx/backend/metal/jit_kernels.cpp
+6 −0 mlx/backend/metal/kernels.h
+49 −0 mlx/backend/metal/kernels/fence.metal
+4 −0 mlx/backend/metal/nojit_kernels.cpp
+70 −7 mlx/backend/metal/quantized.cpp
+6 −0 mlx/backend/no_gpu/fence.cpp
+2 −1 mlx/distributed/CMakeLists.txt
+16 −0 mlx/distributed/distributed.cpp
+15 −0 mlx/distributed/distributed.h
+25 −0 mlx/distributed/distributed_impl.h
+50 −10 mlx/distributed/jaccl/jaccl.cpp
+79 −0 mlx/distributed/jaccl/lib/README.md
+27 −0 mlx/distributed/jaccl/lib/jaccl/group.h
+9 −3 mlx/distributed/jaccl/lib/jaccl/mesh.cpp
+27 −0 mlx/distributed/jaccl/lib/jaccl/mesh.h
+179 −36 mlx/distributed/jaccl/lib/jaccl/mesh_impl.h
+286 −0 mlx/distributed/jaccl/lib/jaccl/progress_guard.h
+5 −1 mlx/distributed/jaccl/lib/jaccl/rdma.cpp
+61 −5 mlx/distributed/jaccl/lib/jaccl/rdma.h
+2 −2 mlx/distributed/jaccl/lib/jaccl/ring.cpp
+8 −0 mlx/distributed/jaccl/lib/jaccl/ring.h
+143 −33 mlx/distributed/jaccl/lib/jaccl/ring_impl.h
+33 −0 mlx/distributed/jaccl/lib/jaccl/send_frame.h
+112 −0 mlx/distributed/jaccl/lib/jaccl/startup_wait_budget.h
+5 −1 mlx/distributed/jaccl/lib/jaccl/threadpool.h
+67 −0 mlx/distributed/primitives.h
+608 −0 mlx/distributed/sealed.cpp
+120 −0 mlx/distributed/sealed.h
+336 −0 mlx/distributed/sealed_stream.h
+17 −0 mlx/fast.h
+69 −5 mlx/fast_primitives.h
+12 −0 mlx/fence.h
+10 −4 mlx/ops.cpp
+12 −0 mlx/scheduler.h
+231 −32 mlx/transforms.cpp
+37 −0 mlx/utils.h
+9 −6 python/src/transforms.cpp
+6 −0 python/tests/mlx_tests.py
+60 −0 python/tests/test_compile.py
+69 −1 tests/CMakeLists.txt
+265 −0 tests/distributed_sealed_stream_tests.cpp
+61 −0 tests/jaccl/CMakeLists.txt
+458 −0 tests/jaccl/exchange_tests.cpp
+312 −0 tests/jaccl/fake_rdma.cpp
+94 −0 tests/jaccl/fake_rdma.h
+69 −0 tests/jaccl/fake_verbs/infiniband/verbs.h
+198 −0 tests/jaccl/fixture.h
+1,333 −0 tests/jaccl/progress_guard_tests.cpp
+363 −0 tests/jaccl/send_frame_tests.cpp
+75 −0 tests/jaccl/startup_wait_budget_api_tests.cpp
+123 −0 tests/jaccl/startup_wait_budget_group_tests.cpp
+441 −0 tests/jaccl/startup_wait_budget_tests.cpp
+148 −0 tests/metal_fence_chain.cpp
+17 −0 tests/ops_tests.cpp
+170 −0 tests/qmv_batch_invariant_tests.cpp
+112 −0 tests/quantized_tile_tests.cpp
+75 −32 tests/standalone/process_allocation_cap_metal.cpp
2 changes: 1 addition & 1 deletion libs/mlx-swift-lm
Submodule mlx-swift-lm updated 153 files
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import MLXLMCommon

extension EngineV2Bridge {
func matchedStopSequence(
Expand All @@ -10,13 +11,25 @@ extension EngineV2Bridge {
tokenIds: generatedTokens,
skipSpecialTokens: false
)
return Self.matchedStopSequence(candidates: candidates, generatedText: generatedText)
return Self.matchedStopSequence(
candidates: candidates, generatedText: generatedText, scope: stopStringScope)
}

/// The candidate that ended generation. A scoped model matched stops only
/// inside its scope, so a candidate seen elsewhere (Harmony analysis) did
/// not stop it.
static func matchedStopSequence(
candidates: [String],
generatedText: String
generatedText: String,
scope: CBv2StopStringScope? = nil
) -> String? {
if let scope {
let holdback = StopHoldback(stopStrings: candidates, scope: scope)
let scan = holdback.ingest(generatedText)
guard scan.stopped else { return nil }
let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count)
return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) }
}
let generatedScalars = Array(generatedText.unicodeScalars)
var best: (position: Int, candidateIndex: Int, value: String)?
for (candidateIndex, candidate) in candidates.enumerated() where !candidate.isEmpty {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ extension EngineV2Bridge {
samplingDefaults: samplingDefaults,
// The same coordinator hint that gates the write also tells the
// engine which fork boundary is worth staging.
prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens
prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens,
stopStringScope: stopStringScope
)
cbv2Request.positionState = positionState ?? multimodal?.positionState
cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ enum EngineV2Translation {
multimodal: CBv2MultimodalInput? = nil,
tokenConstraint: (any CBv2TokenConstraint)? = nil,
samplingDefaults: EngineV2SamplingDefaults = .legacy,
prefixCheckpointTargetTokens: Int? = nil
prefixCheckpointTargetTokens: Int? = nil,
stopStringScope: CBv2StopStringScope? = nil
) -> CBv2Request {
CBv2Request(
id: id,
Expand All @@ -79,7 +80,8 @@ enum EngineV2Translation {
prefixCacheEnabled: cacheEnabled,
multimodal: multimodal,
tokenConstraint: tokenConstraint,
prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil
prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil,
stopStringScope: stopStringScope
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ public actor EngineV2Bridge {
/// tokens) — `buildStopTokenIds` semantics, computed ONCE at bridge
/// construction so B=1 and batched behavior stay identical.
let stopTokenIds: Set<Int>
/// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`);
/// nil matches the whole generated text.
let stopStringScope: CBv2StopStringScope?
/// Artifact sampling defaults resolved once at construction
/// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family
/// that has not been admitted.
Expand Down Expand Up @@ -368,6 +371,7 @@ public actor EngineV2Bridge {
tokenizer: TokenizerHandle,
eosTokenIds: Set<Int>,
extraEOSTokens: [String] = [],
stopStringScope: CBv2StopStringScope? = nil,
samplingDefaults: EngineV2SamplingDefaults = .legacy,
defaultMaxTokens: Int = 4096,
maxConcurrentRequests: Int = 4,
Expand Down Expand Up @@ -428,6 +432,7 @@ public actor EngineV2Bridge {
extraEOSTokens: extraEOSTokens,
convertTokenToId: { [inner = tokenizer.inner] in inner.convertTokenToId($0) }
)
self.stopStringScope = stopStringScope
self.samplingDefaults = samplingDefaults
self.defaultMaxTokens = defaultMaxTokens
self.maxConcurrentRequests = maxConcurrentRequests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ public enum EngineV2Factory {
tokenizer: TokenizerHandle,
eosTokenIds: Set<Int>,
extraEOSTokens: [String] = [],
stopStringScope: CBv2StopStringScope? = nil,
samplingDefaults: EngineV2SamplingDefaults = .legacy,
defaultMaxTokens: Int = 4096,
maxConcurrentRequests: Int = 4,
Expand Down Expand Up @@ -204,6 +205,7 @@ public enum EngineV2Factory {
tokenizer: tokenizer,
eosTokenIds: eosTokenIds,
extraEOSTokens: extraEOSTokens,
stopStringScope: stopStringScope,
samplingDefaults: samplingDefaults,
defaultMaxTokens: defaultMaxTokens,
maxConcurrentRequests: maxConcurrentRequests,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@ enum EngineV2SlotFactory {
tokenizer: tokenizer,
eosTokenIds: eosTokenIds,
extraEOSTokens: snapshot.extraEOSTokens,
stopStringScope: ModelEOSPolicy.stopStringScope(modelId: modelId, modelType: modelType),
samplingDefaults: samplingDefaults,
defaultMaxTokens: sizing.defaultMaxTokens,
maxConcurrentRequests: effectiveMaxConcurrentRequests,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func classifyTypedInferenceErrorReason(_ error: Error) -> InferenceErrorReason?
}
if let serviceError = error as? MLXOpenAIServiceError {
switch serviceError {
case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed:
case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed:
// Response-format validation and parallel-tool enforcement inspect
// sampled model output. Another sample/provider can comply, so
// these share the retryable non-provider-fault reason above.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// after the model family so future fixes do not bleed across templates.

import Foundation
import MLXLMCommon
import MLXLMServer

struct ChatTemplateFixContext: Sendable {
Expand Down Expand Up @@ -132,6 +133,11 @@ enum ChatTemplateFixes {
return ids
}

static func stopStringScope(context: ChatTemplateFixContext) -> CBv2StopStringScope? {
GPTOSSHarmonyTemplateFix.applies(to: context)
? GPTOSSHarmonyTemplateFix.finalChannelStopScope : nil
}

static func validateGenericToolHistory(
_ messages: [[String: any Sendable]]
) throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ struct GLM5NextResponseFormatOutput {
content += parsed.content
guard let reasoning = parsed.reasoningContent, !reasoning.isEmpty else { return nil }
return .parsed(.init(content: "", reasoningContent: reasoning))
case .toolCall, .toolCallDelta, .info:
case .toolCall, .toolCallDelta, .info, .logprobs:
return event
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// templates without changing other model families.

import Foundation
import MLXLMCommon

enum GPTOSSHarmonyTemplateFix {
static func applies(to context: ChatTemplateFixContext) -> Bool {
Expand Down Expand Up @@ -37,6 +38,14 @@ enum GPTOSSHarmonyTemplateFix {
Set(["<|return|>", "<|endoftext|>", "<|call|>"].compactMap(tokenToId))
}

/// Client stop strings apply to the final channel, the text clients
/// receive as `content`. Matching them in analysis ended requests before
/// any answer existed (finish_reason "stop", reasoning only); tool-call
/// arguments are not answer text either.
static let finalChannelStopScope = CBv2StopStringScope(
opener: "<|channel|>final", openerEnd: "<|message|>",
closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"])

private static func isHarmonyModelHint(_ value: String?) -> Bool {
guard let value else { return false }
let normalized = value.lowercased()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ struct JSONAnswerOutput {
switch event {
case .content(let text): content += text
case .parsed(let parsed): content += parsed.content
case .toolCall, .toolCallDelta, .info: break
case .toolCall, .toolCallDelta, .info, .logprobs: break
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// slot construction has one scheduler-independent stop-token policy.

import Foundation
import MLXLMCommon

public enum ModelEOSPolicy {
/// Return model-specific EOS tokens at the engine boundary. Most models
Expand All @@ -24,4 +25,13 @@ public enum ModelEOSPolicy {
tokenToId: tokenToId
)
}

/// Where client stop strings apply; nil keeps whole-output matching.
public static func stopStringScope(
modelId: String,
modelType: String? = nil
) -> CBv2StopStringScope? {
ChatTemplateFixes.stopStringScope(
context: ChatTemplateFixContext(modelId: modelId, modelType: modelType))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ extension ProviderLoop {
}
if let svcErr = error as? MLXOpenAIServiceError {
switch svcErr {
case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed:
case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed:
return 422
case .embeddingsNotConfigured:
return 501
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,39 @@ struct EngineV2MatchedStopSequenceTests {
) == nil)
}

@Test("a scoped model reports only the stop that ended its answer")
func scopedMatchedSequence() {
let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b")
let analysis = "<|channel|>analysis<|message|>The answer: Canberra. Done.<|end|>"
#expect(EngineV2Bridge.matchedStopSequence(
candidates: ["."],
generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra",
scope: scope
) == nil, "a period in the analysis did not stop the request")
#expect(EngineV2Bridge.matchedStopSequence(
candidates: ["!", "."],
generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra. More",
scope: scope
) == ".")
}

@Test("GPT-OSS requests carry the bridge's stop-string scope")
func translationCarriesStopScope() {
let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b")
let request = ChatCompletionRequest(
model: "gpt-oss-20b", messages: [ChatMessage(role: "user", content: "hi")],
stop: .multiple(["\n\n"]))
let scoped = EngineV2Translation.cbv2Request(
id: CBv2RequestID(1), promptTokens: [1], request: request, defaultMaxTokens: 16,
stopTokenIds: [], stopStringScope: scope)
#expect(scoped.stopStrings == ["\n\n"])
#expect(scoped.stopStringScope == scope)
let unscoped = EngineV2Translation.cbv2Request(
id: CBv2RequestID(2), promptTokens: [1], request: request, defaultMaxTokens: 16,
stopTokenIds: [])
#expect(unscoped.stopStringScope == nil)
}

@Test("compares Unicode scalars exactly rather than canonically")
func unicodeScalarExactness() {
#expect(EngineV2Bridge.matchedStopSequence(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ private func recordServerStream(
events.append(.parsed(parsed))
case .info(let info):
events.append(.info(prompt: info.promptTokens, completion: info.completionTokens))
case .toolCall, .toolCallDelta:
case .toolCall, .toolCallDelta, .logprobs:
continue
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,17 @@ func harmonyEOSUsesModelTypeForAliasedModels() {
#expect(ids == [199999, 200002, 200012])
}

@Test("GPT-OSS client stop strings apply to the Harmony final channel only")
func gptOssStopStringsAreScopedToTheFinalChannel() {
let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b")
#expect(scope == CBv2StopStringScope(
opener: "<|channel|>final", openerEnd: "<|message|>",
closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"]))
#expect(ModelEOSPolicy.stopStringScope(modelId: "local-alias", modelType: "gpt_oss") == scope)
#expect(ModelEOSPolicy.stopStringScope(modelId: "gemma-4-26b-qat-4bit") == nil)
#expect(ModelEOSPolicy.stopStringScope(modelId: "qwen3.6-35b-a3b-vl-mtp-mxfp8") == nil)
}

@Test("non-Harmony EOS set is unchanged")
func nonHarmonyEOSIsUnchanged() {
let ids = ModelEOSPolicy.effectiveEOSTokenIds(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ struct GemmaToolCallLiveTests {
case .toolCall(let call): calls.append(call)
case .content(let text): visible += text
case .parsed(let parsed): visible += parsed.content
case .info: break
case .info, .logprobs: break
case .toolCallDelta: Issue.record("a named tool_choice call is never streamed")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,8 @@ private enum Qwen36ProductionCanary {
if let call = delta.completed { result.toolCalls.append(call) }
case .info(let info):
result.info = info
case .logprobs:
break
}
}
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ private struct FlintStreamOutcome {
case .toolCall(let call): calls.append(call)
case .toolCallDelta(let delta): if let call = delta.completed { calls.append(call) }
case .info(let info): self.info = info
case .logprobs: break
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ struct FlintResponseFormatOutputTests {
case .content(let text): outcome.content += text
case .toolCall: outcome.calls += 1
case .toolCallDelta(let delta): if delta.completed != nil { outcome.calls += 1 }
case .info: break
case .info, .logprobs: break
}
}
} catch { outcome.error = error }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private struct QwenAnswerOutcome {
case .content(let text): parser.parse(text).forEach { apply($0) }
case .parsed(let parsed): apply(parsed)
case .info(let info): self.info = info
case .toolCall, .toolCallDelta: break
case .toolCall, .toolCallDelta, .logprobs: break
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ final class NemotronSuperLocalOutputTests: XCTestCase {
return "F:" + call.function.name
+ String(decoding: try encoder.encode(call.function.arguments), as: UTF8.self)
case .info: return "I"
case .logprobs: return "L"
case .toolCallDelta:
XCTFail("the Super output holds calls until validation; it never streams fragments")
return "D"
Expand Down
Loading