Skip to content
Open
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
3 changes: 3 additions & 0 deletions ACKNOWLEDGMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ MLX Swift was developed with contributions from the following individuals:
- [John Mai](https://github.com/johnmai-dev): Added support for multiple models (Qwen2, Starcoder2, InternLM2, Qwen3,
Qwen3 MoE, GLM-4, MiMo, BitNet, SmolLM3, LFM2, Baichuan-M1, GPT-OSS, FalconH1, Exaone4, Qwen3.5, Qwen3.5 MoE).
- [Christoph Rohde](https://github.com/CodebyCR): Improved Embedders documentation. Added Gemma 3 Embedding Model.
- [John Auxillos](https://github.com/jyauxi): Added DeepSeek-OCR and Unlimited-OCR VLM support,
including `RingSlidingKVCache` for Reference Sliding Window Attention. The DeepSeek-OCR port is
adapted from [mzbac/deepseek-ocr.swift](https://github.com/mzbac/deepseek-ocr.swift) (MIT).

<a href="https://github.com/ml-explore/mlx-swift-lm/graphs/contributors">
<img class="dark-light" src="https://contrib.rocks/image?repo=ml-explore/mlx-swift-lm&anon=0&columns=20&max=100&r=true" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright © 2026 Apple Inc.

import CoreImage
import Foundation
import HuggingFace
import IntegrationTestHelpers
import MLXHuggingFace
import MLXLMCommon
import MLXVLM
import Testing
import Tokenizers

// MARK: - DeepSeek-OCR (deepseekocr) IntegrationTesting example
//
// Proves first-class DeepSeek-OCR via `VLMRegistry.deepseekOCR5bit`
// (`model_type=deepseekocr`) — not Unlimited remap, `UnlimitedOCR`, or R-SWA.
//
// Cache-gated on `mlx-community/DeepSeek-OCR-5bit`, or download it with
// `TEST_RUNNER_MLX_RUN_DEEPSEEK_OCR_INTEGRATION=1` (xcodebuild drops the prefix). OCR content quality is
// not asserted — load + prepare + short generate must succeed on the DeepSeek path.

private let deepseekOCRModelId = "mlx-community/DeepSeek-OCR-5bit"
private let unlimitedOCRModelId = "mlx-community/Unlimited-OCR-6bit"

private var shouldRunDeepseekOCRIntegration: Bool {
ProcessInfo.processInfo.environment["MLX_RUN_DEEPSEEK_OCR_INTEGRATION"] == "1"
|| hfSnapshotDir(modelId: deepseekOCRModelId) != nil
}

extension ModelLoadingSuite {
@Suite(
.serialized,
.timeLimit(.minutes(15)),
.enabled(if: shouldRunDeepseekOCRIntegration))
struct DeepseekOCRIntegrationTests {}
}

extension ModelLoadingSuite.DeepseekOCRIntegrationTests {

@Test
func loadsDeepseekOCRAndRunsOCR() async throws {
let container = try await TestModelManager.shared.load("deepseekocr-container") {
// Keep Hub `_orig_model_type` from diverting loads to UnlimitedOCR.
let tokenizerLoader = #huggingFaceTokenizerLoader()
let deepseekFactory = VLMModelFactory(
typeRegistry: VLMTypeRegistry.shared,
processorRegistry: VLMProcessorTypeRegistry.shared,
modelRegistry: VLMRegistry.shared,
honorOrigModelType: false)
if let dir = hfSnapshotDir(modelId: deepseekOCRModelId) {
return try await deepseekFactory.loadContainer(
from: dir, using: tokenizerLoader)
}
return try await deepseekFactory.loadContainer(
from: #hubDownloader(),
using: tokenizerLoader,
configuration: VLMRegistry.deepseekOCR5bit)
}

let isDeepseek = await container.perform { $0.model is DeepseekOCR }
let isUnlimited = await container.perform { $0.model is UnlimitedOCR }
#expect(isDeepseek, "expected DeepseekOCR for deepseekocr path")
#expect(!isUnlimited, "must not load UnlimitedOCR / R-SWA here")

// Synthetic page larger than one 640 tile, so gundam crops local tiles; asserts
// path health, not OCR accuracy.
let page = VisionTestImages.solidColor(.white, size: 1280)
let session = ChatSession(
container,
generateParameters: GenerateParameters(maxTokens: 32, temperature: 0),
// Keep native resolution (ChatSession default 512² best-fit breaks tiling).
processing: .init())

let text = try await session.respond(
to: "Free OCR.",
image: .ciImage(page))
#expect(!text.isEmpty, "DeepSeek-OCR produced empty output")
}
}

// MARK: - Unlimited-OCR chat template
//
// The processor the `UnlimitedOCRProcessor` key builds must render one `<image>`
// through the shipped pack's own chat template. Needs the pack's tokenizer and
// processor files, not its weights.

@Suite(
.serialized,
.enabled(if: hfSnapshotDir(modelId: unlimitedOCRModelId) != nil))
struct UnlimitedOCRTokenizerIntegrationTests {

@Test
func checkpointTemplateRendersImagePlaceholder() async throws {
let directory = try #require(hfSnapshotDir(modelId: unlimitedOCRModelId))
let tokenizer = TemplateRecordingTokenizer(
try await #huggingFaceTokenizerLoader().load(from: directory))
let configURL = try #require(
["preprocessor_config.json", "processor_config.json"]
.map { directory.appending(component: $0) }
.first { FileManager.default.fileExists(atPath: $0.path) })
let processor = try await VLMProcessorTypeRegistry.shared.createModel(
configuration: try Data(contentsOf: configURL),
processorType: "UnlimitedOCRProcessor",
tokenizer: tokenizer)

_ = try await processor.prepare(
input: UserInput(
prompt: "document parsing.",
images: [.ciImage(VisionTestImages.solidColor(.white, size: 64))]))

let render = try #require(tokenizer.renders.first)
let imageToken = try #require(tokenizer.convertTokenToId("<image>"))
#expect(render.contents == ["<image>document parsing."])
#expect(render.tokens.count(where: { $0 == imageToken }) == 1)
}
}

/// Forwards to a real tokenizer and records each chat-template render.
private final class TemplateRecordingTokenizer: MLXLMCommon.Tokenizer, @unchecked Sendable {
private let inner: any MLXLMCommon.Tokenizer
private let lock = NSLock()
private var _renders = [(contents: [String], tokens: [Int])]()

init(_ inner: any MLXLMCommon.Tokenizer) { self.inner = inner }

var renders: [(contents: [String], tokens: [Int])] { lock.withLock { _renders } }

func encode(text: String, addSpecialTokens: Bool) -> [Int] {
inner.encode(text: text, addSpecialTokens: addSpecialTokens)
}
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
inner.decode(tokenIds: tokenIds, skipSpecialTokens: skipSpecialTokens)
}
func convertTokenToId(_ token: String) -> Int? { inner.convertTokenToId(token) }
func convertIdToToken(_ id: Int) -> String? { inner.convertIdToToken(id) }
var bosToken: String? { inner.bosToken }
var eosToken: String? { inner.eosToken }
var unknownToken: String? { inner.unknownToken }

func applyChatTemplate(
messages: [[String: any Sendable]],
tools: [[String: any Sendable]]?,
additionalContext: [String: any Sendable]?
) throws -> [Int] {
let tokens = try inner.applyChatTemplate(
messages: messages, tools: tools, additionalContext: additionalContext)
lock.withLock {
_renders.append((messages.compactMap { $0["content"] as? String }, tokens))
}
return tokens
}
}
7 changes: 7 additions & 0 deletions Libraries/IntegrationTestHelpers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ xcodebuild test \
-scheme IntegrationTesting \
-destination 'platform=macOS' \
-only-testing:IntegrationTestingTests/ModelLoadingSuite/ToolCallIntegrationTests/qwen35FormatAutoDetection\(\)

# DeepSeek-OCR (deepseekocr) — cache-gated, or force Hub download
TEST_RUNNER_MLX_RUN_DEEPSEEK_OCR_INTEGRATION=1 xcodebuild test \
-project IntegrationTesting/IntegrationTesting.xcodeproj \
-scheme IntegrationTesting \
-destination 'platform=macOS' \
-only-testing:IntegrationTestingTests/ModelLoadingSuite/DeepseekOCRIntegrationTests
```

These tests do not run in CI.
Expand Down
31 changes: 31 additions & 0 deletions Libraries/MLXLMCommon/BaseConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ public struct BaseConfiguration: Codable, Sendable {
/// The architecture identifier (e.g., "bert", "roberta", "xlm-roberta").
public let modelType: String

/// Optional native architecture of a pack that shims `model_type` for a
/// foreign loader (`_orig_model_type` in `config.json`).
///
/// Honored when the loading factory opts in; see
/// ``resolvedModelType(honorOrigModelType:)``.
public let origModelType: String?

/// Configuration parameters for weight quantization.
///
/// MLX uses group-wise quantization to reduce memory footprint. This struct
Expand Down Expand Up @@ -207,6 +214,29 @@ public struct BaseConfiguration: Codable, Sendable {
Set(eosTokenIds?.values ?? textConfiguration?.eosTokenIds?.values ?? [])
}

/// Model type to try first for registry lookup.
///
/// When `honorOrigModelType` is true (default) and the pack declares a
/// non-empty `_orig_model_type`, returns that value trimmed and lowercased;
/// otherwise returns ``modelType``. Registry keys keep the Hub spelling
/// (underscore and hyphen forms are registered separately when both occur
/// in the wild), so the shim is matched as spelled. Whether the result is
/// loadable is the registry's decision — a factory that honors the original
/// type falls back to ``modelType`` when its registry has no creator for it.
///
/// Callers select the immutable policy per factory — see
/// `VLMModelFactory.init(…honorOrigModelType:)`.
public func resolvedModelType(honorOrigModelType: Bool = true) -> String {
guard honorOrigModelType,
let orig = origModelType?
.trimmingCharacters(in: .whitespacesAndNewlines),
!orig.isEmpty
else {
return modelType
}
return orig.lowercased()
}

/// The default quantization settings.
@available(*, deprecated, message: "Please use perLayerQuantization instead")
public var quantization: Quantization? {
Expand All @@ -220,6 +250,7 @@ public struct BaseConfiguration: Codable, Sendable {

enum CodingKeys: String, CodingKey {
case modelType = "model_type"
case origModelType = "_orig_model_type"
case quantizationContainer = "quantization"
case textConfiguration = "text_config"
case eosTokenIds = "eos_token_id"
Expand Down
13 changes: 13 additions & 0 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,19 @@ struct TokenRing {
return count < capacity ? buffer[..<count] : buffer
}

/// The valid tokens oldest-first, or `nil` if empty.
///
/// Once the ring has wrapped, `buffer` holds the tokens rotated by `writeIndex`
/// (the oldest token sits at `writeIndex`), so the two halves are re-joined here.
var orderedTokens: MLXArray? {
guard count > 0 else { return nil }
if count < capacity {
return buffer[..<count]
}
return writeIndex == 0
? buffer : concatenated([buffer[writeIndex...], buffer[..<writeIndex]])
}

/// Bulk-load from a prompt. Keeps the last `capacity` tokens.
///
/// Image sentinels (such as FastVLM's -200) are not vocabulary IDs, so they are
Expand Down
13 changes: 7 additions & 6 deletions Libraries/MLXLMCommon/GenerationEstimator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ extension GenerationEstimator.Cache {
extension KVCacheLeaf {
fileprivate var strategy: KVCacheStrategyIdentifier? {
switch kind {
case .simple, .rotating: .fullPrecision
case .simple, .rotating, .ringSliding: .fullPrecision
case .affine: .affine
case .turboQuant: .turboQuant
case .varianceNormalized: .varianceNormalized
Expand All @@ -473,11 +473,12 @@ extension KVCacheLeaf {
fixedBytes: state.reduce(0) { $0 + $1.nbytes }, capacity: nil)
}

let capacity =
if case .rotating(let rotating) = self.kind {
rotating.maxSize.map { $0 + rotating.rewindCapacity }
} else {
cache.maxSize
let capacity: Int? =
switch self.kind {
case .rotating(let rotating): rotating.maxSize.map { $0 + rotating.rewindCapacity }
// A ring keeps the whole prompt, which the probe cannot know.
case .ringSliding: nil
default: cache.maxSize
}
// Attention caches store tokens on axis 2 of `[batch, heads, tokens, dim]`.
let bytesPerToken = state.reduce(0) { total, array in
Expand Down
Loading
Loading