Repository navigation
Conversation
90a5697 to
a6b60d4
Compare
| let normalized = orig.lowercased().replacingOccurrences(of: "_", with: "-") | ||
| if normalized == "unlimited-ocr" { | ||
| return "unlimited-ocr" | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| /// 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> |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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/didSamplestate 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
ChainedLogitProcessorthat's the same idea as theSequentialLogitProcessorthis 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.
There was a problem hiding this comment.
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:
- If Add custom LogitProcessor injection to GenerateParameters / ChatSession #401 lands first (my preference): I'll rebase, drop the three
noRepeatNgram*properties andSequentialLogitProcessor, and attachSlidingWindowNoRepeatNGramProcessorthroughGenerationComponents, keeping the OCR-specific defaults (n-gram 35, window 128/1024) as a small preset that builds the components. - If you'd rather merge this PR first: I can drop the
GenerateParametersadditions now — the processor stayspublic, callers construct it directly — and wire it intoGenerationComponentsas 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.
There was a problem hiding this comment.
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.
| // 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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| /// 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 { |
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>
| if self.keys == nil || offset < prefill + windowSize { | ||
| let result = super.update(keys: keys, values: values) |
There was a problem hiding this comment.
I think this needs to consider seqLen -- super doesn't have any idea of the windowSize and seqLen can be > 1.
There was a problem hiding this comment.
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).
| /// 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Since your 2026-08-07 review — three commits, in review order:
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. |
|
Catch-up merge with Since the last round this branch has merged
A couple of notes on upstream changes that land near this PR, in case they save you a question:
Local verification on the merge: |
|
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 { |
There was a problem hiding this comment.
This needs the isTrimmable(after:) (newish API, probably after this was written) -- see RotatingKVCache
There was a problem hiding this comment.
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.
| throw KVCacheError( | ||
| message: "Invalid RingSlidingKVCache metaState - expected 4 values") | ||
| } | ||
| let cache = RingSlidingKVCache(windowSize: max(windowSize, 1)) |
There was a problem hiding this comment.
I think this should probably have the guard like this other cases:
if !state.isEmpty {
cache.state = state
}There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Renamed this to internalPrepare. Production prepare delegates to the same helper; the Testing SPI only exposes the intermediate result for assertions.
| let promptTokens = tokenizer.encode( | ||
| text: userPromptText(from: input), addSpecialTokens: true) |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
This looks equivalent to MessageGenerator, e.g. see Qwen2VLMessageGenerator
There was a problem hiding this comment.
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.
| public func _load( | ||
| configuration: ResolvedModelConfiguration, | ||
| tokenizerLoader: any TokenizerLoader, | ||
| honorOrigModelType: Bool |
There was a problem hiding this comment.
Rather than adding an overload, I think this could just have an optional with a default.
There was a problem hiding this comment.
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.
| // Hub packs often ship DeepseekVLV2Processor; native unlimited-ocr | ||
| // routing prefers UnlimitedOCRProcessor (same tokenize path). | ||
| "unlimited-ocr": "UnlimitedOCRProcessor", | ||
| "unlimited_ocr": "UnlimitedOCRProcessor", |
There was a problem hiding this comment.
See also #565 -- there may be some incoming changes in this area.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
See questions/feedback regarding KVCache API and prepare/text handling. Thanks!
|
Thanks for the latest review. I merged current Verification:
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. |
|
Catch-up merge with Merged current The main motivation is CI: the previous run's only failure was Local verification on the merge:
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. |
…ips-uncommitted-import GLM refused prefix restore: a cold start gets its own MTP binding
| /// 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 { |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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).
| return placed.composited(over: canvas) | ||
| .normalized(mean: config.imageMeanTuple, std: config.imageStdTuple) | ||
| .asMLXArray() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
| 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)) |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
| let x = (block % tilesWide) * tileSize | ||
| let y = (block / tilesWide) * tileSize | ||
| let cropRect = CGRect(x: x, y: y, width: tileSize, height: tileSize) |
There was a problem hiding this comment.
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)
}
}There was a problem hiding this comment.
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.
| static public let unlimitedOCR6bit = ModelConfiguration( | ||
| id: "majentik/Unlimited-OCR-MLX-6bit", |
There was a problem hiding this comment.
This looks like a personal org in HF -- is there an official release?
There was a problem hiding this comment.
Yes, both entries now point at mlx-community: mlx-community/DeepSeek-OCR-5bit and mlx-community/Unlimited-OCR-6bit.
davidkoski
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
| 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 | ||
| } |
There was a problem hiding this comment.
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:
There was a problem hiding this comment.
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.
- 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>
53b39ef to
9931c80
Compare
|
Thanks for the review. This round rebases the branch onto current Commits, in review order
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, No code change, with measurements: the sRGB conversion and Verification on 9931c80
Your call
|
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.swiftis about 60 lines: two configuration aliases, the processor's.unlimitedfactory, and a
DeepseekOCRsubclass whose only override isnewCache(), returning aRingSlidingKVCacheinstead of the default. Reviewingthe 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
projector, and the DeepSeek-V2 MoE language decoder.
DeepseekOCRProcessorwith thegundam/basecrop modes as first-class API(
DeepseekOCRProcessor.Mode,modeContext(_:)/mode(from:)).DeepseekOCRSpecialTokens(id resolution, promptbuilders,
parseDetections(from:)).deepseekocrmodel type,DeepseekOCRProcessor/DeepseekVLV2Processorprocessor types.
refactored toward mlx-swift-lm patterns (
GlmOcr,DeepseekV3sanitize /@ModuleInfo).Attribution is in
ACKNOWLEDGMENTS.mdand in theDeepseekOCR.swiftheader.Unlimited-OCR
RingSlidingKVCache— Reference Sliding Window Attention (R-SWA). Prefill retains the fullprompt 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.unlimited_ocr/unlimited-ocrmodel types.basemode,max_num=32) on the shared processor.mlx-vlm.
RingSlidingKVCacheis not a substitute forRotatingKVCacheThey 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_length + window_size, new KV overwrites a ring of sizewindow_sizeropeOffsetkeeps increasingWhat 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_typeis honoured by default.BaseConfigurationreads it, andVLMModelFactorytries it first when its type registry knows that type, falling back tomodel_typeotherwise. Some Unlimited-OCR packs shipmodel_type: deepseekocrwith_orig_model_type: unlimited-ocras a shim for loaders that predate the Unlimitedregistration; 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:), defaultdefaultHonorOrigModelType = true); if youprefer, the default can be
falsewith the OCR call sites opting in.2.
RingSlidingKVCachein 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
.ringSlidingcase so it is treated as a model-defined window, and thetype registry registers it for prompt-cache save and load. No existing cache changes.
3.
SlidingWindowNoRepeatNGramProcessorin MLXLMCommon (opt-in). Ports mlx-vlm'srepetition guard for long OCR decodes. Nothing touches
GenerateParameters: the guard attachesper request via
GenerationComponents(logitProcessorFactory:)from #401.4.
MediaProcessing. The antialiased bicubic weights EmbeddingGemma 2 had privately movehere unchanged, since DeepSeek-OCR uses them too.
resampleBicubicandresampled(to:method:)gain a defaultedclampToExtent(off), which DeepSeek-OCR turns on; noother model's pixels change.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.
replies were drafted with Claude Code (Claude Opus); every commit carries a
Co-Authored-Byline.