Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions Libraries/MLXVLM/Models/FastVLM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -992,9 +992,8 @@ public struct FastVLMProcessor: UserInputProcessor {
let promptTokens = try tokenizer.applyChatTemplate(
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)
let tokensArray = MLXArray(promptTokens).expandedDimensions(axis: 0)
let mask = ones(like: tokensArray)
return LMInput(text: .init(tokens: tokensArray, mask: mask), image: nil)
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
}

guard input.images.count == 1 else {
Expand Down Expand Up @@ -1189,8 +1188,10 @@ public class FastVLM: Module, VLMModel, KVCacheDimensionProvider {
) throws
-> PrepareResult
{
var tokens = input.text.tokens
if tokens.ndim == 1 { tokens = tokens.expandedDimensions(axis: 0) }
let embeddings = try getInputEmbeddings(
inputIds: input.text.tokens,
inputIds: tokens,
pixelValues: input.image?.pixels,
mask: input.text.mask
)
Expand Down
5 changes: 5 additions & 0 deletions Libraries/MLXVLM/Models/Gemma3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,11 @@ public struct Gemma3Processor: UserInputProcessor {
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)

if input.images.isEmpty {
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
}

// Process images if any
var processedImage: LMInput.ProcessedImage?

Expand Down
10 changes: 10 additions & 0 deletions Libraries/MLXVLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2193,6 +2193,11 @@ public struct Gemma4Processor: UserInputProcessor {
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)

if input.images.isEmpty, input.videos.isEmpty {
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
}

var processedImage: LMInput.ProcessedImage?
if !input.images.isEmpty {
let imagePixelsAndFrames = try input.images.map {
Expand Down Expand Up @@ -2758,6 +2763,11 @@ public struct Gemma4UnifiedProcessor: UserInputProcessor {
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)

if input.images.isEmpty {
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
}

var processedImage: LMInput.ProcessedImage?
if !input.images.isEmpty {
let imageData = try preprocess(
Expand Down
3 changes: 2 additions & 1 deletion Libraries/MLXVLM/Models/Idefics3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,8 @@ public class Idefics3: Module, VLMModel, KVCacheDimensionProvider {
) throws
-> PrepareResult
{
let inputIds = input.text.tokens
var inputIds = input.text.tokens
if inputIds.ndim == 1 { inputIds = inputIds.expandedDimensions(axis: 0) }
let pixelValues = input.image?.pixels
let embeddings = getInputEmbeddings(
inputIds: inputIds,
Expand Down
22 changes: 8 additions & 14 deletions Libraries/MLXVLM/Models/Mistral3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -479,12 +479,8 @@ private enum Language {

var swaMask: MLXFast.ScaledDotProductAttentionMaskMode = .none
if let swaIndex, let slidingWindow, !cache.isEmpty {
let t = h.dim(1)
if t > 1 {
let swaOffset = min(slidingWindow, cache[swaIndex].offset)
swaMask = .array(
createCausalMask(n: t, offset: swaOffset, windowSize: slidingWindow))
}
swaMask = createAttentionMask(
h: h, cache: cache[swaIndex], windowSize: slidingWindow)
}

let beta = config.ropeParameters?["llama_4_scaling_beta"]?.asFloat() ?? 0.0
Expand Down Expand Up @@ -723,7 +719,8 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider {
) throws
-> PrepareResult
{
let inputIds = input.text.tokens
var inputIds = input.text.tokens
if inputIds.ndim == 1 { inputIds = inputIds.expandedDimensions(axis: 0) }
let pixelValues = input.image?.pixels

// Extract image sizes from frames or fall back to config defaults
Expand All @@ -742,18 +739,16 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider {
imageSizes: imageSizes
)

var tokens = inputIds
if tokens.ndim == 1 { tokens = tokens.expandedDimensions(axis: 0) }
let totalPositions = embeddings.dim(1)
let processed = try prefill.forEachChunk(total: totalPositions) { range in
_ = languageModel(
tokens[0..., range], cache: cache,
inputIds[0..., range], cache: cache,
inputsEmbeds: embeddings[0..., range, 0...])
asyncEval(cache)
}
if processed > 0 { eval(cache) }
let logits = languageModel(
tokens[0..., processed...], cache: cache,
inputIds[0..., processed...], cache: cache,
inputsEmbeds: embeddings[0..., processed..., 0...])
prefill.progress?(totalPositions, totalPositions)
return .logits(.init(logits: logits))
Expand Down Expand Up @@ -1022,9 +1017,8 @@ public struct Mistral3VLMProcessor: UserInputProcessor {
tools: input.tools,
additionalContext: input.additionalContext
)
let tokensArray = MLXArray(promptTokens).expandedDimensions(axis: 0)
let mask = ones(like: tokensArray)
return LMInput(text: .init(tokens: tokensArray, mask: mask), image: nil)
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
Comment on lines -1025 to +1021

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.

Mistral3, FastVLM and SmolVLM2 don't handle 1-D

    @Test
    func mistral3DropAttentionTest() throws {
        // e.g. in VLMImageTokenMismatchTests -- not the right place for it,
        // but it builds the model we want
        let model = try Self.makeTinyMistral3()
        
        let cache = try model.newCache(parameters: nil)
        
        // Turn 1: the processor's [1, L] prompt
        
        _ = try model.prepare(
            LMInput(tokens: MLXArray([Int32(1), 2, 3, 4]).expandedDimensions(axis: 0)),
            cache: cache, state: nil, prefill: .init(stepSize: 512))
        
        // Turn 2: 1-D
        //    case .appendSuffix(let suffixStart, _):
        //        input = LMInput(
        //            tokens: MLXArray(Array(promptTokenIds[suffixStart...])))

        _ = try model.prepare(
            LMInput(tokens: MLXArray([Int32(5), 6, 7])),
            cache: cache, state: nil, prefill: .init(stepSize: 512))
    }

these models assume a [1, L] input always. I think it is sufficient to expand dimensions if ndim is 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, I did not think about. Also fixed a Ministral warm-cache mask mismatch using the existing cache-aware helper, see update

}

guard input.images.count == 1 else {
Expand Down
5 changes: 2 additions & 3 deletions Libraries/MLXVLM/Models/SmolVLM2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,8 @@ public struct SmolVLMProcessor: UserInputProcessor {
let promptTokens = try tokenizer.applyChatTemplate(
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)
let tokensArray = MLXArray(promptTokens).expandedDimensions(axis: 0)
let mask = ones(like: tokensArray)
return LMInput(text: .init(tokens: tokensArray, mask: mask), image: nil)
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))
} else if input.images.count > 0 && input.videos.isEmpty {
// Single image scenario
guard input.images.count == 1 else {
Expand Down
Loading
Loading