Repository navigation
Closed
unslothai/unsloth-zoo
#613Labels
Description
Note: Please do not remove the questions. Answer beside them.
- Did you update?
pip install --upgrade unsloth unsloth_zoo: yes ColaborKaggleor local / cloud: cloud ( a40 nvidia gpu )- Number GPUs used, use
nvidia-smi: 1 - Which notebook? Please link! : no
- Which Unsloth version, TRL version, transformers version, PyTorch version?: 2026.4.6, 1.2.0, 5.5.4, 2.10.0
- Which trainer?
SFTTrainer,GRPOTraineretc: 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
Datta0 commentedon Apr 27, 2026
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
Datta0 commentedon Apr 27, 2026
Hey @jaaabir can you try my branch where i tried to fix it? If you can confirm that this works, would merge it soon
Then rerun your script/notebook
jaaabir commentedon Apr 27, 2026
sure let me give it a try
jaaabir commentedon Apr 27, 2026
@Datta0 Nope.
loss_type=vespoFull traceback:
Datta0 commentedon Apr 27, 2026
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?
jaaabir commentedon Apr 27, 2026
@Datta0 ok what do i have to do ? reinstall the same pkg ?
jaaabir commentedon Apr 27, 2026
Also would you mind explaining which parts you changed? was it dropping half of the images before the forward pass?
Datta0 commentedon Apr 27, 2026
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.
jaaabir commentedon Apr 27, 2026
okk let me test it
jaaabir commentedon Apr 27, 2026
@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
loss_type=vespoError
jaaabir commentedon Apr 27, 2026
from what i can pinpoint its the batching problem for the images
Datta0 commentedon Apr 27, 2026
Can you please make sure that you clear all the cache before rerunning? Also please import Unsloth before importing any other package.
jaaabir commentedon Apr 28, 2026
ok, i did remove the cache and unsloth was imported before trl but this time ill move the unsloth import to the top.
jaaabir commentedon Apr 28, 2026
@Datta0 tried again, same error
jaaabir commentedon Apr 28, 2026
try to use .map func to overwrite the prompt and use this ( this is how my dataset is like ):
Datta0 commentedon Apr 28, 2026
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
jaaabir commentedon Apr 29, 2026
here's the list of what i did:
unsloth_compiled_cacheRuntimeError: shape mismatch: value tensor of shape [3, 12941] cannot be broadcast to indexing result of shape [3, 11142]jaaabir commentedon Apr 29, 2026
can you tell me your versions for the following modules:
Datta0 commentedon Apr 29, 2026
Do you mind trying a loss_type which is not vespo? Perhaps something like bnpo or grpo or dr_grpo ?
jaaabir commentedon Apr 29, 2026
the
loss_typethat i used wasgrposince in the beginningvespowasnt supported. I did notice that you addedvesposupport in the latest push but still i usedgrpo.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?
Datta0 commentedon Apr 29, 2026
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
jaaabir commentedon Apr 29, 2026
https://colab.research.google.com/drive/1lRR3B6Aarr9UwHouY-fHrAOv64GFu_nM?usp=sharing
i dont have the higher gpu :(
so the trainer wouldnt even start the training. Any other ideas?
Datta0 commentedon Apr 29, 2026
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.