verl icon indicating copy to clipboard operation
verl copied to clipboard

ValueError: Image features and image tokens do not match: tokens: XXX, features YYY

Open nn-wang opened this issue 1 year ago • 21 comments

System Info

----------Python Info---------- Version : 3.10.18 Compiler : GCC 11.2.0 Build : ('main', 'Jun 5 2025 13:14:17') Arch : ('64bit', 'ELF') ------------Pip Info----------- Version : 25.2 Directory : /home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/pip vllm : 0.8.5.post1 sglang : 0.4.10.post2 ray : 2.49.1 torch : 2.7.1 ----------verl Info----------- Version : 0.5.0.dev Directory : /data/wangnn/repos/verl/verl Commit Hash : a1542172d5077ca59c99ecd1e3adc3223eaadbbd ----------Platform Info---------- Platform : Linux-5.15.0-105-generic-x86_64-with-glibc2.35 system : Linux node : user release : 5.15.0-105-generic version : #115-Ubuntu SMP Mon Apr 15 09:52:04 UTC 2024 ----------Environment---------- CUDA Runtime : 12.6

Information

  • [x] The official example scripts
  • [ ] My own modified scripts

Tasks

  • [x] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [ ] My own task or dataset (give details below)

Reproduction

File "/data/wangnn/repos/verl/verl/utils/profiler/performance.py", line 118, in log
output = func(*args, **kwargs)
File "/data/wangnn/repos/verl/verl/workers/actor/dp_actor.py", line 397, in compute_log_prob
entropy, log_probs = self._forward_micro_batch(
File "/data/wangnn/repos/verl/verl/workers/actor/dp_actor.py", line 236, in _forward_micro_batch
raise e
File "/data/wangnn/repos/verl/verl/workers/actor/dp_actor.py", line 180, in _forward_micro_batch
output = self.actor_module(
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1857, in _call_impl
return inner()
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1805, in inner
result = forward_call(*args, **kwargs)
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/transformers/utils/generic.py", line 961, in wrapper
output = func(self, *args, **kwargs)
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py", line 1482, in forward
outputs = self.model(
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
return forward_call(*args, **kwargs)
File "/home/wangnn/anaconda3/envs/verl/lib/python3.10/site-packages/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py", line 1250, in forward
raise ValueError(
ValueError: Image features and image tokens do not match: tokens: 79752, features 80436

Expected behavior

Image tokens == image feature

nn-wang avatar Sep 14 '25 03:09 nn-wang

(WorkerDict pid=1910872) ==================================================
(WorkerDict pid=1910872) Caught a ValueError! Let's debug...
(WorkerDict pid=1910872) Original error message: Image features and image tokens do not match: tokens: 79752, features 80436
(WorkerDict pid=1910872) --------------------
(WorkerDict pid=1910872) ### Shape Information ###
(WorkerDict pid=1910872) Shape of input_ids_rmpad: torch.Size([1, 170574])
(WorkerDict pid=1910872) Shape of position_ids_rmpad: torch.Size([3, 1, 170574])
(WorkerDict pid=1910872)
(WorkerDict pid=1910872) ### Multi-Modal Inputs Details ###
(WorkerDict pid=1910872) Keys in multi_modal_inputs: dict_keys(['pixel_values', 'image_grid_thw'])
(WorkerDict pid=1910872) Shape of 'pixel_values': torch.Size([319008, 1176])
(WorkerDict pid=1910872) Number of image features detected from shape: 1176
(WorkerDict pid=1910872) image_grid_thw: tensor([[ 1, 36, 24],
(WorkerDict pid=1910872) [ 1, 30, 18],
(WorkerDict pid=1910872) [ 1, 36, 24],
(WorkerDict pid=1910872) ...,
(WorkerDict pid=1910872) [ 1, 16, 36],
(WorkerDict pid=1910872) [ 1, 22, 36],
(WorkerDict pid=1910872) [ 1, 12, 18]])
(WorkerDict pid=1910872) len of image_grid_thw: torch.Size([506, 3])
(WorkerDict pid=1910872) total_patches:321744

打印了一些信息,大致认为321744 = 80436 4 319008 =797524

nn-wang avatar Sep 14 '25 03:09 nn-wang

Check if the token sequence reaches its maximum length and is truncated. Can you provide some more details, such as running scripts, datasets, etc.

Maxwell-Jia avatar Sep 14 '25 07:09 Maxwell-Jia

@Maxwell-Jia ,thank you , Why is my max_prompt_len set to 1024, yet prompt_max always gets truncated at 559?

Image

nn-wang avatar Sep 15 '25 13:09 nn-wang

@Maxwell-Jia ,I'm conducting multi-round RL training with interaction included.

nn-wang avatar Sep 15 '25 13:09 nn-wang

  1. Adjust data.max_prompt_length: The simplest method for debugging, though potentially less efficient for training, is to increase the value of data.max_prompt_length until no samples are filtered out. Alternatively, you could manually remove the oversized samples from your dataset, which might allow you to use a lower max_prompt_length. (Note: I haven't personally tested the latter method).

    • For more details, please refer to this comment: https://github.com/hiyouga/LLaMA-Factory/issues/6559#issuecomment-2678469573
  2. Replace tokenizer.json: If the issue persists after trying the above, consider replacing your model's tokenizer.json with the one from the base model. This is especially relevant if you are working with a fine-tuned model.

    • See this comment for guidance: https://github.com/hiyouga/LLaMA-Factory/issues/6911#issuecomment-2655659562

Hope this helps resolve your problem.

Leon-LihongWang avatar Sep 17 '25 07:09 Leon-LihongWang

@Juvenilecris have you found how to solve this?

yxh-y avatar Sep 29 '25 01:09 yxh-y

@yxh-y @Juvenilecris I encountered this problem, and found my side of issue was kind of stupid: I forgot to put <image> in some of my prompts that have images passed in. Not sure if this is helpful, but it won't hurt to check this.

ziqipang avatar Oct 21 '25 00:10 ziqipang

I’m encountering the same issue.

It reports: “ValueError: Image features and image tokens do not match: tokens: 4, features: 1358.”

However, the error only appears after several epochs, which is quite strange.

ppalantir avatar Dec 17 '25 02:12 ppalantir

I'm also encountering the same issue with Qwen3-VL, and I've double-checked the dataset, and also ran with data.truncation = "error" (so the issue should not be with the input_ids being truncated).

pruksmhc avatar Jan 08 '26 00:01 pruksmhc

ValueError: Image features and image tokens do not match: tokens: 100262, features 100261

I'm also encountering the same issue with Qwen3-VL, and I've double-checked the dataset, and also ran with data.truncation = "error" (so the issue should not be with the input_ids being truncated).

Hi, I encouter the same problem, did you solve it?

Zzoay avatar Jan 14 '26 09:01 Zzoay

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

taoxj2001 avatar Jan 14 '26 14:01 taoxj2001

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

LinjieMu avatar Feb 08 '26 23:02 LinjieMu

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

Same problem. Always 1 greater than features. Any solution please?

volcverse avatar Feb 19 '26 16:02 volcverse

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

Same problem. Always 1 greater than features. Any solution please?

Since it only differs by one token each time, I personally believe this token won't lead to any catastrophic consequences. Therefore, I implemented an automatic truncation/padding logic in qwen3_vl.py.

        if n_image_tokens != n_image_features:
            logger.warning(
                f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}. "
                f"Auto-aligning (pad/truncate) to avoid crash."
            )
            if n_image_features < n_image_tokens:
                # Pad image_embeds with zeros to match token count
                pad_size = n_image_tokens - n_image_features
                pad_embeds = torch.zeros(pad_size, image_embeds.shape[1], dtype=image_embeds.dtype, device=image_embeds.device)
                image_embeds = torch.cat([image_embeds, pad_embeds], dim=0)
                if deepstack_image_embeds is not None:
                    deepstack_image_embeds = [
                        torch.cat([emb, torch.zeros(pad_size, emb.shape[1], dtype=emb.dtype, device=emb.device)], dim=0)
                        for emb in deepstack_image_embeds
                    ]
            else:
                # Truncate image_embeds to match token count
                image_embeds = image_embeds[:n_image_tokens]
                if deepstack_image_embeds is not None:
                    deepstack_image_embeds = [emb[:n_image_tokens] for emb in deepstack_image_embeds]

volcverse avatar Feb 20 '26 03:02 volcverse

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

Same problem. Always 1 greater than features. Any solution please?

Since it only differs by one token each time, I personally believe this token won't lead to any catastrophic consequences. Therefore, I implemented an automatic truncation/padding logic in qwen3_vl.py.

    if n_image_tokens != n_image_features:
        logger.warning(
            f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}. "
            f"Auto-aligning (pad/truncate) to avoid crash."
        )
        if n_image_features < n_image_tokens:
            # Pad image_embeds with zeros to match token count
            pad_size = n_image_tokens - n_image_features
            pad_embeds = torch.zeros(pad_size, image_embeds.shape[1], dtype=image_embeds.dtype, device=image_embeds.device)
            image_embeds = torch.cat([image_embeds, pad_embeds], dim=0)
            if deepstack_image_embeds is not None:
                deepstack_image_embeds = [
                    torch.cat([emb, torch.zeros(pad_size, emb.shape[1], dtype=emb.dtype, device=emb.device)], dim=0)
                    for emb in deepstack_image_embeds
                ]
        else:
            # Truncate image_embeds to match token count
            image_embeds = image_embeds[:n_image_tokens]
            if deepstack_image_embeds is not None:
                deepstack_image_embeds = [emb[:n_image_tokens] for emb in deepstack_image_embeds]

This issue bothered me for a long time. Finally this solution worked! Thanks for sharing!

applenob avatar Feb 20 '26 18:02 applenob

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

Same problem. Always 1 greater than features. Any solution please?

Hi, I encountered the same issue, and I found the reason: the Qwen3-VL-8B generates the special token <|im_pad|> in the response. So it only differs by one token each time.

zhangchbin avatar Mar 07 '26 08:03 zhangchbin

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640同样的问题 ValueError:图像特征和图像标记不匹配:标记数:2641,特征 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?你好,我在 0.7.0.dev 版中也遇到了同样的问题。代币数量比功能多**一 **。你解开了吗?

Same problem. Always 1 greater than features. Any solution please?同样的问题。总是比功能更强。有什么解决办法吗?

Hi, I encountered the same issue, and I found the reason: the Qwen3-VL-8B generates the special token <|im_pad|> in the response. So it only differs by one token each time.你好,我也遇到了同样的问题,并且找到了原因:Qwen3-VL-8B 在响应中生成了特殊的令牌 <|im_pad|>。所以每次都只差一个符号。

So how did you solve this problem?

FangdongWang avatar Apr 01 '26 02:04 FangdongWang

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640同样的问题 ValueError:图像特征和图像标记不匹配:标记数:2641,特征 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?你好,我在 0.7.0.dev 版中也遇到了同样的问题。代币数量比功能多**一 **。你解开了吗?

Same problem. Always 1 greater than features. Any solution please?同样的问题。总是比功能更强。有什么解决办法吗?

Hi, I encountered the same issue, and I found the reason: the Qwen3-VL-8B generates the special token <|im_pad|> in the response. So it only differs by one token each time.你好,我也遇到了同样的问题,并且找到了原因:Qwen3-VL-8B 在响应中生成了特殊的令牌 <|im_pad|>。所以每次都只差一个符号。

So how did you solve this problem?

add " actor_rollout_ref.actor.fsdp_config.fsdp_size=8 "

Cass998 avatar Jun 02 '26 03:06 Cass998

same problem ValueError: Image features and image tokens do not match: tokens: 2641, features 2640

Hi, I encouter the same problem in version 0.7.0.dev. The number of tokens is one greater than features. Did you solve it?

Same problem. Always 1 greater than features. Any solution please?

Since it only differs by one token each time, I personally believe this token won't lead to any catastrophic consequences. Therefore, I implemented an automatic truncation/padding logic in qwen3_vl.py.

    if n_image_tokens != n_image_features:
        logger.warning(
            f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}. "
            f"Auto-aligning (pad/truncate) to avoid crash."
        )
        if n_image_features < n_image_tokens:
            # Pad image_embeds with zeros to match token count
            pad_size = n_image_tokens - n_image_features
            pad_embeds = torch.zeros(pad_size, image_embeds.shape[1], dtype=image_embeds.dtype, device=image_embeds.device)
            image_embeds = torch.cat([image_embeds, pad_embeds], dim=0)
            if deepstack_image_embeds is not None:
                deepstack_image_embeds = [
                    torch.cat([emb, torch.zeros(pad_size, emb.shape[1], dtype=emb.dtype, device=emb.device)], dim=0)
                    for emb in deepstack_image_embeds
                ]
        else:
            # Truncate image_embeds to match token count
            image_embeds = image_embeds[:n_image_tokens]
            if deepstack_image_embeds is not None:
                deepstack_image_embeds = [emb[:n_image_tokens] for emb in deepstack_image_embeds]

This issue bothered me for a long time. Finally this solution worked! Thanks for sharing!

This patch caused all critic scores to zero in a multi-node training. The issue was resolved by setting actor_rollout_ref.actor.fsdp_config.fsdp_size=8.

Cass998 avatar Jun 02 '26 03:06 Cass998

@Cass998 I suggest increasing max prompt length and max response length.

nn-wang avatar Jun 02 '26 03:06 nn-wang