Skip to content

Add DeepSeek-OCR and Unlimited-OCR VLM support (MLXVLM) - #473

Open
jyauxi wants to merge 6 commits into
ml-explore:mainfrom
jyauxi:feature/deepseek-unlimited-ocr
Open

jyauxi wants to merge 6 commits into
ml-explore:mainfrom
jyauxi:feature/deepseek-unlimited-ocr

Conversation

@jyauxi

@jyauxi jyauxi commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Adds two closely-related OCR VLMs to MLXVLM. Closes #15.

Unlimited-OCR is a small delta on DeepSeek-OCR, which is why they are one PR.
UnlimitedOCR.swift is about 60 lines: two configuration aliases, the processor's .unlimited
factory, and a DeepseekOCR subclass whose only override is newCache(), returning a
RingSlidingKVCache instead of the default. Reviewing
the two separately would mean reviewing the same SAM+CLIP vision stack, the same gundam
processor and the same MoE decoder twice in order to land a cache policy. If you would still
rather take them as two PRs, say so and I will split it — the history is already sequenced
so that DeepSeek-OCR ends at a clean commit with Unlimited-OCR stacked on top.

DeepSeek-OCR

  • Port from mlx-vlm (Python): SAM + CLIP dual vision encoder, 16x convolutional compressor,
    projector, and the DeepSeek-V2 MoE language decoder.
  • DeepseekOCRProcessor with the gundam / base crop modes as first-class API
    (DeepseekOCRProcessor.Mode, modeContext(_:) / mode(from:)).
  • Grounding / ref / det token surface: DeepseekOCRSpecialTokens (id resolution, prompt
    builders, parseDetections(from:)).
  • Registry wiring: deepseekocr model type, DeepseekOCRProcessor / DeepseekVLV2Processor
    processor types.
  • Adapted from mzbac/deepseek-ocr.swift (MIT),
    refactored toward mlx-swift-lm patterns (GlmOcr, DeepseekV3 sanitize / @ModuleInfo).
    Attribution is in ACKNOWLEDGMENTS.md and in the DeepseekOCR.swift header.

Unlimited-OCR

  • RingSlidingKVCache — Reference Sliding Window Attention (R-SWA). Prefill retains the full
    prompt and image KV; decode then overwrites a ring of sliding_window_size (default 128),
    so the cache stays constant-size regardless of output length.
  • UnlimitedOCR: newCache() returns R-SWA caches. Everything else is inherited.
  • Registry wiring for the unlimited_ocr / unlimited-ocr model types.
  • Multipage fused prepare (base mode, max_num=32) on the shared processor.
  • Optional sliding-window no-repeat n-gram logits processor, off by default, matching
    mlx-vlm.

RingSlidingKVCache is not a substitute for RotatingKVCache

They differ in all three of prefill retention, rotation policy and RoPE offset, so the
existing cache cannot be reused here:

RingSlidingKVCache (R-SWA) RotatingKVCache (existing)
Prefill Retains full prompt + image KV Truncates / rotates per rotating policy
Decode After prefill_length + window_size, new KV overwrites a ring of size window_size Keeps leading tokens; rotates from the start
RoPE Absolute ropeOffset keeps increasing Offset policy differs

What touches shared code — flagging it up front

Adding two models should ideally touch only MLXVLM. These changes reach further, each for a
concrete reason, and I am happy to narrow any of them. No new package dependencies are added.

1. _orig_model_type is honoured by default. BaseConfiguration reads it, and
VLMModelFactory tries it first when its type registry knows that type, falling back to
model_type otherwise. Some Unlimited-OCR packs ship model_type: deepseekocr with
_orig_model_type: unlimited-ocr as a shim for loaders that predate the Unlimited
registration; honouring it is what loads such a pack as Unlimited-OCR rather than silently as
DeepSeek-OCR with an unbounded cache. It is still a default change on the load path every VLM
uses, for a key only these packs carry. The policy is an init parameter
(VLMModelFactory(…, honorOrigModelType:), default defaultHonorOrigModelType = true); if you
prefer, the default can be false with the OCR call sites opting in.

2. RingSlidingKVCache in MLXLMCommon. The cache Unlimited-OCR's R-SWA attention needs
(table above). Besides the class itself, the cache classifier, runtime, round staging and
estimator each get a .ringSliding case so it is treated as a model-defined window, and the
type registry registers it for prompt-cache save and load. No existing cache changes.

3. SlidingWindowNoRepeatNGramProcessor in MLXLMCommon (opt-in). Ports mlx-vlm's
repetition guard for long OCR decodes. Nothing touches GenerateParameters: the guard attaches
per request via GenerationComponents(logitProcessorFactory:) from #401.

4. MediaProcessing. The antialiased bicubic weights EmbeddingGemma 2 had privately move
here unchanged, since DeepSeek-OCR uses them too. resampleBicubic and
resampled(to:method:) gain a defaulted clampToExtent (off), which DeepSeek-OCR turns on; no
other model's pixels change.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: the code, tests, commit messages, this description and the review
    replies were drafted with Claude Code (Claude Opus); every commit carries a
    Co-Authored-By line.

@jyauxi
jyauxi force-pushed the feature/deepseek-unlimited-ocr branch from 90a5697 to a6b60d4 Compare July 27, 2026 12:14
@jyauxi
jyauxi marked this pull request as ready for review July 27, 2026 12:41
Comment on lines +235 to +238
let normalized = orig.lowercased().replacingOccurrences(of: "_", with: "-")
if normalized == "unlimited-ocr" {
return "unlimited-ocr"
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is not extensible outside of mlx-swift-lm -- developers cannot override this or add to it. I think it is OK to merge but we should follow up with a way to extend it.

Ideas:

  • a dictionary with with replacement text, e.g. ["unlimited_ocr": "unlimited-ocr"]
  • delegation -- register an array of closures, e.g. (String) -> String?

These could be stored in a locked array as a static property on BaseConfiguration. It could be initialized with this (above) handling and callers could add to it if they had other needs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed on both counts — fine as a follow-up, and the replacement-dictionary shape seems right: a locked static [String: String] on BaseConfiguration, initialized with the current handling, that callers can add entries to (with the closure-delegation form as an escalation if someone needs pattern-based rewriting rather than exact matches). Happy to open that follow-up PR once this lands.

Comment thread Libraries/MLXLMCommon/Evaluate.swift Outdated
Comment on lines +131 to +142
/// Optional sliding-window no-repeat n-gram size. `nil` or `<= 0` disables
/// the processor (matches mlx-vlm / Unlimited-OCR default of off). When set
/// (e.g. `35` in Unlimited-OCR examples), ``GenerateParameters/processor()``
/// attaches ``SlidingWindowNoRepeatNGramProcessor``.
public var noRepeatNgramSize: Int?

/// Search window for ``noRepeatNgramSize``. Unlimited-OCR examples use
/// `128` (single image) or `1024` (multi-page/PDF).
public var noRepeatNgramWindowSize: Int

/// Token IDs never banned by the n-gram processor (e.g. EOS).
public var noRepeatNgramWhitelistTokenIds: Set<Int>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am a little leery of adding more to GenerateParameters. We already have a repetition penalty, which sounds similar. Is this new processor general purpose? Or is it more likely to be used with these OCR models?

I wonder if this would fit better once #401 lands?

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.

Author of #401 here — happy to confirm it fits, and it'd actually let this PR drop some code rather than add it.

SlidingWindowNoRepeatNGramProcessor is already a LogitProcessor, so once #401 lands it attaches through GenerationComponents with nothing added to GenerateParameters:

var components = GenerationComponents()
components.logitProcessorFactory = {
    SlidingWindowNoRepeatNGramProcessor(
        ngramSize: 35, windowSize: windowSize, whitelistTokenIds: whitelist)
}

That directly addresses the "leery of adding more to GenerateParameters" concern — the three noRepeatNgram* properties wouldn't need to live on the value type. Two things that line up nicely:

  • The factory is invoked once per generation, so the processor's prompt/didSample state stays fresh each turn — which is what you want for a stateful n-gram tracker in a multi-turn session.
  • Add custom LogitProcessor injection to GenerateParameters / ChatSession #401 also adds a public ChainedLogitProcessor that's the same idea as the SequentialLogitProcessor this PR introduces (compose penalty + custom in order), so that helper would already be provided — no need for both.

The OCR-specific defaults (ngram size / window) are orthogonal to where the behavior lives — those could stay as a small preset that builds the components, without attaching to GenerateParameters. Glad to help wire it up whichever way you land once #401 is in.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed — and thanks @xocialize for confirming the fit. The processor itself is general purpose (it's a sliding-window no-repeat-n-gram ban), but today only these OCR models are known to need it, so I'd rather not grow GenerateParameters for it.

Happy to go whichever way you prefer:

  1. If Add custom LogitProcessor injection to GenerateParameters / ChatSession #401 lands first (my preference): I'll rebase, drop the three noRepeatNgram* properties and SequentialLogitProcessor, and attach SlidingWindowNoRepeatNGramProcessor through GenerationComponents, keeping the OCR-specific defaults (n-gram 35, window 128/1024) as a small preset that builds the components.
  2. If you'd rather merge this PR first: I can drop the GenerateParameters additions now — the processor stays public, callers construct it directly — and wire it into GenerationComponents as a follow-up once Add custom LogitProcessor injection to GenerateParameters / ChatSession #401 lands.

Either way the processor and its tests are unchanged; it's only the attachment point that moves.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in b988c9f — went with option 1 now that #401 has landed.

The three noRepeatNgram* properties and SequentialLogitProcessor are gone.
SlidingWindowNoRepeatNGramProcessor now attaches through GenerationComponents:

let components = GenerationComponents(
    logitProcessorFactory: { SlidingWindowNoRepeatNGramProcessor.unlimitedOCRSingleImage() }
)

Evaluate.swift is byte-for-byte identical to main again — this PR no longer touches
GenerateParameters at all. #401's public ChainedLogitProcessor does what the
SequentialLogitProcessor here was doing, so that helper is deleted rather than duplicated.
Net −71 lines.

One deviation from what I outlined above: instead of adding a preset that builds a
GenerationComponents, I left the OCR defaults where they already were — the existing
SlidingWindowNoRepeatNGramProcessor.unlimitedOCRSingleImage() / .unlimitedOCRMultiPage()
statics (n-gram 35, window 128/1024). Wrapping one of those in GenerationComponents is a
single line at the call site, so a separate preset didn't seem to earn its keep. Happy to add
one if you'd rather it be spelled out.

Thanks @xocialize — the factory-per-generation semantics are exactly right here. The processor
accumulates token history through didSample, so a fresh instance per generation is what you
want in a multi-turn session.

I also merged current main into the branch in the same push (this brings in #502's
ChatConventionsProviding migration). The one conflict was in VLMModelFactory.swift, where
the new conventionsRegistry landed adjacent to this PR's _orig_model_type remap docs — both
sides kept, and the tool-call/reasoning lookups now go through the registry rather than the
deleted infer chains. After the merge this PR deletes 7 lines total from pre-existing files
(5 in Load.swift, 2 in VLMModelFactory.swift); everything else is additive.

Verified locally: build clean, the eight SlidingWindowNoRepeatNGramProcessor tests pass,
swift-format lint clean, and DocC builds clean for MLXLMCommon and MLXVLM.

Comment thread Libraries/MLXLMCommon/Evaluate.swift Outdated
Comment on lines +306 to +310
// Cast to bfloat16 before argmax so ranking matches MLX Python models that
// keep decode logits in bf16. Float32 accumulation can invent a spurious
// ranking among tokens that are exact ties in bf16 (e.g. DeepseekOCR
// "4" vs "7" on the solid-red L3 fixture).
argMax(logits.asType(.bfloat16), axis: -1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Neither mlx-lm or mlx-vlm do this -- both process the logits in whatever dtype the model produces. This would affect all models, not just these OCR models. I wonder if the OCR models are producing float32 logits and perhaps they should do the dtype conversion?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — you're right that this belongs in the model, not the shared sampler. Fixed in 2f857c5: ArgMaxSampler is back to upstream's plain argMax(logits, axis: -1), and DeepseekOCR.computeLogits now emits bf16 logits itself (which UnlimitedOCR inherits).

Background on why the cast exists at all: Python mlx-vlm keeps decode logits in bf16, so greedy argmax there resolves ties at bf16 precision. The Swift port was ranking in higher precision, which broke exact-tie ordering on one of our parity fixtures (token "4" vs "7" on a synthetic solid-color image). Casting at the model boundary reproduces the Python ranking exactly, and no other model is affected now. Verified behavior-preserving: all three of our gold fixtures (single-page gundam ×2, three-page base with the n-gram processor active) reproduce byte-identically against their pre-change baselines.

Comment thread Libraries/MLXLMCommon/KVCache.swift Outdated
/// rotates from the start, which is a different sliding-window semantics.
///
/// Port of Python `mlx_vlm.models.unlimited_ocr.language.RingSlidingKVCache`.
public class RingSlidingKVCache: KVCacheSimple {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good!

jyauxi added a commit to jyauxi/mlx-swift-lm that referenced this pull request Aug 1, 2026
Review feedback on ml-explore#473: the shared sampler should process logits in
whatever dtype the model produces, as mlx-lm and mlx-vlm do. DeepseekOCR
now emits bf16 logits from computeLogits (UnlimitedOCR inherits it), so
the bf16 tie-break ranking that matches Python mlx-vlm greedy decode is
scoped to these models instead of affecting every model in the library.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Comment thread Libraries/MLXLMCommon/KVCache.swift Outdated
Comment on lines +844 to +845
if self.keys == nil || offset < prefill + windowSize {
let result = super.update(keys: keys, values: values)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this needs to consider seqLen -- super doesn't have any idea of the windowSize and seqLen can be > 1.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — fixed in b546ee4. update no longer delegates blindly while the window is filling: a step that fits below prefill + windowSize grows in place, and a multi-token step that overlaps the ring now follows RotatingKVCache's concat precedent — it returns [prefix | last windowSize − 1 decode tokens | new tokens] in temporal order so every new token sees its full window, then retains only prefix + last windowSize. makeMask produces the matching array mask for that case (prefix always visible, decode columns limited to each query's trailing window). Also clamped trim(): trimming back to/below the marked prefix now unmarks it, so prompt-cache reuse can't leave a stale boundary (related to your isTrimmable(after:) idea on #506).

For the record, the Python reference has the same overshoot in its grow branch (and its multi-token ring branch writes slots sequentially without reordering), so this is a deliberate divergence-as-fix rather than drift — single-token decode, the only path Python exercises in practice, is numerically unchanged (our gold fixtures are byte-identical). Happy to upstream the same fix to mlx-vlm.

New tests: boundary-crossing step, wrapped-ring reorder, ring-step mask layout, trim-below-prefix. The branch is also current with main again (merged through #513, adopted the #470 PrefillParameters signature).

Comment thread Libraries/MLXLMCommon/KVCache.swift Outdated
/// rotates from the start, which is a different sliding-window semantics.
///
/// Port of Python `mlx_vlm.models.unlimited_ocr.language.RingSlidingKVCache`.
public class RingSlidingKVCache: KVCacheSimple {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The port is faithful, but I wonder if this needs to be a subtype of BaseKVCache instead (like RotatingKVCache). Consider:

    func isQuantizable(_ cache: KVCache) -> Bool {
        if let list = cache as? CacheList {
            return list.children.contains(where: isQuantizable)
        }
        return cache is KVCacheSimple
            && !(cache is QuantizedKVCache)
            && cache.offset > quantizedKVStart
    }

if we had a config where quantization was attempted, this cache would be quantized, likely with ill effect.

Either change the parent type or maybe we need an isQuantizable property on the KVCache that allows opt-in/opt-out. KVCacheSimple could produce true and this would override to false.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Went with your first suggestion: RingSlidingKVCache now extends BaseKVCache directly, mirroring RotatingKVCache — it owns its allocation path and no longer inherits KVCacheSimple's toQuantized() surface, so the is KVCacheSimple eligibility check skips it for free. After merging current main, that composes nicely with the typed cache configuration from #453 too: the ring cache classifies as unsupported-for-compression in KVCacheTree, so both the legacy path and the new plan machinery leave it alone. That felt cleaner than adding an isQuantizable knob to the KVCache protocol for one cache — but if you'd like that opt-out on the protocol anyway (for future caches), happy to add it.

Test added: maybeQuantizeKVCache leaves the ring cache untouched while a KVCacheSimple control with identical contents converts.

@jyauxi

jyauxi commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Since your 2026-08-07 review — three commits, in review order:

  1. b546ee4 — the response to both comments: RingSlidingKVCache reparented to BaseKVCache + seqLen > 1 handling (isolated compare: 2 files, KVCache.swift + its tests). This is the only commit that needs review.
  2. 13065f0 — merge of current main (your Add typed KV cache configuration and runtime reporting #453/Olmo3: fix newCache signature so the sliding-window cache is actually used #462/Prefill: balanced chunking behind a new PrefillParameters (~9% at 32K) #470/Add parser for GPT-OSS Harmony tool call format #146/Stand down from MTP speculation before the sliding cache wraps #506/Run Integration Tests nightly and report failures on a tracking issue #513; zero conflicts, no manual edits).
  3. ff98294 — Prefill: balanced chunking behind a new PrefillParameters (~9% at 32K) #470 PrefillParameters adoption (same shape as GlmOcr) + the root-README OCR section folded into Libraries/MLXVLM/README.md.

Workflows need approval to run on this push; the same matrix is green locally (build, 423 tests / 40 suites incl. the new #453/#470 suites, swift-format). Details in the two thread replies.

@jyauxi

jyauxi commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

Catch-up merge with main — no change to the code under review.

Since the last round this branch has merged main twice, most recently a4a05e0. Both are pure upstream catch-up:

  • The OCR port is byte-identical to the head you last reviewed — DeepseekOCR.swift, UnlimitedOCR.swift and SlidingWindowNoRepeatNGramProcessor.swift all diff empty, and RingSlidingKVCache is untouched inside KVCache.swift.
  • The only non-upstream content is a three-line conflict resolution. Add Muse-Glimmer, a 30B agentic multimodal model, with ATEM tool calling #523 (Muse-Glimmer) appends to the same three lists this PR does, so both sets of entries now sit side by side:
    • Libraries/MLXVLM/VLMModelFactory.swift (type registry, processor registry, all())
    • Libraries/MLXVLM/README.md
    • skills/mlx-swift-lm/references/supported-models.md

A couple of notes on upstream changes that land near this PR, in case they save you a question:

  • Prompt cache: persist model state, wire Qwen3-VL and GLM-OCR restoration, and fail closed #475 gave GLM-OCR an anchored warm-cache continuation path. The equivalent doesn't apply here: DeepSeek-OCR's decoder uses 1-D RoPE off cache.ropeOffset, so positions already equal the cache offset and there's no rope_deltas anchor to carry — QwenVL.continuationAnchor would be guarding an invariant this model satisfies by construction. Adopting PrefillParameters.forEachChunk chunked prefill in DeepseekOCR.prepare is worthwhile and the ring cache already tolerates it (prefillLength defers to the first single-token decode step, so N prefill chunks produce the same reference prefix as one forward). Happy to fold that into this PR if you'd rather have it here than as a follow-up — it needs a gold-fixture parity run since chunking changes float reduction order.
  • Enforce and expose effective maxKVSize cache policy #514 doesn't reach RingSlidingKVCache; keepCount and effectiveKVCacheCapacity are package-scoped on RotatingKVCache.
  • Known gap, your call: restoreCacheFromMetaState has no RingSlidingKVCache case, so saving and reloading a prompt cache for an Unlimited-OCR model throws Unknown cache class. The cache already implements state/metaState, so it's a small addition — say the word and I'll add it here, otherwise I'll keep it as a follow-up.

Local verification on the merge: xcodebuild build-for-testing green; xcrun xctest MLXLMTests → 581 tests / 49 suites, 0 failures, 1 env-gated skip (LAYER_PARITY_GOLDEN).

@davidkoski

Copy link
Copy Markdown
Member

Don't worry about the xcode27 failure -- there is API drift in the beta SDK

/// rotates from the start, which is a different sliding-window semantics.
///
/// Port of Python `mlx_vlm.models.unlimited_ocr.language.RingSlidingKVCache`.
public class RingSlidingKVCache: BaseKVCache, CustomDebugStringConvertible {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This needs the isTrimmable(after:) (newish API, probably after this was written) -- see RotatingKVCache

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added RingSlidingKVCache.isTrimmable(after:) using the same predictive boundary as RotatingKVCache: the cache is trimmable only while offset + positions < prefillLength + windowSize. This rejects reuse before an append would enter ring-overwrite mode. Covered by testIsTrimmablePredictsWhetherAppendWouldFillRing.

Comment thread Libraries/MLXLMCommon/KVCache.swift Outdated
throw KVCacheError(
message: "Invalid RingSlidingKVCache metaState - expected 4 values")
}
let cache = RingSlidingKVCache(windowSize: max(windowSize, 1))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this should probably have the guard like this other cases:

if !state.isEmpty {
    cache.state = state
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. Restoration now assigns cache.state only when the serialized state is non-empty. testEmptySerializationRoundTripDoesNotAssignEmptyState covers the empty round trip.

}

@_spi(Testing)
public func prepareForTesting(input: UserInput) async throws -> PreparedImageInputs {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this name should be clarified -- it is also used in the production code path. The "Testing" is misleading. internalPrepare() or something along those lines perhaps?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed this to internalPrepare. Production prepare delegates to the same helper; the Testing SPI only exposes the intermediate result for assertions.

Comment on lines +797 to +798
let promptTokens = tokenizer.encode(
text: userPromptText(from: input), addSpecialTokens: true)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This should probably use the message generator / chat template, e.g.:

        let messages = Qwen2VLMessageGenerator().generate(from: input)

        var promptTokens = try tokenizer.applyChatTemplate(
            messages: messages, tools: input.tools,
            additionalContext: input.additionalContext)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched the preparation path to a MessageGenerator followed by tokenizer.applyChatTemplate.

One checkpoint-specific difference from the Qwen example: the shipped DeepSeek/Unlimited templates render message.content directly and do not translate Qwen-style structured image parts into <image>. DeepseekOCRMessageGenerator therefore emits the configured image placeholder as string content while preserving the full chat history and tool metadata.

The cached Unlimited production tokenizer now renders exactly one image token for a normal one-image prompt.

return (processed, tilesWide, tilesHigh)
}

private func userPromptText(from input: UserInput) -> String {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks equivalent to MessageGenerator, e.g. see Qwen2VLMessageGenerator

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed the last-user-prompt helper. Model-specific conversion now lives in DeepseekOCRMessageGenerator, which conforms to MessageGenerator. Tests cover string-content generation, explicit placeholders, multipage input, and preservation of the remaining chat-template output.

Comment thread Libraries/MLXVLM/VLMModelFactory.swift Outdated
public func _load(
configuration: ResolvedModelConfiguration,
tokenizerLoader: any TokenizerLoader,
honorOrigModelType: Bool

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Rather than adding an overload, I think this could just have an optional with a default.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed the additional load overloads. honorOrigModelType is now a defaulted, immutable VLMModelFactory initializer option.

I kept _load(configuration:tokenizerLoader:) with its existing signature because it is the GenericModelFactory protocol witness; adding a defaulted argument does not satisfy that witness. This keeps the default behavior configurable without expanding the load overload family.

Comment thread Libraries/MLXVLM/VLMModelFactory.swift Outdated
// Hub packs often ship DeepseekVLV2Processor; native unlimited-ocr
// routing prefers UnlimitedOCRProcessor (same tokenize path).
"unlimited-ocr": "UnlimitedOCRProcessor",
"unlimited_ocr": "UnlimitedOCRProcessor",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

See also #565 -- there may be some incoming changes in this area.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adapted this to the #565-style processor-loading path. The Unlimited aliases now resolve through VLMProcessorLoadingRegistry, including checkpoints declaring DeepseekVLV2Processor.

I also changed the test to exercise VLMProcessorLoadingRegistry.shared directly instead of constructing a resolver with a duplicated copy of the production mapping.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

See questions/feedback regarding KVCache API and prepare/text handling. Thanks!

@jyauxi

jyauxi commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the latest review. I merged current main (9219508) into the branch and addressed each open thread directly.

Verification:

  • MLXLMTests: 693 tests / 54 suites, 0 failures
  • strict swift-format check passed on the PR changes
  • cached Unlimited production tokenizer rendered exactly one <image> token for a normal one-image prompt

The prompt test double now matches the checkpoints’ real string-only chat-template behavior, and the processor-registry test exercises the shared production registry instead of duplicating its mapping.

Ready for re-review when convenient.

@jyauxi

jyauxi commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Catch-up merge with main — no change to the code under review.

Merged current main (37688d2) into the branch: one merge commit, zero conflicts, no manual edits. The OCR port is byte-identical to the head you last reviewed — DeepseekOCR.swift, UnlimitedOCR.swift, the processor, and the factory/registry files all diff empty, and RingSlidingKVCache is untouched inside KVCache.swift (the only delta in that file is #329's VarianceNormalizedKVCache arriving alongside it).

The main motivation is CI: the previous run's only failure was integration_build_xcode27, failing on the known beta-SDK drift in MLXFoundationModels — a target this PR doesn't touch, and the job #582 has since disabled on the PR path. This merge brings that in, so the rerun reflects only code this PR owns.

Local verification on the merge:

  • xcodebuild build-for-testing green; scripts/verify-docs.sh passed
  • MLXLMTests: 604 XCTest tests (0 failures, 2 env-gated skips) + 722 Swift Testing tests / 55 suites, all passed
  • Local caveat: built with the FoundationModelsIntegration trait disabled, since MLXFoundationModels doesn't compile against the current Xcode 27 beta seed (same drift the retired CI job hit). That matches the stable-Xcode CI environment, where the adapter compiles out; MLXLMTests doesn't depend on it.

All seven threads from your 2026-08-24 review remain addressed as of the previous push — this merge changes none of that code. Ready for re-review when convenient.

div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ips-uncommitted-import

GLM refused prefix restore: a cold start gets its own MTP binding
@davidkoski davidkoski self-assigned this Dec 4, 2026
Comment on lines +617 to +619
/// Bicubic resize with edge clamp — CI's default samples empty outside the
/// extent, which washes tile borders (local crop corners were ~0.70 not 1.0).
private func resampleClamped(_ image: CIImage, to size: CGSize) -> CIImage {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a good idea but I wonder this this should be in MediaProcessing -- clampToExtent is probably what all callers want (unless they are doing a center crop, in which case they don't care).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, moved. MediaProcessing.resampleBicubic(_:to:clampToExtent:) and CIImage.resampled(to:method:clampToExtent:) now take a defaulted clampToExtent, and the model's private resampleClamped is gone (9931c80). When it is set, edge pixels repeat before the scale and the result is cropped at the scaled image's origin (the current default crops at zero).

I left the default off for now: turning it on changes the border pixels of every model that uses the bicubic resize, so it seemed better as its own change with its own checks. Happy to send that PR if you want it on for everyone.

Test: MediaProcessingTests.testResampleBicubicClampToExtent (equal to the old private resize pixel for pixel, edge values kept, default output unchanged).

Comment on lines +611 to +613
return placed.composited(over: canvas)
.normalized(mean: config.imageMeanTuple, std: config.imageStdTuple)
.asMLXArray()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is rendering in whatever colorspace the image is in, which is often not sRGB. This should probably be something like:

        image
            .toSRGB()
            .resampled(to: resizedSize, method: .bicubic)

Note that the conversion to sRGB is done before the resampling. In general this is incorrect (you want to resample in linear space) but this is how most python libraries operation and certainly how PIL does.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right: page content reaches the model in linear light today. Only the pad colour is corrected for it.

I tried exactly this (toSRGB() before the resize, for the global view and the tiles, with the pad at PIL's byte mean) and measured each fixture's line distance to mlx-vlm's output on the same pack (lower is closer to Python):

fixture today with toSRGB()
sample (DeepSeek) 0 2
sample (Unlimited) 6 14
invoice (Unlimited) 8 18
invoice, detections (Unlimited) 8 18
dense policy (Unlimited) 8 20
receipt (DeepSeek) 12 38
invoice, grounding (DeepSeek) 24 14
table, grounding (DeepSeek) 16 18
multipage, fused (Unlimited) 21 21
multipage demo, fused (Unlimited) 90 67

Seven of the eight single-page fixtures moved further from Python, so I have left the preprocessing as it is in this round. An earlier try in this PR gave a similar result.

How would you like to go: keep it as it is, or take the PIL-style conversion anyway and chase the remaining difference separately?

Comment on lines +589 to +606
func srgbEncode(_ linear: CGFloat) -> CGFloat {
if linear <= 0.0031308 { return linear * 12.92 }
return 1.055 * pow(linear, 1.0 / 2.4) - 0.055
}
let padLinear = (
pilMeanByte(config.imageMean[0]),
pilMeanByte(config.imageMean[1]),
pilMeanByte(config.imageMean[2])
)
let padColor = CIColor(
red: srgbEncode(padLinear.0),
green: srgbEncode(padLinear.1),
blue: srgbEncode(padLinear.2))
let canvas = CIImage(color: padColor).cropped(
to: CGRect(x: 0, y: 0, width: targetSide, height: targetSide))
let dx = ((targetSide - contained.width) * 0.5).rounded() - resized.extent.origin.x
let dy = ((targetSide - contained.height) * 0.5).rounded() - resized.extent.origin.y
let placed = resized.transformed(by: CGAffineTransform(translationX: dx, y: dy))

@davidkoski davidkoski Dec 4, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is pretty similar to MediaProcessing.padToSquare() -- if this needs rectangular padding, we should add a padToRect() I think. But maybe this is a square too. At the top of the file:

// ... ImageOps.pad(image, (side, side)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It is a square, but padToSquare does not place the content where PIL does. It centres with unrounded offsets ((side - w) * 0.5), so an odd gap gives a half-pixel shift. ImageOps.pad pastes at round(gap / 2) from the top left, and Python rounds half to even.

Checking this showed our own placement is also one pixel off from PIL in about half of the odd-gap cases. I tried matching PIL exactly. Nine of the ten fixtures changed, but only one moved closer to mlx-vlm's output (table 16 → 12) and one moved further (sample, DeepSeek 0 → 2), so I left it as it is for now and wrote it down as a known deviation.

If you would like this shared, I can add a rounded option to padToSquare (or a padToRect) in a follow-up. Your call.

Comment on lines +767 to +769
let x = (block % tilesWide) * tileSize
let y = (block / tilesWide) * tileSize
let cropRect = CGRect(x: x, y: y, width: tileSize, height: tileSize)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am not sure this is correct -- CoreImage coordinates are quadrant 1 with the origin at the lower left while PIL and others are typically origin and the upper right. I think this is probably constructing the tiles out of order compared to what the model expects.

See SmolVLM2:

        // Warning: in CIImage, y=0 is the bottom side. We reverse the rows to match the transformers processor
        let tileEdge = Int(fixedImageSize)
        for row in (0 ..< nRows).reversed() {
            for col in 0 ..< nCols {
                let x0 = col * tileEdge
                let y0 = row * tileEdge
                let x1 = min(x0 + tileEdge, Int(image.extent.size.width))
                let y1 = min(y0 + tileEdge, Int(image.extent.size.height))

                let tile = image.cropped(to: CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0))
                tiles.append(tile)
            }
        }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. This was wrong in the version you reviewed and is fixed: the tiles are now cropped row by row from the top, with the row index flipped for Core Image's bottom-left origin, as in SmolVLM2 (dynamicPreprocess).

Test: DeepseekOCRProcessorTests.testGundamTilesRunTopToBottomAsPythonCrops.

Comment thread Libraries/MLXVLM/VLMModelFactory.swift Outdated
Comment on lines +300 to +301
static public let unlimitedOCR6bit = ModelConfiguration(
id: "majentik/Unlimited-OCR-MLX-6bit",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks like a personal org in HF -- is there an official release?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, both entries now point at mlx-community: mlx-community/DeepSeek-OCR-5bit and mlx-community/Unlimited-OCR-6bit.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Sorry for the long turnaround time on this -- added some feedback on the image processing and a few other spots. This needs a rebase so it can be reviewed in the context of current code. Thank you!

embeddings = mergeInputIdsWithImageFeatures(
inputIds: input.text.tokens, imageFeatures: imageFeatures)
} else {
embeddings = languageModel.embedTokens(input.text.tokens)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There are cases where this can get 1D tokens and this (and other places) can potentially crash because of the unexpected shape.

Many of the VLMs have code like this:

            var tokens = input.text.tokens
            if tokens.ndim == 1 { tokens = tokens.expandedDimensions(axis: 0) }

that may be needed here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the two lines at the top of prepare, so rank-1 tokens get the batch axis before the image merge and the embedding (a45c94c).

Test: DeepseekOCRProcessorTests.testPrepareTreatsRankOneTokensAsOneBatch (rank-1 and rank-2 tokens give the same logits, text-only and with an image).

Comment on lines +1012 to +1019
if prefillLength == nil {
// Multi-token prefill: grow like a standard cache; defer marking
// prefill length until the first single-token decode step.
if seqLen > 1 {
return appendGrowing(keys: keys, values: values)
}
prefillLength = offset
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

prefillLength is set on the first single token update. Speculative decoding never triggers it. mlx-vlm (current) sets prefill_length = offset + length -- I think the same should be done here. Having this not set is (I think) a bug.

A repro case I had claude generate:

RingSlidingKVCacheReviewTests.swift.zip

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, that was a bug. If beginPrefill was not called, the first update of any length now marks prefillLength = offset + length. That is the rule current mlx-vlm (0.8.3) applies in the language model to a fresh cache (e7f6970). The model's own prefill still calls beginPrefill before the first chunk, so that path does not change.

I also changed trim: trimming back to the prefix boundary now keeps the mark, so a rejected verify batch retried there goes into the ring rather than the prefix. Trimming into the prefix still clears it.

The same commit stops the generation estimator from taking a ring cache's capacity from its two-token probe, which the new rule now marks as the prefix. A ring keeps the whole prompt, so its capacity is left open (GenerationEstimatorTests.ringSlidingLayersGrowWithThePrompt).

Thanks for the repro. The first case is now RingSlidingKVCacheTests.testMultiTokenOnlyDecodeStaysBoundedAndMatchesItsMask, which also checks each step's returned keys against its mask. The second case (a follow-up prompt on a warm cache) still evicts. mlx-vlm extends the prefix with the new prompt there, while beginPrefill leaves an existing mark alone. I would rather do that as its own change, since it affects chat-session reuse. Your call.

jyauxi and others added 6 commits December 5, 2026 21:16
- RingSlidingKVCache: the rotating cache mlx-vlm uses for R-SWA
  attention (a fixed prefix plus a ring of recent tokens), registered
  with the cache type registry and the cache tree.
- SlidingWindowNoRepeatNGramProcessor: the windowed no-repeat-n-gram
  logits processor from mlx-vlm's DeepSeek-OCR generation path.
- BaseConfiguration reads `_orig_model_type`, and VLMModelFactory
  builds the model from it when the type registry knows it, falling back
  to `model_type` otherwise (`honorOrigModelType`, default on).
- MediaProcessing gains the shared helpers EmbeddingGemma2 already used
  privately; EmbeddingGemma2 now calls them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports mlx-vlm's `deepseekocr` model: the SAM + CLIP vision encoder, the
projector and the DeepSeek-V2 MoE decoder, plus `DeepseekOCRProcessor`
(base and Gundam tiling, grounding prompts and detection parsing,
fused multipage). The processor also carries the per-pack settings that
Unlimited-OCR, which shares this encoder and decoder, reuses.

Registers `deepseekocr`, the `DeepseekOCRProcessor` and
`DeepseekVLV2Processor` processor keys, and
`mlx-community/DeepSeek-OCR-5bit`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unlimited-OCR is DeepSeek-OCR with a one-placeholder prompt, a 32-tile
cap, a fused multipage path, a layout output format and reference
sliding-window attention, which runs on RingSlidingKVCache. Ports
mlx-vlm's `unlimited_ocr` as a subclass of DeepseekOCR plus the
`DeepseekOCRProcessor.unlimited` factory.

Registers `unlimited_ocr` and `unlimited-ocr`, the
`UnlimitedOCRProcessor` key, the processor rule for packs that declare
`DeepseekVLV2Processor`, and `mlx-community/Unlimited-OCR-6bit`. Adds the
integration tests, the README sections and the acknowledgment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RingSlidingKVCache marked its prefix only on the first single-token
update, which speculative decoding never makes: its verify steps carry
numDraft + 1 tokens, so the prefix stayed unmarked and the cache grew
without bound. Without beginPrefill(promptLength:), the first update now
marks `offset + length`, the rule mlx-vlm's language model applies to a
fresh cache (mlx-vlm 0.8.3, unlimited_ocr/language.py).

Trimming back to the prefix boundary now keeps the mark, so a rejected
verify batch retried there goes to the ring, not into the prefix.
Trimming into the prefix still clears it.

The generation estimator no longer takes a ring cache's capacity from
its two-token probe, which now marks the prefix: a ring keeps the whole
prompt, so its size grows with the prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The processor always builds `[1, n]` tokens, but a caller that builds
its own LMInput can pass rank-1 tokens, and the image merge and
embedding would then fail on the shape. prepare now adds the batch axis
first, as other VLMs do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
resampleBicubic and CIImage.resampled(to:method:) take a defaulted
`clampToExtent` parameter. When it is set, edge pixels repeat before
the bicubic scale, so border taps do not sample transparent black, and
the result is cropped at the scaled image's origin. That is the resize
DeepSeek-OCR carried privately as resampleClamped, which is now
deleted. The default stays off, so no other model's pixels change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jyauxi
jyauxi force-pushed the feature/deepseek-unlimited-ocr branch from 53b39ef to 9931c80 Compare December 5, 2026 17:43
@jyauxi

jyauxi commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. This round rebases the branch onto current main (d8d2de2) and answers all seven comments. The rebase meant a force push; the history is now three area commits plus one commit per fix.

Commits, in review order

  1. 787710f Add the shared pieces DeepSeek-OCR and Unlimited-OCR need
  2. e4376d5 Add DeepSeek-OCR
  3. 30bd889 Add Unlimited-OCR
  4. e7f6970 Mark the ring cache's prefix on its first update of any length (your prefillLength comment)
  5. a45c94c Accept rank-1 tokens in DeepSeek-OCR's prepare (1-D tokens)
  6. 9931c80 Move DeepSeek-OCR's edge-clamped resize into MediaProcessing (clamp)

DeepSeek-OCR ends at a clean commit (2), so the split into two PRs is still on offer. Commits 4–6 are the fixes for this review: jyauxi/mlx-swift-lm@30bd889...9931c80

Commits 1–3 also carry work you have not seen yet, done after 53b39ef and before your review arrived: following mlx-vlm 0.8.0 (chunked prefill with the last prompt token alone, the MoE gate in the activation dtype, RingSlidingKVCache.beginPrefill fixing the prefix before a chunked prefill), the tile-order fix and the mlx-community model ids. They also add the ring cache to two switches that landed on main since the last merge (GenerationEstimator, KVCacheTree.checkpointStrategy), and give the DeepSeek-OCR processor tests' small model a vocabulary that covers the test tokenizer's ids (one test was reading past the embedding table and failed when its suite ran alone).

No code change, with measurements: the sRGB conversion and padToSquare. Both moved the output further from mlx-vlm's on some fixtures, so the replies give the numbers and ask how you want to go.

Verification on 9931c80

  • xcodebuild build-for-testing and scripts/verify-docs.sh: pass.
  • xcodebuild test: XCTest 1356 tests, 0 failures, 10 skipped (checkpoint downloads, benchmarks and one golden-file test); Swift Testing 1723 tests in 144 suites passed, with 2 known issues.
  • Integration tests against the downloaded packs: DeepseekOCRIntegrationTests and UnlimitedOCRTokenizerIntegrationTests, 2 tests, both pass.
  • End-to-end: all 10 OCR fixtures (both packs, grounding, fused multipage) and a 92-page book scan are byte-identical to their outputs from before this round.

Your call

  • Turning clampToExtent on by default for every bicubic caller (a separate PR, as it changes other models' border pixels).
  • Your second repro: a follow-up prompt on a warm ring cache still evicts, where mlx-vlm extends the prefix. I would do it as its own change.
  • A rounded option for padToSquare (or padToRect), if you want the pad shared.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for Deepseek OCR

4 participants