Repository navigation
Labels
Description
Hello!
I have been working on fine tuning Gemma 3. During training, I wish to validate based on a custom metric. To mitigate the following error, I set os.environ["UNSLOTH_RETURN_LOGITS"] = "1":
TypeError: Unsupported types (<class 'unsloth_compiled_module_gemma3.EmptyLogits'>) passed to `_pad_across_processes`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.
I am using the following configuration:
config = SFTConfig(
per_device_train_batch_size=self.train_args.get("batch_size", 4),
gradient_accumulation_steps=self.train_args.get("grad_accum", 8),
gradient_checkpointing=True,
gradient_checkpointing_kwargs={"use_reentrant": False},
max_grad_norm=0.3,
warmup_ratio=0.03,
learning_rate=self.train_args.get("lr", 2e-4),
logging_steps=10,
save_strategy="steps",
save_steps=10,
eval_strategy="steps",
eval_steps=self.train_args.get("eval_steps", 10),
load_best_model_at_end=self.train_args.get("load_best_model_at_end", True),
metric_for_best_model=self.train_args.get("metric_for_best_model", "top1_accuracy"),
greater_is_better=self.train_args.get("greater_is_better", True),
optim=self.train_args.get("optim", "adamw_torch_fused"),
weight_decay=0.01,
lr_scheduler_type="cosine",
seed=self.train_args.get("seed", 3407),
output_dir=self.output_dir,
report_to="tensorboard",
run_name="gemma_4b_lora_run_2",
logging_dir="gemma_4b_lora_run_2",
# max_seq_length=20000,
remove_unused_columns=False,
dataset_text_field="",
dataset_kwargs={"skip_prepare_dataset": True},
)
trainer = SFTTrainer(
model=self.model,
predict_with_generate=True,
train_dataset=self.train_dataset,
eval_dataset=self.val_dataset,
compute_metrics=self.compute_metrics,
processing_class=self.processor.tokenizer,
data_collator=self.collator,
args=config,
)
train_output = trainer.train()
Before running training, I check if the environment variable is set correctly (and it is):

However, it seems to have changed in the process of training, and is back to being 0.

What can I do here? I saw another issue about this, but it seemed like no one found a solution.
Reacted by Steve and Niels Warncke
Activity
zaidalyafeai commentedon Jul 30, 2025
I am facing a similar issue
Sekinal commentedon Jul 31, 2025
The
os.environonly works for as long as the runtime of Python works, once it crashes, it resets back to normal. The bug, however, is that even if you set theUNSLOTH_RETURN_LOGITSas 1, Unsloth ignores it completely and doesn't return logits anyway! I've had the same issue both with Gemma 3 & Qwen3. I'm linking the full relevant error (although the problem is that anEmtpyLogitsobject is always returned no matter what):This was a bug that didn't happen in
"unsloth==2025.6.2", as I fine-tuned a model and used a custom metric to evaluate it without problems. If I remember right, setting the environment variable wasn't even a requirement and it worked out of the box.EDIT1: After some research I found that the unsloth package wasn't the issue, it's an issue with unsloth_zoo (or at least seems like it, unsloth_zoo==2025.6.2 fixes the bug when using the same unsloth version), I'm trying to find the root cause now.
EDIT2: As a temporary workaround, using
unsloth_zoo==2025.7.1withunsloth<=2025.6.5fixes the issue (not sure if it causes other issues, tho), the breaking change was at2025.7.2.EDIT3: Indeed, even having the environment variable
UNSLOTH_RETURN_LOGITS = "0"worked.davidsvaughn commentedon Jul 31, 2025
That's probably because, once you reverted to
unsloth_zoo==2025.7.1then the automated detection ofcompute_metricsstarted working again here in rl.py (which, BTW, works by setting the environment variableUNSLOTH_RETURN_LOGITS='1'whencompute_metricsis detected - so I'm guessing thatunsloth_zoo==2025.7.1allows the environment variable to persist)charvishukla-bc commentedon Jul 31, 2025
Ah! Unfortunately, that fix does not work for me!
I used the versions of

unslothandunsloth_zoothat you mentioned.Before running training, I also checked that

UNSLOTH_RETURN_LOGITS='1'However, even with this set up, I get this error:
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.Here'r my config now:
Where
compute_metricsis defined as:def compute_metrics(self, p: EvalPrediction) -> Dict[str, float]and contains custom logic for calculating accuracy.I wonder why it worked for you! What compute_metrics did you use?
davidsvaughn commentedon Jul 31, 2025
@charvishukla-bc you are welcome to try this tweak I made to unsloth-zoo...
It solved the problem for me (but I still had to manually set
UNSLOTH_RETURN_LOGITS='1'since the auto-detection of compute_metrics still isn't fixed). I would create a PR, but I'm still not satisfied with this solution... at compile time it hard-codes the user's setting of UNSLOTH_RETURN_LOGITS into the dynamically generated modules, since the environment variable method wasn't working. After that, I also had to uncomment several commented out lines for logit computation (see diff).Sekinal commentedon Aug 1, 2025
Really weird! I'll have to look into it too... if it's of any help here's the repo with all of the settings that have worked for me: https://github.com/Sekinal/neuraltranslate-en-es/tree/master
Currently using
full.pywith no issues in a B200.mmathew23 commentedon Aug 1, 2025
Hello @charvishukla-bc @zaidalyafeai, if possible to provide a script that reproduces the issue that would be greatly appreciated.
Fix UNSLOTH_RETURN_LOGITS environment variable reset in for_training()
devlup commentedon Aug 10, 2025
For me the flag is set as os.environ["UNSLOTH_RETURN_LOGITS"] = "1" but in unsloth_compiled_cache/unsloth_compiled_module_gpt_oss.py line : 725 logits were not generated and set to empty logits elif self.loss_function.name.endswith("ForCausalLMLoss") and labels is not None:
lm_head_weight = self.lm_head.weight
lm_head_bias = getattr(self.lm_head, "bias", None)
steveepreston commentedon Oct 14, 2025
Facing same issue
pluesclues commentedon Oct 22, 2025
Hello, custom evaluation and
"UNSLOTH_RETURN_LOGITS="1"should work now, please update unsloth again viapip install --upgrade --force-reinstall --no-deps unsloth_zoo unslothjrobis commentedon Oct 23, 2025
This didn't look like it fixed the issue. Running
unsloth==2025.10.9unsloth_zoo==2025.10.10pluesclues commentedon Oct 23, 2025
Hello @jrobis apologies for that, do you mind attaching a sample script? I ran a
compute_metricfunction that needed logits and it seems they were returned when I enabled the flag, I ran this for"unsloth/gemma-3n-E4B-it", with multi-modal input and just text. But, please let me know, thank you.2 remaining items
steveepreston commentedon Oct 31, 2025
@rolandtannous Man please include FSDP mode too
rolandtannous commentedon Nov 2, 2025
The container image has been updated to 2025.10.13 which should contain the fix for this issue
Please make sure to pull the latest image
Note: if you have, unsloth==2025.10.9 and unsloth_zoo==2025.10.10 in your environment, then you do not have the required fix. If you are in a local python environment
don't do this if you are using the docker container image (just pulled the latest image). The latest unsloth pypi versions are already built in.
steveepreston commentedon Nov 7, 2025
is there a basic tutorial on How to launch Unsloth docker in kaggle?
richiejp commentedon Nov 10, 2025
I seem to be still hitting this bug in 2025.11.x
richiejp commentedon Nov 11, 2025
Here is the problem
for_traininginvision.pysets it to zero.EDIT:
I'm not sure how
for_training()is getting called, it appears to be part of some generated code? But I was able to use the following workaroundsteveepreston commentedon Nov 21, 2025
Any solution?
electroglyph commentedon Mar 4, 2026
to reproduce:
Tighten the #3071 test docstring
Keep a user-set UNSLOTH_RETURN_LOGITS=1 across trainer.train() (unslo…
Give the #3071 lifted-method test the mode-switch helpers
Switch between training and inference mode in one tree walk (#13374)
danielhanchen commentedon Oct 12, 2026
Fixed! Sorry on the delay. Training was resetting
UNSLOTH_RETURN_LOGITSback to 0 when it switched the model between inference and training, so acompute_lossorcompute_metricsthat readoutputs.logitsgot empty logits even after you set the flag to 1. #13311 stopped the reset, and #13406 covers the last case (setting the flag after generating with aFastModel/FastVisionModelmodel), so your setting now survives everytrainer.train().To update:
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.Lift for_inference's tensor parallel helpers in the return-logits test (