Skip to content
Closed
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
87 changes: 78 additions & 9 deletions src/transformers/models/qwen3_vl/processing_qwen3_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,16 +124,23 @@ def __call__(
text = [text]

text = text.copy() # below lines change text in-place

# Optimization strategy: keep only 1 image_token as a placeholder, record the number of tokens needed at each position
# After tokenization, expand directly at the token_ids level to avoid processing extra-long strings
image_token_counts = [] # Record the number of tokens needed at each image_token position
if image_grid_thw is not None:
merge_length = self.image_processor.merge_size**2
index = 0
for i in range(len(text)):
while self.image_token in text[i]:
# Calculate how many image_tokens are in this text
count = text[i].count(self.image_token)
for _ in range(count):
num_image_tokens = image_grid_thw[index].prod() // merge_length
text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
image_token_counts.append(num_image_tokens)
index += 1
text[i] = text[i].replace("<|placeholder|>", self.image_token)
# Do not modify text, keep it as is (only 1 image_token at each position)

video_token_counts = [] # Record the number of tokens needed at each video_token position
if video_grid_thw is not None:
merge_length = self.video_processor.merge_size**2
index = 0
Expand All @@ -155,14 +162,19 @@ def __call__(
self.video_processor.temporal_patch_size,
)

video_placeholder = ""
# Optimization: use list concatenation, only 1 video_token per frame, record the number to be expanded
video_parts = []
frame_seqlen = video_grid_thw[index][1:].prod() // merge_length
for frame_idx in range(video_grid_thw[index][0]):
curr_time = curr_timestamp[frame_idx]
video_placeholder += f"<{curr_time:.1f} seconds>"
video_placeholder += (
self.vision_start_token + "<|placeholder|>" * frame_seqlen + self.vision_end_token
)
video_parts.append(f"<{curr_time:.1f} seconds>")
video_parts.append(self.vision_start_token)
video_parts.append(self.video_token) # Only use 1
video_parts.append(self.vision_end_token)
# Record the number to be expanded
video_token_counts.append(frame_seqlen)

video_placeholder = "".join(video_parts)
if f"{self.vision_start_token}{self.video_token}{self.vision_end_token}" in text[i]:
text[i] = text[i].replace(
f"{self.vision_start_token}{self.video_token}{self.vision_end_token}", video_placeholder, 1
Expand All @@ -172,13 +184,70 @@ def __call__(
text[i] = text[i].replace(self.video_token, video_placeholder, 1)
index += 1

text[i] = text[i].replace("<|placeholder|>", self.video_token)

return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])

# Expand image tokens (optimization: operate directly at token_ids level)
if image_grid_thw is not None and image_token_counts:
# Global image_token counter
global_token_count_idx = 0

# Iterate through each sample's input_ids
for batch_idx in range(len(text_inputs['input_ids'])):
input_ids = text_inputs['input_ids'][batch_idx]

# Find all image_token_id positions and expand
new_input_ids = []

for token_id in input_ids:
if token_id == self.image_token_id and global_token_count_idx < len(image_token_counts):
# Expand 1 image_token to N tokens
num_tokens = image_token_counts[global_token_count_idx]
new_input_ids.extend([self.image_token_id] * num_tokens)
global_token_count_idx += 1
else:
new_input_ids.append(token_id)

# Update input_ids
text_inputs['input_ids'][batch_idx] = new_input_ids

# Synchronously update attention_mask (if exists)
if 'attention_mask' in text_inputs:
text_inputs['attention_mask'][batch_idx] = [1] * len(new_input_ids)

# Expand video tokens (optimization: operate directly at token_ids level)
if video_grid_thw is not None and video_token_counts:
# Global video_token counter
global_video_token_idx = 0

# Iterate through each sample's input_ids
for batch_idx in range(len(text_inputs['input_ids'])):
input_ids = text_inputs['input_ids'][batch_idx]

# Find all video_token_id positions and expand
new_input_ids = []

for token_id in input_ids:
if token_id == self.video_token_id and global_video_token_idx < len(video_token_counts):
# Expand 1 video_token to N tokens
num_tokens = video_token_counts[global_video_token_idx]
new_input_ids.extend([self.video_token_id] * num_tokens)
global_video_token_idx += 1
else:
new_input_ids.append(token_id)
Comment on lines +233 to +240

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.

hmm, I wonder if Qwen-VL uses rust tokenizer backend, which is supposed to be super fast/optimized

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, I have already used it, but it's not very effective for multimodal inputs with large images. For example, large images might have around 6000 <image_pad>, which significantly slows down the tokenization process.

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.

hmm, and the wins are quite big as per your benchmarks. I see that the current code assumes bs==1 and thus no padding. Expanding manually is a bit more involved than the current code, we have been doing it manually in the past during model's forward and it has costed us several bugs/issues. The main issue is to take into account padding and pad tokens to the correct side when needed. Same applies for attention mask, we can't simply set all to 1

I'd like to hear what @itazap thinks. If we decide to expand those after tokenizing, it would need a utility (inside a tokenizer or processor) that any multimodal model can call

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@itazap could you please review this pr, thanks

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

thanks for working on this! Agreed that the performance wins are attractive.bs==1and no padding support does make me question the complexity of a tokenizers utility for this. I'm wondering if maybe we can do a hybrid approach where we use your post-tokenization expansion when bs==1 and padding=False. Interested to know if you think that would be useful @zucchini-nlp ? Also on having done it manually in the past - is the performance of this a common reported issue?

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.

is the performance of this a common reported issue?

no, this is the first issue mentioning it. I dont' think it causes more overhead than other parts of processing such as "image_processing". I agree that this is hard to implement with bs>1 unless tokenizers have a prebuilt utility for that. I don't think we want to keep the code if it's going to run only under bs==1, padding=False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

yes understood - I would say let's reconsider this for now as it would add maintenance overhead for a solution that covers only one case for now (being bs==1, padding=False). Happy to revisit this if it gets more demand from the community


# Update input_ids
text_inputs['input_ids'][batch_idx] = new_input_ids

# Synchronously update attention_mask (if exists)
if 'attention_mask' in text_inputs:
text_inputs['attention_mask'][batch_idx] = [1] * len(new_input_ids)



if return_mm_token_type_ids:
array_ids = np.array(text_inputs["input_ids"])
mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
Expand Down
Loading