Skip to content

Keep a user-set UNSLOTH_RETURN_LOGITS=1 across trainer.train() - #13311

Merged
danielhanchen merged 4 commits into
mainfrom
fix-3071-keep-user-return-logits
Oct 12, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix-3071-keep-user-return-logits

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Fixes #3071

Setting os.environ["UNSLOTH_RETURN_LOGITS"] = "1" did not survive trainer.train(). The trainer's __init__ and its train() wrapper both call model.for_training(), and FastBaseModel.for_training() (the path every FastModel / FastVisionModel and, through the inner model, FastLanguageModel checkpoints take) unconditionally set the flag back to "0". So a compute_loss or compute_metrics that reads logits got EmptyLogits and the run stopped with NotImplementedError: Unsloth: Logits are empty from 2024.11 onwards ... set UNSLOTH_RETURN_LOGITS to "1", even though it was set.

The "0" was only ever meant to undo the "1" that for_inference() forces for generation.

Changes

  • for_inference() records the value its forced "1" replaced (only when the flag was not already "1").
  • for_training() puts that recorded value back. With no record it keeps the current value, still defaulting an unset flag to "0" as before.
  • The generated trainer __init__ ends with a mode-only for_inference() call: it now leaves UNSLOTH_RETURN_LOGITS and the record as it found them, so a flag set after building the trainer and before train() (what the error message tells users to do) also holds.
  • The UNSLOTH_RETURN_LOGITS=1 the trainer __init__ sets for compute_metrics / preprocess_logits_for_metrics is recorded the same way, so for_training() still clears it as before: training stays on the fused CE path and eval logits keep coming from prediction_step.
  • The train() wrapper's restore of eval mode after a run is treated the same way, so a flag set between two train() calls on the same trainer also holds.

Users who never set the flag see the same values as before at every training step: training still runs on the fused CE path, and generation still forces logits on.

Evidence

Tiny checkpoints, one fresh process per cell, base = main at fc5cf50, head = 4a852c2, both arms on the same unsloth_zoo main. compute_loss reads outputs.logits (the reproducer from the issue). Expected: logits are real tensors when the flag is set, and the fused CE path (EmptyLogits, flag "0") when it is not.

Scenario Gemma3 main Gemma3 PR Qwen3 main Qwen3 PR
flag set before import unsloth NotImplementedError logits NotImplementedError logits
flag set after building the trainer, before train() NotImplementedError logits NotImplementedError logits
train once without the flag, set it, train() again NotImplementedError logits NotImplementedError logits
flag never set, compute_metrics eval every 2 steps fused CE, metrics ran fused CE, metrics ran fused CE, metrics ran fused CE, metrics ran
flag set, compute_metrics eval every 2 steps NotImplementedError logits, metrics ran NotImplementedError logits, metrics ran
flag never set fused CE fused CE fused CE fused CE
flag never set, model.generate() before training fused CE fused CE fused CE fused CE

In the two flag-never-set rows the per-step losses are identical on both arms (Gemma3 24.81, 24.77, 24.71; Qwen3 23.86, 23.86, 23.85) and padding-free is chosen the same way.

New tests/test_return_logits_survives_for_training.py: 3 tests fail on main and pass here (user flag kept through the trainer's for_training / for_inference / for_training cycle, the trainer __init__ not arming a restore of "0", and a flag set between two train() calls); a compute_metrics test guards the auto-set flag being cleared at train time; 3 controls pass on both (generation's "1" is still undone, repeated for_inference() keeps the first saved value, an unset flag still becomes "0").

Known limit

for_inference() (also run by generate()) still forces the flag to "1". If a user calls it, then sets "1" themselves and trains, the two writes look the same, so the first train() restores the value from before generation. On main the flag is reset on every train(); here, setting it again after that first run makes it hold. Separately, a labeled forward after train() without for_inference() now gets the EmptyLogits message (setting the flag works) instead of logits that the trainer's own mode restore used to turn on.

for_training() forced UNSLOTH_RETURN_LOGITS to 0, and both the trainer __init__
and train() call it, so a flag set before training was gone by the first step and
compute_loss / compute_metrics got EmptyLogits. for_inference() now records the
value its forced 1 replaced and for_training() puts that back, and the trainer
__init__'s trailing for_inference() leaves the flag as it found it.

Fixes #3071
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-11T10:43:44.471819Z 896cd86 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T11:32:40.772158Z 4a852c2 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6287df84ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/vision.py

os.environ["UNSLOTH_RETURN_LOGITS"] = "0"
# Undo only for_inference()'s "1": forcing "0" here wiped a user's UNSLOTH_RETURN_LOGITS=1 (#3071).
_return_logits = os.environ.pop("_UNSLOTH_RETURN_LOGITS_BEFORE_INFERENCE", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor a logits override after restoring inference mode

When the same trainer is trained twice, prepare_for_training_mode restores its original inference mode after the first run, so for_inference() leaves this marker set to "0" while forcing the public flag to "1". If the user then follows the documented instruction and assigns UNSLOTH_RETURN_LOGITS="1" before the second trainer.train(), this pop() still restores the stale "0", causing the second run to return EmptyLogits instead of the requested logits. The restoration state must not override an explicit setting made between training runs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f3e3792: the train() wrapper's post-run for_inference() is now a mode switch only, so a flag set before the second train() is kept; covered by test_flag_set_between_two_train_calls_is_kept and a two-run GPU check on tiny Gemma3 and Qwen3.

The train() wrapper puts a model that was in eval mode back with for_inference(),
which recorded the training-time value and forced 1. A UNSLOTH_RETURN_LOGITS=1 set
before the next train() then lost to that stale record. Treat this restore as a mode
switch only, like the one at the end of the trainer __init__.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3e37929d1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/vision.py
Comment on lines +5052 to +5055
_return_logits = os.environ.pop("_UNSLOTH_RETURN_LOGITS_BEFORE_INFERENCE", None)
if _return_logits is None:
_return_logits = os.environ.get("UNSLOTH_RETURN_LOGITS", "0")
os.environ["UNSLOTH_RETURN_LOGITS"] = _return_logits

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve an explicit flag set after direct inference

When model.generate() or a direct model.for_inference() occurs before training, unsloth_base_fast_generate calls FastBaseModel.for_inference() (vision.py:1702), which records the old "0"; if the user then follows the documented guidance and sets UNSLOTH_RETURN_LOGITS="1" immediately before trainer.train(), this pop() restores the stale "0" and training still receives EmptyLogits. Fresh evidence beyond the resolved two-train case is that direct generation bypasses the new mode-only snapshots in rl.py, so an explicit current value must take precedence over this saved marker.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known limit, not fixable through the env var: after for_inference() forced "1", a user writing "1" is a no-op, so nothing can tell the two apart. The PR still improves this path: on main the flag is reset on every train(), here the first train() restores the pre-generation value and a re-set flag then holds. Telling them apart needs a channel other than UNSLOTH_RETURN_LOGITS in the compiled forwards, which is out of scope for this fix.

Comment thread unsloth/models/rl.py
Comment on lines +494 to +498
_logits_env = [(_k, os.environ.get(_k)) for _k in ("UNSLOTH_RETURN_LOGITS", "_UNSLOTH_RETURN_LOGITS_BEFORE_INFERENCE")]
self.model.for_inference()
for _k, _v in _logits_env:
if _v is None: os.environ.pop(_k, None)
else: os.environ[_k] = _v

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep logits enabled when restoring inference mode

When the trainer entered train() in eval mode—which is the normal state established by the generated trainer constructor—this block calls for_inference() after training but immediately restores the training-time UNSLOTH_RETURN_LOGITS="0". The model is therefore left in inference/eval mode while a direct trainer.model(...) call returns EmptyLogits, whereas before this change the same post-training for_inference() enabled real logits; the analogous snapshot in __init__ also creates this inconsistent state immediately after trainer construction.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional. A "1" left behind by the trainer's own mode restore is indistinguishable from a user's "1", and leaving it is exactly what made the documented "set it before trainer.train()" advice a no-op (#3071). A labeled forward after train() now gets the EmptyLogits message, and its instruction works; generate(), an explicit for_inference() and trainer.evaluate() with compute_metrics still turn logits on, and loss-only eval stays on the fused path as #1801 intended.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3e37929d1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/vision.py
Comment on lines +5053 to +5055
if _return_logits is None:
_return_logits = os.environ.get("UNSLOTH_RETURN_LOGITS", "0")
os.environ["UNSLOTH_RETURN_LOGITS"] = _return_logits

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope automatically enabled logits to the requesting trainer

When a generated trainer is constructed with compute_metrics or preprocess_logits_for_metrics, unsloth/models/rl.py:2515-2519 automatically sets UNSLOTH_RETURN_LOGITS=1; this fallback now treats that internal setting as permanent, with no cleanup when the trainer finishes. If another trainer without metrics is subsequently constructed in the same process, unsloth/trainer.py:1619 sees the leaked flag, disables packing/padding-free, and makes training materialize full vocabulary logits unnecessarily, which can cause a major slowdown or OOM. Track or restore trainer-generated settings separately so only an explicit user setting persists across unrelated trainers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4a852c2: the compute_metrics / preprocess_logits_for_metrics write is recorded like for_inference()'s, so for_training() undoes it as main did. Training stays on the fused CE path (tiny Gemma3 and Qwen3, flag unset + compute_metrics: EmptyLogits during training, metrics still get full logits, flag back to 0 after train), covered by test_compute_metrics_auto_flag_does_not_outlive_the_trainer_init.

The generated __init__ sets UNSLOTH_RETURN_LOGITS=1 when compute_metrics or
preprocess_logits_for_metrics is given, and for_training() used to clear it. Record
that write like for_inference()'s so for_training() still undoes it: training stays on
the fused CE path and the next trainer's packing / padding-free gate does not see a
leaked 1. Eval logits keep coming from prediction_step.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 4a852c22c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] os.environ["UNSLOTH_RETURN_LOGITS"] = "1" becomes unset to "0" once I start to train

1 participant