Skip to content

The bug encountered when running the official fine-tuning example code for Qwen 2-VL. #2031

Closed

Description

@1804696177

`from unsloth import FastVisionModel,is_bf16_supported # FastLanguageModel for LLMs
import torch
from datasets import load_dataset
from unsloth.trainer import UnslothVisionDataCollator
from trl import SFTTrainer, SFTConfig

model, tokenizer = FastVisionModel.from_pretrained(
"/home/extra1T/xxx/projects/Qwen/unsloth_qwen_vl/unsloth/Qwen2-VL-2B",
load_in_4bit = True, # Use 4bit to reduce memory use. False for 16bit LoRA.
use_gradient_checkpointing = "unsloth", # True or "unsloth" for long context
)
model = FastVisionModel.get_peft_model(
model,
finetune_vision_layers = True, # False if not finetuning vision layers
finetune_language_layers = True, # False if not finetuning language layers
finetune_attention_modules = True, # False if not finetuning attention layers
finetune_mlp_modules = True, # False if not finetuning MLP layers

r = 16,           # The larger, the higher the accuracy, but might overfit
lora_alpha = 16,  # Recommended alpha == r at least
lora_dropout = 0,
bias = "none",
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = False,  # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
# target_modules = "all-linear", # Optional now! Can specify a list if needed

)

dataset = load_dataset("/home/extra1T/xxx/projects/Qwen/unsloth_qwen_vl/unsloth___la_te_x_ocr", split = "train",cache_dir='./')
instruction = "Write the LaTeX representation for this image."
def convert_to_conversation(sample):
conversation = [
{ "role": "user",
"content" : [
{"type" : "text", "text" : instruction},
{"type" : "image", "image" : sample["image"]} ]
},
{ "role" : "assistant",
"content" : [
{"type" : "text", "text" : sample["text"]} ]
},
]
return { "messages" : conversation }
converted_dataset = [convert_to_conversation(sample) for sample in dataset]
FastVisionModel.for_training(model)
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
data_collator = UnslothVisionDataCollator(model, tokenizer), # Must use!
train_dataset = converted_dataset,
args = SFTConfig(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 5,
max_steps = 30,
# num_train_epochs = 1, # Set this instead of max_steps for full training runs
learning_rate = 2e-4,
fp16 = not is_bf16_supported(),
bf16 = is_bf16_supported(),
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "none", # For Weights and Biases

    # You MUST put the below items for vision finetuning:
    remove_unused_columns = False,
    dataset_text_field = "",
    dataset_kwargs = {"skip_prepare_dataset": True},
    dataset_num_proc = 4,
    max_seq_length = 2048,
),

)
trainer_stats = trainer.train()
model.save_pretrained("lora_model") # Local saving
tokenizer.save_pretrained("lora_model")
File "/home/extra1T/xxx/projects/Qwen/unsloth_qwen_vl/train.py", line 79, in
trainer_stats = trainer.train()
^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/transformers/trainer.py", line 2241, in train
return inner_training_loop(
^^^^^^^^^^^^^^^^^^^^
File "", line 307, in _fast_inner_training_loop
File "", line 31, in _unsloth_training_step
File "/home/extra1T/xxx/projects/Qwen/unsloth_qwen_vl/unsloth_compiled_cache/UnslothSFTTrainer.py", line 747, in compute_loss
outputs = super().compute_loss(
^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/unsloth/models/_utils.py", line 1025, in _unsloth_pre_compute_loss
outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/transformers/trainer.py", line 3759, in compute_loss
outputs = model(**inputs)
^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/accelerate/utils/operations.py", line 819, in forward
return model_forward(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/accelerate/utils/operations.py", line 807, in call
return convert_to_fp32(self.model_forward(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/peft/peft_model.py", line 1719, in forward
return self.base_model(
^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/extra1T/xxx/miniconda/envs/unsloth_env/lib/python3.11/site-packages/peft/tuners/tuners_utils.py", line 197, in forward
return self.model.forward(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Qwen2VLForConditionalGeneration.forward() got an unexpected keyword argument 'num_items_in_batch'
0%| | 0/30 [00:14<?, ?it/s] `

Activity

  1. ItzAmirreza commented on Mar 21, 2025

    @ItzAmirreza

    Hey, I'm getting the same thing.

    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 1,000 | Num Epochs = 1 | Total steps = 62
    O^O/ \_/ \    Batch size per device = 1 | Gradient accumulation steps = 16
    \        /    Data Parallel GPUs = 1 | Total batch size (1 x 16 x 1) = 16
     "-____-"     Trainable parameters = 400,637,952/7,000,000,000 (5.72% trained)
    wandb: WARNING The `run_name` is currently set to the same value as `TrainingArguments.output_dir`. If this was not intended, please specify a different run name by setting the `TrainingArguments.run_name` parameter.
    wandb: Using wandb-core as the SDK backend.  Please refer to https://wandb.me/wandb-core for more information.
    wandb: Currently logged in as: itzamir (itzamir-test) to https://api.wandb.ai/. Use `wandb login --relogin` to force relogin
    Tracking run with wandb version 0.19.8
    Run data is saved locally in /workspace/wandb/run-20250321_104512-6z00ee3i
    Syncing run [outputs](https://wandb.ai/itzamir-test/FMAX/runs/6z00ee3i) to [Weights & Biases](https://wandb.ai/itzamir-test/FMAX) ([docs](https://wandb.me/developer-guide))
    View project at https://wandb.ai/itzamir-test/FMAX
    View run at https://wandb.ai/itzamir-test/FMAX/runs/6z00ee3i
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    Cell In[13], line 1
    ----> 1 trainer_stats = trainer.train()
    
    File /usr/local/lib/python3.10/dist-packages/transformers/trainer.py:2241, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
       2239         hf_hub_utils.enable_progress_bars()
       2240 else:
    -> 2241     return inner_training_loop(
       2242         args=args,
       2243         resume_from_checkpoint=resume_from_checkpoint,
       2244         trial=trial,
       2245         ignore_keys_for_eval=ignore_keys_for_eval,
       2246     )
    
    File <string>:307, in _fast_inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
    
    File <string>:31, in _unsloth_training_step(self, model, inputs, num_items_in_batch)
    
    File /workspace/unsloth_compiled_cache/UnslothSFTTrainer.py:748, in _UnslothSFTTrainer.compute_loss(self, model, inputs, return_outputs, num_items_in_batch)
        747 def compute_loss(self, model, inputs, return_outputs = False, num_items_in_batch = None):
    --> 748     outputs = super().compute_loss(
        749         model,
        750         inputs,
        751         return_outputs = return_outputs,
        752         num_items_in_batch = num_items_in_batch,
        753     )
        754     return outputs
    
    File /usr/local/lib/python3.10/dist-packages/unsloth/models/_utils.py:1028, in _unsloth_pre_compute_loss(self, model, inputs, *args, **kwargs)
       1022     logger.warning_once(
       1023         f"Unsloth: Not an error, but {name} does not accept `num_items_in_batch`.\n"\
       1024         "Using gradient accumulation will be very slightly less accurate.\n"\
       1025         "Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient"
       1026     )
       1027 pass
    -> 1028 outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
       1029 return outputs
    
    File /usr/local/lib/python3.10/dist-packages/transformers/trainer.py:3759, in Trainer.compute_loss(self, model, inputs, return_outputs, num_items_in_batch)
       3757         loss_kwargs["num_items_in_batch"] = num_items_in_batch
       3758     inputs = {**inputs, **loss_kwargs}
    -> 3759 outputs = model(**inputs)
       3760 # Save past state if it exists
       3761 # TODO: this needs to be fixed and made cleaner later.
       3762 if self.args.past_index >= 0:
    
    File /usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
       1737     return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
       1738 else:
    -> 1739     return self._call_impl(*args, **kwargs)
    
    File /usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
       1745 # If we don't have any hooks, we want to skip the rest of the logic in
       1746 # this function, and just call forward.
       1747 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
       1748         or _global_backward_pre_hooks or _global_backward_hooks
       1749         or _global_forward_hooks or _global_forward_pre_hooks):
    -> 1750     return forward_call(*args, **kwargs)
       1752 result = None
       1753 called_always_called_hooks = set()
    
    File /usr/local/lib/python3.10/dist-packages/accelerate/utils/operations.py:819, in convert_outputs_to_fp32.<locals>.forward(*args, **kwargs)
        818 def forward(*args, **kwargs):
    --> 819     return model_forward(*args, **kwargs)
    
    File /usr/local/lib/python3.10/dist-packages/accelerate/utils/operations.py:807, in ConvertOutputsToFp32.__call__(self, *args, **kwargs)
        806 def __call__(self, *args, **kwargs):
    --> 807     return convert_to_fp32(self.model_forward(*args, **kwargs))
    
    File /usr/local/lib/python3.10/dist-packages/torch/amp/autocast_mode.py:44, in autocast_decorator.<locals>.decorate_autocast(*args, **kwargs)
         41 @functools.wraps(func)
         42 def decorate_autocast(*args, **kwargs):
         43     with autocast_instance:
    ---> 44         return func(*args, **kwargs)
    
    File /usr/local/lib/python3.10/dist-packages/peft/peft_model.py:1756, in PeftModelForCausalLM.forward(self, input_ids, attention_mask, inputs_embeds, labels, output_attentions, output_hidden_states, return_dict, task_ids, **kwargs)
       1754     with self._enable_peft_forward_hooks(**kwargs):
       1755         kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args}
    -> 1756         return self.base_model(
       1757             input_ids=input_ids,
       1758             attention_mask=attention_mask,
       1759             inputs_embeds=inputs_embeds,
       1760             labels=labels,
       1761             output_attentions=output_attentions,
       1762             output_hidden_states=output_hidden_states,
       1763             return_dict=return_dict,
       1764             **kwargs,
       1765         )
       1767 batch_size = _get_batch_size(input_ids, inputs_embeds)
       1768 if attention_mask is not None:
       1769     # concat prompt attention mask
    
    File /usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
       1737     return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
       1738 else:
    -> 1739     return self._call_impl(*args, **kwargs)
    
    File /usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
       1745 # If we don't have any hooks, we want to skip the rest of the logic in
       1746 # this function, and just call forward.
       1747 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
       1748         or _global_backward_pre_hooks or _global_backward_hooks
       1749         or _global_forward_hooks or _global_forward_pre_hooks):
    -> 1750     return forward_call(*args, **kwargs)
       1752 result = None
       1753 called_always_called_hooks = set()
    
    File /usr/local/lib/python3.10/dist-packages/peft/tuners/tuners_utils.py:193, in BaseTuner.forward(self, *args, **kwargs)
        192 def forward(self, *args: Any, **kwargs: Any):
    --> 193     return self.model.forward(*args, **kwargs)
    
    TypeError: Qwen2_5_VLForConditionalGeneration.forward() got an unexpected keyword argument 'num_items_in_batch'
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  2. ykallan commented on Apr 4, 2025

    @ykallan

    i got same error while fine tuning "Qwen/Qwen2.5-VL-3B-Instruct"

  3. Gladiator07 commented on Apr 23, 2025

    @Gladiator07

    I get the same error. this is so frustrating. qwen 2 vl finetuning always breaks with an update and is never stable.

  4. PIN-FENG commented on May 8, 2025

    @PIN-FENG

    You can refer to the YouTube video titled 'Unsloth + Qwen2.5-VL: Environment Setup Guide' for instructions on environment installation.

  5. danielhanchen commented on Sep 15, 2026

    @danielhanchen
    Member

    Fixed! The Qwen2.5-VL vision finetuning example trains with gradient accumulation now, no num_items_in_batch error, since the VLM forwards take **kwargs. Please reopen if you still hit it on the current release!

    Please update Unsloth: uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir (if it's not in the current release yet it'll be in the next one). Reopen if it still happens!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions