Repository navigation
Description
Describe the bug
I'm currently trying to finetune Qwen2.5 VL for a bounding box object detection task and wanna therefore evaluate the performance based on bounding box accuracy metrics.
I've got all the necessary code to actually evaluate the output during fine-tuning, but the compute_metrics function is receiving incoherent generated text. However, the model is fully capable of generating coherent text when prompted with the same prompts in a normal inference run... Something is clearly going wrong during the inference when running against the eval_dataset.
Small sample of the text received by the compute_metrics function:
I a AI analyzing-level analysis you-depth a the name the paragraph><th through the the in the image describe their they are private not<th with a <think><th that through the, please the analysis a HTMLanalysis>output> block. a JSON. the following keys:-image": "1
"is": , "isposure": str} "is_box": {"bbox,, y_min, x_max, y_max]} "is": <th examples to consider:
full sample available here: https://gist.githubusercontent.com/hugohabicht01/a776b2d5b921b2cd93fd58a4b277dead/raw/93b41a71128811026580563385bb6421c7440b13/bad_generation.txt
-
Environment Setup:
- Python Version: 3.12
- unsloth version: 2025.3.19
-
Dataset Details:
- Dataset Name: custom dataset, with 4 columns,
prompt,image,outputandname
- Dataset Name: custom dataset, with 4 columns,
-
Model Details:
- Model ID:
unsloth/Qwen2.5-VL-3B-Instruct-unsloth-bnb-4bit - Model Configuration: load_in_4bit = True
- Model ID:
-
Training Configuration:
- Standard
SFTTrainersetup as specified in the various notebooks
- Standard
-
Reproduction Steps:
- Relevant code can be found here:
# dataset preprocess...
dataset = load_dataset("me/my-dataset")
train_data = dataset['train']
val_data = dataset['validation']
def convert_to_conversation_val(sample):
conversation = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are a helpful assistant for privacy analysis of images. Please always answer in English."
}
]
},
{"role": "user",
"content": [
{"type": "text", "text": sample['prompt']},
{"type": "image", "image": sample["image"]}]
},
{"role": "assistant",
"content": [
{"type": "text", "text": sample["output"]}]
},
]
return {
"messages": conversation,
"images": sample["image"], # images for displaying during inference, not passed thru the model
"name": sample["name"], # carry over the sample name for easier tracing, not passed thru the model
"output": sample["output"], # also not passed thru, i think?
"labels": sample['output'] # also not passed thru, i think?
}
train_dataset = [convert_to_conversation(entry) for entry in train_data]
val_dataset = [convert_to_conversation_val(entry) for entry in val_data]
model, tokenizer = FastVisionModel.from_pretrained(
"unsloth/Qwen2.5-VL-3B-Instruct-unsloth-bnb-4bit",
load_in_4bit=True, # Use 4bit to reduce memory use. False for 16bit LoRA.
use_gradient_checkpointing="unsloth", # True or "unsloth" for long context
)
# ... bunch of stuff in between, just stolen from the notebooks
def preprocess_logits_for_metrics(logits, labels):
if isinstance(logits, tuple):
logits = logits[0] # Take the first element of the tuple
# `logits` shape: (batch_size, seq_len, vocab_size)
pred_ids = torch.argmax(logits, dim=-1) # take argmax to get token predictions
return pred_ids
# Our custom metrics function
def compute_metrics(eval_pred: EvalPrediction):
# Unpack EvalPrediction
pred_ids = eval_pred.predictions # these are token IDs from our preprocess function
label_ids = eval_pred.label_ids # true token IDs (with -100 for ignored positions)
losses = eval_pred.losses
mean_ce_loss = losses.mean()
pred_ids = np.where(pred_ids == -100, tokenizer.pad_token_id, pred_ids)
# Replace -100 in labels to pad token id (so they decode to pad or nothing instead of -100)
label_ids = np.where(label_ids == -100, tokenizer.pad_token_id, label_ids)
# Decode token IDs to strings
pred_texts = tokenizer.batch_decode(pred_ids, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
label_texts = tokenizer.batch_decode(label_ids, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
# dumping the data into a file for debugging
with open("pred_texts.pkl", "wb") as f:
pickle.dump(pred_texts, f)
with open("label_texts.pkl", "wb") as f:
pickle.dump(label_texts, f)
#
# THIS IS WHERE THE ISSUE IS, THE DATA IS BROKEN FOR THE PREDS
# sry for screaming, all the label_texts are decoded correctly, but the predictions are just slightly off
# I have no idea why its happening or how to fix it...
# I'm not even sure anymore whether the mean cross entropy loss is even correct, given the shitty generated data
#
predicted_boxes = []
ground_truth_boxes = []
# the actual eval stuff, the data passed into here is good for the labels, but broken data for the preds
for pred_text, label_text in zip(pred_texts, label_texts):
# Extract boxes from ground truth and prediction
gt_boxes = extract_boxes(label_text)
pred_boxes = extract_boxes(pred_text)
ground_truth_boxes.append(gt_boxes)
predicted_boxes.append(pred_boxes)
# Use the provided evaluation function to get precision, recall, F1, IoU, etc.
custom_evals = evaluate_dataset(ground_truth_boxes, predicted_boxes)
return {**custom_evals, "loss": mean_ce_loss}
from unsloth import is_bf16_supported
from unsloth.trainer import UnslothVisionDataCollator
from trl import SFTTrainer, SFTConfig
FastVisionModel.for_training(model) # Enable for training!
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
data_collator=UnslothVisionDataCollator(model, tokenizer, resize="max"), # Must use!
train_dataset=train_dataset,
eval_dataset=val_dataset,
compute_metrics=compute_metrics,
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
args=SFTConfig(
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
warmup_steps=5,
num_train_epochs=6,
learning_rate=4e-5,
fp16=not is_bf16_supported(),
bf16=is_bf16_supported(),
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="cosine",
seed=1337,
report_to="wandb", # For Weights and Biases
eval_strategy="steps",
eval_steps=50,
eval_accumulation_steps=1,
save_strategy="steps",
save_steps=50,
metric_for_best_model="F1",
greater_is_better=True,
eval_on_start=True,
include_for_metrics=["precision", "recall", "F1", "average_iou", "loss"],
# 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=1024,
),
)
trainer_stats = trainer.train()-
Expected Behavior:
- Receive coherent text in the compute_metrics function and not this jumbled garbage.
-
Actual Behavior:
- see above
-
Additional notes:
- The labels received in the compute_metrics function are fully coherent, so I doubt the issue is caused by the tokenizer
Activity
BenjaminBruenau commentedon Jun 9, 2025
Hey I encountered the same issues with a custom compute_metrics function as you did when trying to calculate metrics based on the predicted text.
I think the problem lies with transformers / trl and not with unsloth.
The crux of the problem seems to be that the evaluation loop of the SFTTrainer is not generating the predictions of the model in the same way as regular inference would (
single forward pass vs. autoregressive generation -> multiple forward passes for each new token until EOS token is reached), which is why it works fine for a regular inference run but the predictions passed to compute_metrics seem off.See this issue for reference: huggingface/trl#862
and these two comments for more detailed explanations:
I am pretty sure a more elegant solution (until this behaviour is changed / configurable) is possible, but my quick and dirty workaround for this is simply passing the trainer object to my compute_metrics function and generating the prediction with trainer.model and the prompts contained in the labels. Note that this slows the whole training process down significantly.
If you are using a logging service like wandb and do not necessarily need to have your custom metrics as an eval loss in the trainer you can also implement a custom callback which logs this (so something similar to this)
steveepreston commentedon Oct 17, 2025
Struggling with this trash state from 2023, not found a working way
danielhanchen commentedon Oct 8, 2026
Sorry on the delay! This one is expected behaviour of the Trainer eval loop, not a bug in Unsloth (plain transformers gives the exact same text). Two things are going on:
eval_pred.predictionsis not generated text. The eval loop does one teacher-forced forward pass, soargmax(logits)at positiontis the model's guess for tokent + 1given the ground truth up tot. Decoding it unshifted, and over the system prompt, user prompt and image positions too, gives exactly the jumbled text you posted.Add
train_on_responses_only = True, instruction_part = "<|im_start|>user\n", response_part = "<|im_start|>assistant\n"toUnslothVisionDataCollatorso the labels (and the loss) only cover the assistant answer.I checked this on Qwen2.5-VL-3B (4bit and 16bit) with Unsloth main and with plain transformers on the same eval batch. Your decoding gives
1开幕式联 multi AI follow with ... background square ... rectangle rectanglewith both. With the shift, the answer span decodes toThe image shows a blue square with a white background.for a label ofThe image shows a blue rectangle on a white background., about 80% token accuracy, and Unsloth's predictions match plain transformers on 96% to 99% of answer tokens.Even shifted, these are still teacher-forced guesses, so for bounding box metrics you want real generation. SFTTrainer has no
predict_with_generate(see huggingface/trl#862), so runmodel.generateon the eval prompts yourself, for example in aTrainerCallback.on_evaluateor after training:Closing since this works as intended, but feel free to reopen if the shifted predictions still look wrong for you.