Repository navigation
Closed
Labels
feature requestFeature request pending on roadmap
Description
Hello! Have a nice day!
In the process of finetuning LLAMA3.2, I tried to implement compute_metrics function but during training, at the first attempt to pass the evaluation step, an error occurs:
TypeError: Unsupported types (<class 'unsloth.models._utils.EmptyLogits'>) passed to '_pad_across_processes'. Only nested list/tuple/dicts of objects that are valid for 'is_torch_tensor' should be passed.
Can someone please tell me what I'm doing wrong?
Thank you in advance!
Simple code example:
import datasets
import evaluate
import numpy as np
import torch
from common import make_json
from transformers import DataCollatorForSeq2Seq, EvalPrediction, TrainingArguments
from trl import SFTTrainer
from unsloth import FastLanguageModel, is_bfloat16_supported, unsloth_train
from unsloth.chat_templates import get_chat_template, train_on_responses_only
datasets.disable_caching()
model_size = "3B"
max_seq_length = 16384
dtype = None
load_in_4bit = True
eval_steps = 8
bleu_metric = evaluate.load("bleu")
rouge_metric = evaluate.load("rouge")
meteor_metric = evaluate.load("meteor")
def compute_metrics(p: EvalPrediction):
print("in compute")
logits, labels = p
if isinstance(logits, tuple):
logits = logits[0]
if isinstance(logits, np.ndarray):
logits = torch.from_numpy(logits)
if isinstance(labels, np.ndarray):
labels = torch.from_numpy(labels)
preds = torch.argmax(logits, dim=-1)
preds = preds.detach().cpu()
labels = labels.detach().cpu()
labels[labels == -100] = tokenizer.pad_token_id
preds_list = preds.tolist()
labels_list = labels.tolist()
decoded_preds = tokenizer.batch_decode(preds_list, skip_special_tokens=True)
decoded_labels = tokenizer.batch_decode(labels_list, skip_special_tokens=True)
decoded_labels = [[label] for label in decoded_labels]
bleu = bleu_metric.compute(predictions=decoded_preds, references=decoded_labels)
rouge = rouge_metric.compute(predictions=decoded_preds, references=decoded_labels)
meteor = meteor_metric.compute(predictions=decoded_preds, references=decoded_labels)
return {
"bleu": bleu["bleu"],
**rouge,
**meteor,
}
def format_chat_template(row):
return {
"text": tokenizer.apply_chat_template(
make_json(row["html_spec"], row["result_json"]),
tokenize=False,
add_generation_prompt=False,
)
}
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=f"unsloth/Llama-3.2-3B-Instruct",
max_seq_length=max_seq_length,
dtype=dtype,
load_in_4bit=load_in_4bit,
use_cache=False,
)
model = FastLanguageModel.get_peft_model(
model,
r=32,
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
],
lora_alpha=8,
lora_dropout=0.05,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=73,
use_rslora=True,
loftq_config=None,
)
tokenizer = get_chat_template(
tokenizer,
chat_template="llama-3.1",
)
files = {
"train": "train.csv",
"val": "val.csv",
}
dataset = datasets.load_dataset("./ds/", data_files=files)
dataset = dataset.map(
format_chat_template,
num_proc=2,
load_from_cache_file=False,
)
train = dataset["train"]
val = dataset["val"]
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=train,
eval_dataset=val,
dataset_text_field="text",
max_seq_length=max_seq_length,
data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer),
dataset_num_proc=2,
packing=False,
compute_metrics=compute_metrics, #! эксерименты
args=TrainingArguments(
include_for_metrics=["inputs"],
per_device_train_batch_size=1,
per_device_eval_batch_size=1,
gradient_accumulation_steps=8,
warmup_steps=5,
num_train_epochs=25,
learning_rate=1e-5,
fp16=not is_bfloat16_supported(),
bf16=is_bfloat16_supported(),
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
seed=73,
output_dir="outputs",
report_to="tensorboard",
eval_strategy="steps",
eval_steps=eval_steps,
load_best_model_at_end=True,
save_strategy="steps",
save_steps=eval_steps,
greater_is_better=False,
metric_for_best_model="eval_loss",
),
)
trainer = train_on_responses_only(
trainer,
instruction_part="<|start_header_id|>user<|end_header_id|>\n\n",
response_part="<|start_header_id|>assistant<|end_header_id|>\n\n",
)
trainer_stats = unsloth_train(trainer)
print(trainer_stats)Full traceback:
==((====))== Unsloth - 2x faster free finetuning | Num GPUs = 1
\\ /| Num examples = 135 | Num Epochs = 25
O^O/ \_/ \ Batch size per device = 1 | Gradient Accumulation steps = 8
\ / Total batch size = 8 | Total steps = 400
"-____-" Number of trainable parameters = 48,627,712
{'loss': 0.4289, 'grad_norm': 0.602544367313385, 'learning_rate': 2.0000000000000003e-06, 'epoch': 0.06}
{'loss': 0.3933, 'grad_norm': 0.5527276992797852, 'learning_rate': 4.000000000000001e-06, 'epoch': 0.12}
{'loss': 0.3182, 'grad_norm': 0.5175687074661255, 'learning_rate': 6e-06, 'epoch': 0.18}
{'loss': 0.3351, 'grad_norm': 0.5350865125656128, 'learning_rate': 8.000000000000001e-06, 'epoch': 0.24}
{'loss': 0.4945, 'grad_norm': 0.64827960729599, 'learning_rate': 1e-05, 'epoch': 0.3}
{'loss': 1.1773, 'grad_norm': 1.3612430095672607, 'learning_rate': 9.974683544303799e-06, 'epoch': 0.36}
{'loss': 0.392, 'grad_norm': 0.6794989109039307, 'learning_rate': 9.949367088607596e-06, 'epoch': 0.41}
{'loss': 0.437, 'grad_norm': 0.6301035284996033, 'learning_rate': 9.924050632911392e-06, 'epoch': 0.47}
2%|████ | 8/400 [01:04<52:46, 8.08s/it]Unsloth: Not an error, but LlamaForCausalLM does not accept `num_items_in_batch`.
Using gradient accumulation will be very slightly less accurate.
Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient
Traceback (most recent call last):
File "/home/user/mik/unsloth/./simple_train.py", line 178, in <module>
trainer_stats = unsloth_train(trainer)
^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/unsloth/trainer.py", line 45, in unsloth_train
return trainer.train(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 157, in train
File "<string>", line 449, in _fast_inner_training_loop
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/transformers/trainer.py", line 3071, in _maybe_log_save_evaluate
metrics = self._evaluate(trial, ignore_keys_for_eval)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/transformers/trainer.py", line 3025, in _evaluate
metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/transformers/trainer.py", line 4076, in evaluate
output = eval_loop(
^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/transformers/trainer.py", line 4292, in evaluation_loop
logits = self.accelerator.pad_across_processes(logits, dim=1, pad_index=-100)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/accelerate/accelerator.py", line 2602, in pad_across_processes
return pad_across_processes(tensor, dim=dim, pad_index=pad_index, pad_first=pad_first)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/accelerate/utils/operations.py", line 412, in wrapper
return function(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/accelerate/utils/operations.py", line 682, in pad_across_processes
return recursively_apply(
^^^^^^^^^^^^^^^^^^
File "/home/user/mik/unsloth/env/lib/python3.12/site-packages/accelerate/utils/operations.py", line 129, in recursively_apply
raise TypeError(
TypeError: Unsupported types (<class 'unsloth.models._utils.EmptyLogits'>) passed to `_pad_across_processes`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.
Python version: Python 3.12.3
Package versions:
unsloth 2025.1.5
unsloth_zoo 2025.1.3
transformers 4.48.0
accelerate 1.2.1
bitsandbytes 0.45.0
torch 2.5.1
Unsloth info:
==((====))== Unsloth 2025.1.5: Fast Llama patching. Transformers: 4.48.0.
\\ /| GPU: NVIDIA RTX A5000. Max memory: 23.679 GB. Platform: Linux.
O^O/ \_/ \ Torch: 2.5.1+cu124. CUDA: 8.6. CUDA Toolkit: 12.4. Triton: 3.1.0
\ / Bfloat16 = TRUE. FA [Xformers = 0.0.29.post1. FA2 = False]
"-____-" Free Apache license: http://github.com/unslothai/unsloth
Reacted by Steve
Reacted by Anna Savitskaya
Metadata
Metadata
Assignees
Labels
feature requestFeature request pending on roadmap
Activity
danielhanchen commentedon Jan 16, 2025
Sorry on the issue!
Before training (at the start of the Python script), could you place:
mik8142 commentedon Jan 16, 2025
Thank you for your help, but after adding this line at the start of script, i get OOM on eval step
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 10.00 GiB. GPU 0 has a total capacity of 23.68 GiB of which 9.69 GiB is free. Process 1153437 has 3.14 GiB memory in use. Including non-PyTorch memory, this process has 10.83 GiB memory in use. Of the allocated memory 10.49 GiB is allocated by PyTorch, and 93.31 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)But my validation batch size set to 1 (per_device_eval_batch_size=1), may be it can move predicted data on evaluation step from vram to ram?
I also have this strings in output, before eval step:
is it ok?
mik8142 commentedon Jan 16, 2025
Looks like i found the solution, it works for me:
I added to training args:
And rewrite compute_metrics (simple example below):
More information can be found here: huggingface/transformers#28769
kesimeg commentedon Jan 18, 2025
Hello I ran in to the same problem. I want to calculate BLEU score similar to the original question. Returning the logits increase the memory consumption too much. Also BLEU score doesn't actually need logits. So as far as I understand I have to use logits just because compute_metrics is asking for it. So I have to use memory for logits which is not even used. Is there any other workaround with this? This just waste memory for no reason.
mik8142 commentedon Jan 18, 2025
Hello! Can you show how you calculate BLEU without logits?
In previous versions of unsloth (~2024.*) compute metrics works for me without os.environ["UNSLOTH_RETURN_LOGITS"] = "1" may be it helps you
kesimeg commentedon Jan 18, 2025
Hello! I unfortunately don't have any code but theoretically you just need the output tokens for BLEU. You can even calculate it using strings : https://www.nltk.org/api/nltk.translate.bleu . I will try the older version. Thank you for the suggestion! The problem is putting BLEU score doesn't need logits and putting it into memory during training and evaluation just wastes resources for no reason. (Also increase the training time)
[-]Error on compute_metrics with unsloth-llama3.2[/-][+]BLEU Score[/+]danielhanchen commentedon Jan 19, 2025
I could try adding BLEU into Unsloth, but I'll have to investigate it more. Sadly a temporary solution is to enable logits output (which yes sadly uses more VRAM)
Ie putting at the start:
@mik8142 Yes correct - we actually have some code for less memory usage for eval loops - https://github.com/unslothai/unsloth/wiki#evaluation-loop---also-fixes-oom-or-crashing
kesimeg commentedon Jan 19, 2025
Thank you for your response, I think there is a misunderstanding. I checked the BLEU score implementation of Huggingface again. It actually works on strings so it doesn't need logits.
You can check the original BLEU example from here: https://github.com/huggingface/evaluate/blob/main/metrics/bleu/README.md .
So there is no problem with BLEU. The problem is compute_metrics requires logits currently. I don't have much experience in training models with unsloth or transformers, I have mostly used native pytorch. But to my understanding if we can use compute_metrics without logits the problem will be solved. Also the same logic applies to other metrics such as ROUGE or METEOR.
Joe02exe commentedon Jan 20, 2025
You could also add the
preprocess_logits_for_metricsfunction which saves a lot of memory:Additionally you will need to set the function when creating the trainer (same as for the
compute_metrics- function):mik8142 commentedon Jan 21, 2025
When i try to turn off UNSLOTH_RETURN_LOGITS
On eval step, i get these error:
TypeError: Unsupported types (<class 'unsloth.models._utils.EmptyLogits'>) passed to_pad_across_processes. Only nested list/tuple/dicts of objects that are valid foris_torch_tensorshould be passed.I try to add preprocess_logits_for_metrics from @Joe02exe post, but nothing change.
Am I correct in understanding that there is currently no way to use compute_metrics without UNSLOTH_RETURN_LOGITS=1?
Joe02exe commentedon Jan 21, 2025
You will need to set
os.environ["UNSLOTH_RETURN_LOGITS"] = "1", thepreprocess_logits_for_metrics-function is just there so that you don't store too much tensors and run out of memory.philmas commentedon Jul 15, 2025
I am confused on what is the final solutoin to problem. I am running into the same issue, none of the above has helped me resolving this issue:
davidsvaughn commentedon Jul 15, 2025
None of the above helped me either, but this finally worked for me:
The
UNSLOTH_RETURN_LOGITS="1"wasn't getting picked up inside the unsloth compiled module (in my caseunsloth_compiled_module_phi3.py) until I setUNSLOTH_COMPILE_DISABLE="1". I guess the compilation process was somehow wiping out my environment vars.BTW, this is related to a "breaking" change discussed here. The clue was the first part of this error msg:
Another solution is just rolling back to earlier Unsloth version (pre-2024.11, discussed here), but that wasn't an option for me, since that broke other things, and also I wanted to use phi-4 which wasn't available then.
Hope that helps!
rolandtannous commentedon Jul 17, 2025
@davidsvaughn UNSLOTH_COMPILE_DISABLE fully disables compilation in unsloth and should not be a default mode of usage since unsloth is an optimization finetuning framework. You're getting the logits but losing the optimizations. Definitely not a fix but I see why you did that.
davidsvaughn commentedon Jul 17, 2025
@rolandtannous I totally agree this is not a "fix"... more of a "hack"...
to paraphrase Winston Churchill, it's actually a horrible solution... except for all the others I've tried. ;)
It's the only way I could get my custom
compute_metricsfunction to work in theSFTTrainer(when using phi-3 based models), so I just thought it might help others. The "right" way to fix this is to figure out why theUNSLOTH_RETURN_LOGITSenvironment variable is getting reset to'0'inside unsloth compiled modules and solve that. I tried (for a while) to figure that out, but couldn't. If I do, I'll definitely submit a PR. If somebody else figures it out, hopefully they will do the same.supreme-gg-gg commentedon Aug 3, 2025
This happened to me on Gemma3 as well:
Would appreciate if the team can provide an official solution anytime since reverting to old version isn't very feasible for Gemma3. My
compute_metricsfunction is pretty much doing the same thing as the OP using theevaluatelibrarySetting
os.environ["UNSLOTH_RETURN_LOGITS"] = "1"alone somehow has no effect unlessos.environ["UNSLOTH_COMPILE_DISABLE"] = "1"is also set. However it ends up using a lot of VRAM (I was on colab)Akhilrajeevp commentedon Oct 7, 2025
Hey Did you find any solution for this?
danielhanchen commentedon Oct 7, 2025
Oh my I totally forgot about this sorry - will re-prioritize sorry!
Akhilrajeevp commentedon Oct 7, 2025
TypeError: Unsupported types (<class 'unsloth_compiled_module_gemma3.EmptyLogits'>) passed to
_pad_across_processes. Only nested list/tuple/dicts of objects that are valid foris_torch_tensorshould be passed.I am getting a similar issue and there is no patch or fix available even after 2 months. Guess will have to train without ROGUE metrics and evaluate it seperately for now
thewh1teagle commentedon Oct 17, 2025
Any update? should I just update the unsloth package version?
Trying to use the metrics for getting WER/CER during Gemma3 fine tune
Akhilrajeevp commentedon Oct 17, 2025
I don't think that will work, unsloth is not allowing any kind of custom metrics
steveepreston commentedon Oct 24, 2025
Can someone please attach a Causal fine-tuning that contains a
compute_metricsto calculate BLEU/Accuracy/f1?Because as i know, there is a related open issue about
compute_metricsin SFTTrainer: huggingface/trl#862danielhanchen commentedon Jul 14, 2026
This should be fixed now - sorry on the delay - please update with
uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir- if it's not fixed yet, it'll be in the next pip / PyPI release - if it's still not working after that, please open another issue - appreciate it again!The accelerate _pad_across_processes crash on EmptyLogits is now patched at import, so padded multi-process runs no longer error.