Skip to content

importing unsloth before trl on multi image grpo training gives mismatch error #5183

Closed
unslothai/unsloth-zoo
#613

Description

@jaaabir

Note: Please do not remove the questions. Answer beside them.

  1. Did you update? pip install --upgrade unsloth unsloth_zoo: yes
  2. Colab or Kaggle or local / cloud: cloud ( a40 nvidia gpu )
  3. Number GPUs used, use nvidia-smi: 1
  4. Which notebook? Please link! : no
  5. Which Unsloth version, TRL version, transformers version, PyTorch version?: 2026.4.6, 1.2.0, 5.5.4, 2.10.0
  6. Which trainer? SFTTrainer, GRPOTrainer etc: GRPOTrainer
#  Testing script

from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer
from unsloth import FastVisionModel
from peft import LoraConfig
import torch 
from datasets import Sequence, Image as HFImage
import os 


# If not handled properly, prompt truncation may truncate image token
dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_prompt_only", split="train")
dataset = dataset.filter(lambda x: len(x["images"]) == 2) 


def my_reward_function(prompts, completions, **kwargs):
    return [1.0] * len(prompts)

model, processor = FastVisionModel.from_pretrained(
            "./outputs/qwen3.5-2b-invoice-finetuned",
            max_seq_length=55_000,
            dtype=torch.bfloat16,
            load_in_4bit=False,
            trust_remote_code=True,
            device_map="auto",
            attn_implementation="flash_attention_2",
            fast_inference=False
        )

model = FastVisionModel.get_peft_model(
            model,
        )

training_args = GRPOConfig(
    output_dir="tmp_dir",   
    # ── generation ─────────────────────────────────────────
            # max_new_tokens=self.max_new_tokens,
            temperature=0.9,       # higher than inference — need diverse rollouts
            top_p=0.95,
            top_k=20,
            num_generations=4,     # G=4 rollouts per prompt
            # ── training ───────────────────────────────────────────
            num_train_epochs=1,
            learning_rate=1e-5,
            weight_decay=0.01,
            max_grad_norm=0.5,
            warmup_steps=20,
            lr_scheduler_type="cosine",
            optim="adamw_8bit",
            # ── batch / accumulation ───────────────────────────────
            per_device_train_batch_size=1,
            gradient_accumulation_steps=4,
            # ── GRPO-specific ──────────────────────────────────────
            beta=0.04,             # KL penalty coefficient
            epsilon=0.2,           # PPO clip ratio
            # ── memory ─────────────────────────────────────────────
            bf16=True,
            fp16=False,
            use_cache=False,
            # ── dataloader ─────────────────────────────────────────
            dataloader_num_workers=2,
            dataloader_pin_memory=True,
            # ── saving / logging ───────────────────────────────────
            save_strategy="epoch",
            save_total_limit=2,
            logging_steps=5,
            report_to="none",
            seed=4123,
            remove_unused_columns=False,
            use_vllm=False,
            log_completions = True,
            # max_prompt_length = 45_000,
            max_completion_length = 20_000,
            importance_sampling_level = "sequence",
            # mask_truncated_completions = False,
            loss_type = "vespo"
        )

trainer = GRPOTrainer(
    model=model,
    processing_class=processor,
    reward_funcs=my_reward_function,  # define a dummy reward function
    args=training_args,
    train_dataset=dataset,
)

previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}

trainer.train()

Explanation:

  • I get this mismatch in the image tokens and image features if i import unsloth before trl but doesn't give that same error if i import trl before unsloth.
  • This only happens when the sample has multiple images but doesn't give any error if a sample has one image.
  • Also the error shows that for a sample with images == 2 , it seems to use only one image and thats the reason for model to produce image feature for only one image.

error:

Traceback (most recent call last):
  File "/workspace/ocr/qwen_grpo2.py", line 350, in <module>
    main()
  File "/workspace/ocr/qwen_grpo2.py", line 346, in main
    trainer.train()
  File "/workspace/ocr/qwen_grpo2.py", line 290, in train
    result =self.trainer.train()
            ^^^^^^^^^^^^^^^^^^^^
  File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 84, in wrapper
    output = f(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 144, in _unsloth_train_with_resume_guard
    return original_train(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1425, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1507, in _inner_training_loop
    self._run_epoch(
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1735, in _run_epoch
    tr_loss_step = self.training_step(model, inputs, num_items_in_batch)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3086, in training_step
    output = super().training_step(model, inputs, num_items_in_batch)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 34, in _unsloth_training_step
  File "/workspace/stable-venv/lib/python3.12/site-packages/trl/extras/profiling.py", line 202, in wrapper
    return func(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3115, in _prepare_inputs
    generation_batch = self._generate_and_score_completions(generation_batch)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 526, in wrapped
    return original(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 4111, in _generate_and_score_completions
    ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3021, in _get_per_token_logps_and_entropies
    logits_chunk = unwrapped_model(
                   ^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/peft/peft_model.py", line 1993, in forward
    return self.base_model(
           ^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 330, in forward
    return self.model.forward(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
    output = func(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1937, in forward
    outputs = self.model(
              ^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
    output = func(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1666, in forward
    image_mask, _ = self.get_placeholder_mask(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1569, in get_placeholder_mask
    torch_compilable_check(
  File "/workspace/stable-venv/lib/python3.12/site-packages/transformers/utils/import_utils.py", line 1540, in torch_compilable_check
    torch._check_with(error_type, cond, msg_callable)
  File "/workspace/stable-venv/lib/python3.12/site-packages/torch/__init__.py", line 1719, in _check_with
    raise error_type(message_evaluated)
ValueError: Image features and image tokens do not match, tokens: 596, features: 298

🦥 You can also ask via our Reddit page: https://reddit.com/r/unsloth/

Activity

  1. Datta0 commented on Apr 27, 2026

    @Datta0
    Contributor

    Interesting, the way we expect imports to be ordered is Unsloth before trl & co. But I do remember there's something with multiple images in the same request... Will have to seee

  2. self-assigned this
    on Apr 27, 2026
  3. Datta0 commented on Apr 27, 2026

    @Datta0
    Contributor

    Hey @jaaabir can you try my branch where i tried to fix it? If you can confirm that this works, would merge it soon

    ! pip uninstall unsloth unsloth_zoo -y
    ! uv pip install git+https://github.com/datta0/unsloth@multi_image_grpo --no-deps
    ! uv pip install git+https://github.com/datta0/unsloth-zoo@multi_image_grpo --no-deps
    ! rm -rf unsloth_compiled_cache
    

    Then rerun your script/notebook

  4. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    sure let me give it a try

  5. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    @Datta0 Nope.

    • Training became slower ( x2 slower )
    • This version doesn't support loss_type=vespo
    • it ran successfully for 2 steps but then it gave a mismatch error ( in between layers this time )

    Full traceback:

    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Passing `generation_config` together with generation-related arguments=({'pad_token_id', 'disable_compile'}) is deprecated and will be removed in future versions. Please pass either a `generation_config` object OR all generation parameters explicitly, but not both.
    Casting fp32 inputs back to torch.float16 for flash-attn compatibility.
    Unsloth: Will smartly offload gradients to save VRAM!
     20%|██████████████▍                                                         | 1/5 [04:51<19:26, 291.63s/it]Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
     40%|████████████████████████████▊                                           | 2/5 [06:39<09:10, 183.47s/it]Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Traceback (most recent call last):
      File "/workspace/ocr/qwen_grpo2.py", line 341, in <module>
        main()
      File "/workspace/ocr/qwen_grpo2.py", line 337, in main
        trainer.train()
      File "/workspace/ocr/qwen_grpo2.py", line 292, in train
        result =self.trainer.train()
                ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 84, in wrapper
        output = f(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 144, in _unsloth_train_with_resume_guard
        return original_train(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1424, in train
        return inner_training_loop(
               ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1506, in _inner_training_loop
        self._run_epoch(
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1734, in _run_epoch
        tr_loss_step = self.training_step(model, inputs, num_items_in_batch)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "<string>", line 34, in _unsloth_training_step
      File "/workspace/test-venv/lib/python3.12/site-packages/trl/extras/profiling.py", line 98, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 2874, in _prepare_inputs
        generation_batch = self._generate_and_score_completions(generation_batch)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 526, in wrapped
        return original(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3378, in _generate_and_score_completions
        ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 2735, in _get_per_token_logps_and_entropies
        logits_chunk = unwrapped_model(
                       ^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/peft/peft_model.py", line 1993, in forward
        return self.base_model(
               ^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 330, in forward
        return self.model.forward(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
        output = func(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1916, in forward
        outputs = self.model(
                  ^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
        output = func(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1662, in forward
        position_ids = self.compute_3d_position_ids(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1583, in compute_3d_position_ids
        position_ids, rope_deltas = self.get_rope_index(
                                    ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1472, in get_rope_index
        position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
        ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    RuntimeError: shape mismatch: value tensor of shape [3, 12941] cannot be broadcast to indexing result of shape [3, 11142]
    
  6. Datta0 commented on Apr 27, 2026

    @Datta0
    Contributor

    Hey @jaaabir , I updated the brands again, and tried with the exact example that you gave me and got it to work. Can you please retry?

  7. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    @Datta0 ok what do i have to do ? reinstall the same pkg ?

  8. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    Also would you mind explaining which parts you changed? was it dropping half of the images before the forward pass?

  9. Datta0 commented on Apr 27, 2026

    @Datta0
    Contributor

    Yeah just follow the same instructions that are previously mentioned.Make sure to clear caches uh before rerunning.
    Uh we never had support for multi image GRPO. We only had support for single image GRPO. This branch/PR currently adds support for multi-image GRPO and image processing is kind of the bottleneck.
    Just like we were processing single image previously, we do now process multi images equivalently.

  10. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    okk let me test it

  11. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    @Datta0 you are right it does work, but only for this test image for now. but when i use it on my own inhouse dataset i get the same error i got last time

    • This version doesnt support loss_type=vespo
    • Encountered the same error as last time related to mismatch in the model layers.

    Error

    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Passing `generation_config` together with generation-related arguments=({'pad_token_id', 'disable_compile'}) is deprecated and will be removed in future versions. Please pass either a `generation_config` object OR all generation parameters explicitly, but not both.
    Casting fp32 inputs back to torch.float16 for flash-attn compatibility.
    Unsloth: Will smartly offload gradients to save VRAM!
     20%|██████████████▍                                                         | 1/5 [04:51<19:26, 291.63s/it]Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
     40%|████████████████████████████▊                                           | 2/5 [06:39<09:10, 183.47s/it]Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
    Traceback (most recent call last):
      File "/workspace/ocr/qwen_grpo2.py", line 341, in <module>
        main()
      File "/workspace/ocr/qwen_grpo2.py", line 337, in main
        trainer.train()
      File "/workspace/ocr/qwen_grpo2.py", line 292, in train
        result =self.trainer.train()
                ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 84, in wrapper
        output = f(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 144, in _unsloth_train_with_resume_guard
        return original_train(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1424, in train
        return inner_training_loop(
               ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1506, in _inner_training_loop
        self._run_epoch(
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/trainer.py", line 1734, in _run_epoch
        tr_loss_step = self.training_step(model, inputs, num_items_in_batch)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "<string>", line 34, in _unsloth_training_step
      File "/workspace/test-venv/lib/python3.12/site-packages/trl/extras/profiling.py", line 98, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 2874, in _prepare_inputs
        generation_batch = self._generate_and_score_completions(generation_batch)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/unsloth/models/rl.py", line 526, in wrapped
        return original(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3378, in _generate_and_score_completions
        ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/ocr/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 2735, in _get_per_token_logps_and_entropies
        logits_chunk = unwrapped_model(
                       ^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/peft/peft_model.py", line 1993, in forward
        return self.base_model(
               ^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 330, in forward
        return self.model.forward(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
        output = func(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1916, in forward
        outputs = self.model(
                  ^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/utils/generic.py", line 876, in wrapper
        output = func(self, *args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1662, in forward
        position_ids = self.compute_3d_position_ids(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1583, in compute_3d_position_ids
        position_ids, rope_deltas = self.get_rope_index(
                                    ^^^^^^^^^^^^^^^^^^^^
      File "/workspace/test-venv/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1472, in get_rope_index
        position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
        ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    RuntimeError: shape mismatch: value tensor of shape [3, 12941] cannot be broadcast to indexing result of shape [3, 11142]
    
  12. jaaabir commented on Apr 27, 2026

    @jaaabir
    Author

    from what i can pinpoint its the batching problem for the images

  13. Datta0 commented on Apr 27, 2026

    @Datta0
    Contributor

    Can you please make sure that you clear all the cache before rerunning? Also please import Unsloth before importing any other package.

  14. jaaabir commented on Apr 28, 2026

    @jaaabir
    Author

    ok, i did remove the cache and unsloth was imported before trl but this time ill move the unsloth import to the top.

  15. jaaabir commented on Apr 28, 2026

    @jaaabir
    Author

    @Datta0 tried again, same error

  16. jaaabir commented on Apr 28, 2026

    @jaaabir
    Author

    try to use .map func to overwrite the prompt and use this ( this is how my dataset is like ):

    def convert_prompt_and_resize_images(example):
        completion = """{\n  "invoiceNumber": "FT 2024/001",\n  "currency": "EUR",\n  "issuer": {\n    "name": "Example Company Lda",\n    "taxId": "123456789"\n  },\n  "buyer": {\n    "name": "Client Company SA",\n    "taxId": "987654321"\n  },\n  "issueDate": "2024-01-15",\n  "dueDate": "2024-02-15",\n  "totalGross": 1230.00,\n  "totalNet": 1000.00,\n  "totalVat": 230.00,\n  "totalStamp": 0.00,\n  "taxWithholding": 0.00,\n  "items": [\n    {\n      "quantity": 10,\n      "description": "Professional Services",\n      "discount": 0,\n      "discountMode": "FixedAmount",\n      "price": 1000.00,\n      "priceType": "Net",\n      "vat": 230.00,\n      "vatMode": "FixedAmount",\n      "stamp": 0,\n      "stampMode": "FixedAmount"\n    }\n  ]\n}"""
        example["prompt"] = [
            {
                'role': 'system', 
                'content': [{
                    'type': 'text', 
                    'text': '<<CONTEXT>>\nYou are analyzing invoice images to extract structured data. Invoices may be in Portuguese or English.\nIssuer\'s taxId appears top-left near issuer details. Buyer\'s taxId appears near buyer section.\n<</CONTEXT>>\n\n<<CRITICAL EXTRACTION RULES>>\n\n**VAT/Tax ID Extraction (CRITICAL):**\n- Valid VAT format: 2 letters followed by numbers (e.g., PT123456789, ES12345678) OR exactly 9 digits in most cases\n- DO NOT extract client numbers, reference numbers, order numbers or phone numbers as VAT\n- If multiple number sequences appear, choose the one that matches VAT format\n- Verify the number appears near "NIF", "NIPC", "VAT", "Tax ID", or similar labels\n\n**Company Name Extraction:**\n- Extract ONLY the company or person name\n- EXCLUDE titles and honorifics: Dr., Exmo., Exma., Sr., Sra., Eng., Prof., etc.\n- Example: "Exmo. João Silva" → extract as "João Silva"\n\n**Price Field (MOST IMPORTANT):**\n- `price` = TOTAL LINE PRICE including quantity, NOT per-unit price\n- Example: if 5 units at 100€ each, price = 500€\n\n**Price Type:**\n- "Net" = base price BEFORE discount, BEFORE taxes (default/preferred - most common)\n"Gross" = price INCLUDING taxes, AFTER discount and after all taxes\n- Default to "Net" when uncertain\n\n**Discount:**\n- Applied to the net price (before taxes)\n- After discount is applied, you get the discounted net amount\n\n**Calculation Flow:**\n- Net price → apply discount → discounted net → apply VAT/stamp → gross total\n\n**Mode Selection:**\n- "Percentage" = rate shown (e.g., 23%)\n- "FixedAmount" = currency amount shown (e.g., 115.00€)\n- Prefer "FixedAmount" when both are available\n\n**Required Fields:**\n- Invoice number, currency (3-letter ISO: EUR, USD, etc.)\n- At least one of: issuer name OR issuer taxId\n- At least one of: buyer name OR buyer taxId\n- Issue date (YYYY-MM-DD format)\n- At least one item with: quantity > 0, description\n\n**Validation:**\n- totalNet = optional when not visible in the invoice, if existent should be sum of all item net prices AFTER discounts\n- totalVat = optional when not visible in the invoice, if existent should be sum of all item VAT amounts\n- totalStamp = optional when not visible in the invoice, if existent should be sum of all item stamp amounts\n- totalGross = REQUIRED, total value with all taxes included (totalNet + totalVat + totalStamp)\n\n<</CRITICAL EXTRACTION RULES>>\n\n<<OUTPUT FORMAT>>\nReturn a single JSON object with this structure:\n```json\n{completion}\n```\n\n**Key notes:**\n- Use camelCase for all keys\n- Set missing optional fields to null\n- Extract values exactly as shown - don\'t calculate\n- price = total line price (quantity included)\n- Modes: only "Percentage" or "FixedAmount"\n- priceType: only "Net" or "Gross"\n<</OUTPUT FORMAT>>'
                    }]}, 
            {
                'role': 'user', 
                'content': [{
                    'type': 'text', 
                    'text': 'Process the provided document.'}, 
                    {'type': 'image', 'text': None}, 
                    {'type': 'image', 'text': None}
                    ]}
            ]
    
        example["images"] = [i.resize((2481, 3508)) for i in example["images"] if i is not None]
        example['answer'] = completion
        return example
  17. Datta0 commented on Apr 28, 2026

    @Datta0
    Contributor

    We do not have support for vespo yet. But regarding the said shape mismatch, I fixed it and pushed the changes
    If you can retry and confirm that would be great

  18. jaaabir commented on Apr 29, 2026

    @jaaabir
    Author

    here's the list of what i did:

    • removed unsloth_compiled_cache
    • uninstalled the old unsloth and unsloth-zoo
    • installed this new updated version
    • made sure the code are similar to the recent push.
    • reran the script which uses my main dataset that has big system prompt, and large images ( ~ 2481x3500 )
    • got the same error mismatch error RuntimeError: shape mismatch: value tensor of shape [3, 12941] cannot be broadcast to indexing result of shape [3, 11142]
    • However the script ran successfully when i tried the same script on the test dataset which has small images
  19. jaaabir commented on Apr 29, 2026

    @jaaabir
    Author

    can you tell me your versions for the following modules:

    • trl
    • torch
    • torchvision
    • transformers
  20. Datta0 commented on Apr 29, 2026

    @Datta0
    Contributor

    Do you mind trying a loss_type which is not vespo? Perhaps something like bnpo or grpo or dr_grpo ?

  21. jaaabir commented on Apr 29, 2026

    @jaaabir
    Author

    the loss_type that i used was grpo since in the beginning vespo wasnt supported. I did notice that you added vespo support in the latest push but still i used grpo.

    tell me about your output, did it work on that test dataset that i gave you? have you tried that map method to override the test prompt and test images with my in-house dataset sys and user prompt and resizing the images to the size of my dataset images?

  22. Datta0 commented on Apr 29, 2026

    @Datta0
    Contributor
    torch                                    2.10.0+cu130
    torchaudio                               2.10.0+cu130
    torchvision                              0.25.0+cu130
    transformers                             5.6.2
    trl                                      1.3.0
    unsloth                                  2026.4.8        <dir>/multi-image-grpo
    unsloth-zoo                              2026.4.9        <dir>/multi-image-grpo
    
    

    This is my setup and I tried exactly what you mentioned. If you can perhaps create a colab notebook to reproduce the error, that would help

  23. jaaabir commented on Apr 29, 2026

    @jaaabir
    Author
  24. Datta0 commented on Apr 29, 2026

    @Datta0
    Contributor

    You should remove the previous parameters thingy
    Also because you're using images, the seq len is blowing up. It was 32K+ I saw. You should install flash-attn, flash-linear-attn and causal-conv-1d

    you can follow the instructions here for the latter two. For flash-attn, use whatever method is favorable for you.

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

Metadata

Metadata

Assignees

Labels

bugcurrently fixing

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions