Skip to content

Commit 8cb233b

Browse files
committed
Use chat template for Qwen 2 VL
1 parent 8cdc4a0 commit 8cb233b

File tree

9 files changed

+138
-89
lines changed

9 files changed

+138
-89
lines changed

Applications/VLMEval/ContentView.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,16 @@ class VLMEvaluator {
331331
MLXRandom.seed(UInt64(Date.timeIntervalSinceReferenceDate * 1000))
332332

333333
let result = try await modelContainer.perform { context in
334-
var userInput = UserInput(prompt: prompt, images: [.ciImage(image)])
334+
var userInput = UserInput(
335+
messages: [
336+
[
337+
"role": "user",
338+
"content": [
339+
["type": "text", "text": prompt],
340+
["type": "image"],
341+
],
342+
]
343+
], images: [.ciImage(image)])
335344
userInput.processing.resize = .init(width: 448, height: 448)
336345

337346
let input = try await context.processor.prepare(input: userInput)

Libraries/MLXLLM/LLMModelFactory.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ private struct LLMUserInputProcessor: UserInputProcessor {
230230
// but that is not public so just fall back to text
231231
let prompt = input.prompt
232232
.asMessages()
233-
.compactMap { $0["content"] }
233+
.compactMap { $0["content"] as? String }
234234
.joined(separator: ". ")
235235
let promptTokens = tokenizer.encode(text: prompt)
236236
return LMInput(tokens: MLXArray(promptTokens))

Libraries/MLXLMCommon/LanguageModel.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,13 @@ public struct LMInput {
6969
public struct ProcessedImage {
7070

7171
public let pixels: MLXArray
72-
public let imageGridThw: [THW]?
72+
public let frames: [THW]?
7373

7474
public init(
75-
pixels: MLXArray, imageGridThw: [THW]? = nil
75+
pixels: MLXArray, frames: [THW]? = nil
7676
) {
7777
self.pixels = pixels
78-
self.imageGridThw = imageGridThw
78+
self.frames = frames
7979
}
8080
}
8181

Libraries/MLXLMCommon/UserInput.swift

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ import CoreImage
44
import Foundation
55
import MLX
66

7+
public typealias Message = [String: any (Codable & Sendable)]
8+
79
/// Container for raw user input.
810
///
911
/// A ``UserInputProcessor`` can convert this to ``LMInput``.
1012
/// See also ``ModelContext``.
1113
public struct UserInput: Sendable {
12-
1314
/// Representation of a prompt or series of messages (conversation).
1415
public enum Prompt: Sendable, CustomStringConvertible {
1516
case text(String)
16-
case messages([[String: String]])
17+
case messages([Message])
1718

18-
public func asMessages() -> [[String: String]] {
19+
public func asMessages() -> [Message] {
1920
switch self {
2021
case .text(let text):
2122
return [["role": "user", "content": text]]
@@ -116,7 +117,7 @@ public struct UserInput: Sendable {
116117
self.images = images
117118
}
118119

119-
public init(messages: [[String: String]], images: [Image] = [Image]()) {
120+
public init(messages: [Message], images: [Image] = [Image]()) {
120121
self.prompt = .messages(messages)
121122
self.images = images
122123
}

Libraries/MLXVLM/Models/Idefics3.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,7 @@ public class Idefics3Processor: UserInputProcessor {
805805
}
806806

807807
public func prepare(input: UserInput) throws -> LMInput {
808-
let prompt = input.prompt.asMessages().last?["content"] ?? ""
808+
let prompt = input.prompt.asMessages().last?["content"] as? String ?? ""
809809

810810
if input.images.isEmpty {
811811
// No image scenario

Libraries/MLXVLM/Models/Paligemma.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ public class PaligGemmaProcessor: UserInputProcessor {
478478
}
479479

480480
// this doesn't have a chat template so just use the last message.
481-
var prompt = input.prompt.asMessages().last?["content"] ?? ""
481+
var prompt = input.prompt.asMessages().last?["content"] as? String ?? ""
482482

483483
// based on transformers/processing_paligemma
484484
let count = input.images.count * config.imageSequenceLength

Libraries/MLXVLM/Models/Qwen2VL.swift

Lines changed: 84 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -367,10 +367,10 @@ private enum Vision {
367367
}
368368

369369
public func callAsFunction(
370-
_ x: MLXArray, gridThw: [THW], rotaryPositionEmbedding: MLXArray
370+
_ x: MLXArray, frames: [THW], rotaryPositionEmbedding: MLXArray
371371
) -> MLXArray {
372372
let sequenceLength = x.dim(0)
373-
let B = gridThw[0].t
373+
let B = frames[0].t
374374
let L = sequenceLength / B
375375

376376
let qkv = qkv(x)
@@ -435,13 +435,13 @@ private enum Vision {
435435
}
436436

437437
func callAsFunction(
438-
_ hiddenStates: MLXArray, gridThw: [THW], rotaryPositionEmbedding: MLXArray
438+
_ hiddenStates: MLXArray, frames: [THW], rotaryPositionEmbedding: MLXArray
439439
) -> MLXArray {
440440
var hiddenStates =
441441
hiddenStates
442442
+ attention(
443443
norm1(hiddenStates),
444-
gridThw: gridThw,
444+
frames: frames,
445445
rotaryPositionEmbedding: rotaryPositionEmbedding
446446
)
447447
hiddenStates = hiddenStates + mlp(norm2(hiddenStates))
@@ -479,10 +479,10 @@ private enum Vision {
479479
spatialMergeSize: 2)
480480
}
481481

482-
func rotaryPositionEmbedding(_ gridThw: [THW]) -> MLXArray {
482+
func rotaryPositionEmbedding(_ frames: [THW]) -> MLXArray {
483483
var positionIds = [MLXArray]()
484484

485-
for row in gridThw {
485+
for row in frames {
486486
let (t, h, w) = row.values
487487

488488
var hposIds = expandedDimensions(MLXArray(0 ..< h), axis: 1)
@@ -516,22 +516,22 @@ private enum Vision {
516516
}
517517

518518
let indices = concatenated(positionIds, axis: 0)
519-
let maxGridSize = gridThw.lazy.map { max($0.h, $0.w) }.max() ?? 0
520-
let rotaryPositionEmbedFull = rotaryPositionEmbedding(sequenceLength: maxGridSize)[
519+
let maxFrameSize = frames.lazy.map { max($0.h, $0.w) }.max() ?? 0
520+
let rotaryPositionEmbedFull = rotaryPositionEmbedding(sequenceLength: maxFrameSize)[
521521
indices]
522522

523523
return rotaryPositionEmbedFull.reshaped(indices.dim(0), -1)
524524
}
525525

526-
public func callAsFunction(_ hiddenStates: MLXArray, gridThw: [THW]) -> MLXArray {
526+
public func callAsFunction(_ hiddenStates: MLXArray, frames: [THW]) -> MLXArray {
527527
var hiddenStates = patchEmbed(hiddenStates)
528-
let rotaryPositionEmbedding = rotaryPositionEmbedding(gridThw)
528+
let rotaryPositionEmbedding = rotaryPositionEmbedding(frames)
529529

530-
let batchSize = gridThw.count
530+
let batchSize = frames.count
531531

532532
for block in blocks {
533533
hiddenStates = block(
534-
hiddenStates, gridThw: gridThw,
534+
hiddenStates, frames: frames,
535535
rotaryPositionEmbedding: rotaryPositionEmbedding)
536536
}
537537

@@ -585,6 +585,10 @@ private enum Vision {
585585
/// This is meant to be used with ``Qwen2VL`` and is typically created by ``VLMModelFactory``.
586586
public class Qwen2VLProcessor: UserInputProcessor {
587587

588+
enum Qwen2VLProcessorError: Error {
589+
case framesIsNil
590+
}
591+
588592
private let config: Qwen2VLProcessorConfiguration
589593
private let tokenizer: any Tokenizer
590594

@@ -686,72 +690,87 @@ public class Qwen2VLProcessor: UserInputProcessor {
686690
return (flattenedPatches, .init(gridT, gridH, gridW))
687691
}
688692

689-
public func prepare(prompt: UserInput.Prompt, imageTHW: [THW]?) -> String {
690-
// the tokenizer does have a chat template and it expects messages
691-
// like this:
692-
//
693-
// [{'role': 'user', 'content': [{'type': 'text', 'text': 'What are these?'},
694-
// {'type': 'image'}, {'type': 'image'}, {'type': 'image'}]}]
695-
//
696-
// The output of the prompt template is fed into
697-
// image_processing_qwen2_vl.preprocess where it is further augmented
698-
// by replacing tokens according to imageTHW.
699-
//
700-
// Neither the structured content nor the postprocessing of the template
701-
// are supported in current Tokenizer/Jinja (swift) so handle that here.
702-
703-
var messages = prompt.asMessages()
704-
if messages[0]["role"] != "system" {
693+
private func prepareMessages(_ messages: [Message]) -> [Message] {
694+
var messages = messages
695+
print(messages)
696+
// Add system message if not present
697+
if let role = messages[0]["role"] as? String, role != "system" {
705698
messages.insert(["role": "system", "content": "You are a helpful assistant."], at: 0)
706699
}
707700

708-
let lastIndex = messages.count - 1
709-
var lastMessage = messages[lastIndex]["content"] ?? ""
710-
711-
// image_processing_qwen2_vl.preprocess -- inject image_pad tokens for each image
712-
let mergeLength = config.mergeSize * config.mergeSize
713-
for thw in imageTHW ?? [] {
714-
lastMessage += "<|vision_start|>"
715-
lastMessage += Array(repeating: "<|image_pad|>", count: thw.product / mergeLength)
716-
.joined()
717-
lastMessage += "<|vision_end|>"
718-
}
719-
720-
messages[lastIndex]["content"] = lastMessage
721-
722-
return
723-
messages
724-
.map {
725-
"<|im_start|>\($0["role"] ?? "user")\n\($0["content"] ?? "")<|im_end|>"
726-
}
727-
.joined(separator: "\n")
728-
+ "\n<|im_start|>assistant\n"
701+
return messages
729702
}
730703

704+
// public func prepare(prompt: UserInput.Prompt, frames: [THW]?) throws -> String {
705+
// let messages = prepareMessages(prompt.asMessages())
706+
// let tokens = try tokenizer.applyChatTemplate(messages: messages)
707+
// return tokenizer.decode(tokens: tokens)
708+
// }
709+
731710
public func prepare(input: UserInput) throws -> LMInput {
711+
// Text-only input
732712
if input.images.isEmpty {
733-
// just a straight text prompt
734-
let prompt = prepare(prompt: input.prompt, imageTHW: nil)
735-
let promptTokens = try tokenizer.encode(text: prompt)
713+
let messages = input.prompt.asMessages()
714+
let promptTokens = try tokenizer.applyChatTemplate(messages: messages)
736715
return LMInput(tokens: MLXArray(promptTokens))
737716
}
738717

739-
// image_processing_qwen2_vl.preprocess
740-
let images = try input.images.map {
718+
// Input with images
719+
let pixelsAndFrames = try input.images.map {
741720
try preprocess(images: [$0.asCIImage()], processing: input.processing)
742721
}
743-
let pixels = concatenated(images.map { $0.0 })
744-
let image = LMInput.ProcessedImage(pixels: pixels, imageGridThw: images.map { $0.1 })
722+
let pixelsConcatenated = concatenated(pixelsAndFrames.map { $0.0 })
723+
724+
// Are the images concatenated here because they're frames of a video? How should we handle the case where multiple images are included in a multi-turn chat?
725+
let image = LMInput.ProcessedImage(
726+
pixels: pixelsConcatenated, frames: pixelsAndFrames.map { $0.1 })
727+
728+
// Get tokens from messages
729+
let messages = prepareMessages(input.prompt.asMessages())
730+
var promptTokens = try tokenizer.applyChatTemplate(messages: messages)
731+
732+
// Replace single image pad token with correct number for each image
733+
let mergeLength = config.mergeSize * config.mergeSize
734+
735+
let imagePlaceholderTokens = try tokenizer.encode(
736+
text: "<|vision_start|><|image_pad|><|vision_end|>")
737+
738+
guard let frames = image.frames else {
739+
throw Qwen2VLProcessorError.framesIsNil
740+
}
741+
for thw in frames {
742+
if let padIndex = findSubsequence(promptTokens, imagePlaceholderTokens) {
743+
let paddingCount = thw.product / mergeLength
744+
promptTokens.replaceSubrange(
745+
padIndex ..< (padIndex + imagePlaceholderTokens.count),
746+
with: try tokenizer.encode(
747+
text:
748+
"<|vision_start|>\(Array(repeating: "<|image_pad|>", count: paddingCount).joined())<|vision_end|>"
749+
)
750+
)
751+
}
752+
}
753+
754+
let promptTokensDecoded = try tokenizer.decode(tokens: promptTokens)
755+
756+
print(promptTokensDecoded)
745757

746-
// processing_qwen2_vl.Qwen2VLProcessor
747-
let prompt = prepare(prompt: input.prompt, imageTHW: image.imageGridThw)
748-
let promptTokens = try tokenizer.encode(text: prompt)
749758
let promptArray = MLXArray(promptTokens).expandedDimensions(axis: 0)
750759
let mask = ones(like: promptArray).asType(.int8)
751-
752760
return LMInput(text: .init(tokens: promptArray, mask: mask), image: image)
753761
}
754762

763+
private func findSubsequence(_ array: [Int], _ subsequence: [Int]) -> Int? {
764+
guard subsequence.count <= array.count else { return nil }
765+
766+
for i in 0 ... (array.count - subsequence.count) {
767+
if Array(array[i ..< (i + subsequence.count)]) == subsequence {
768+
return i
769+
}
770+
}
771+
return nil
772+
}
773+
755774
}
756775

757776
// MARK: - Model
@@ -779,18 +798,18 @@ public class Qwen2VL: Module, VLMModel, KVCacheDimensionProvider {
779798
self._languageModel.wrappedValue = Language.LanguageModel(config.textConfiguration)
780799
}
781800

782-
private func inputEmbeddings(inputIds: MLXArray, pixelValues: MLXArray?, gridThw: [THW]?)
801+
private func inputEmbeddings(inputIds: MLXArray, pixelValues: MLXArray?, frames: [THW]?)
783802
-> MLXArray
784803
{
785-
guard let pixelValues, let gridThw else {
804+
guard let pixelValues, let frames else {
786805
return languageModel(inputIds).logits
787806
}
788807

789808
// Get the input embeddings from the language model
790809
let inputEmbeds = languageModel.model.embedTokens(inputIds)
791810

792811
// Get the ouptut hidden states from the vision model
793-
var hiddenStates = self.visionModel(pixelValues, gridThw: gridThw)
812+
var hiddenStates = self.visionModel(pixelValues, frames: frames)
794813

795814
if hiddenStates.ndim == 2 {
796815
hiddenStates = hiddenStates[.newAxis, 0..., 0...]
@@ -820,13 +839,13 @@ public class Qwen2VL: Module, VLMModel, KVCacheDimensionProvider {
820839
public func prepare(_ input: LMInput, cache: [any KVCache], windowSize: Int?) throws
821840
-> PrepareResult
822841
{
823-
let gridThw = input.image?.imageGridThw
842+
let frames = input.image?.frames
824843

825844
let dtype = visionModel.patchEmbed.proj.weight.dtype
826845
let pixels = input.image?.pixels.asType(dtype)
827846

828847
let inputEmbeddings = self.inputEmbeddings(
829-
inputIds: input.text.tokens, pixelValues: pixels, gridThw: gridThw)
848+
inputIds: input.text.tokens, pixelValues: pixels, frames: frames)
830849

831850
let result = languageModel(nil, cache: cache, inputEmbedding: inputEmbeddings)
832851

Package.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ let package = Package(
2828
],
2929
dependencies: [
3030
.package(url: "https://github.com/ml-explore/mlx-swift", from: "0.21.2"),
31-
.package(url: "https://github.com/huggingface/swift-transformers", from: "0.1.13"),
31+
// .package(url: "https://github.com/huggingface/swift-transformers", from: "0.1.13"),
32+
.package(
33+
url: "https://github.com/DePasqualeOrg/swift-transformers", branch: "images-and-tools"),
3234
.package(url: "https://github.com/1024jp/GzipSwift", "6.0.1" ... "6.0.1"),
3335
.package(url: "https://github.com/apple/swift-async-algorithms", from: "1.0.0"),
3436
],

0 commit comments

Comments
 (0)