Repository navigation
Keep a user-set UNSLOTH_RETURN_LOGITS=1 across trainer.train() - #13311
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
|
|
||
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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__.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| _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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| _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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if _return_logits is None: | ||
| _return_logits = os.environ.get("UNSLOTH_RETURN_LOGITS", "0") | ||
| os.environ["UNSLOTH_RETURN_LOGITS"] = _return_logits |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Fixes #3071
Setting
os.environ["UNSLOTH_RETURN_LOGITS"] = "1"did not survivetrainer.train(). The trainer's__init__and itstrain()wrapper both callmodel.for_training(), andFastBaseModel.for_training()(the path everyFastModel/FastVisionModeland, through the inner model,FastLanguageModelcheckpoints take) unconditionally set the flag back to"0". So acompute_lossorcompute_metricsthat reads logits gotEmptyLogitsand the run stopped withNotImplementedError: 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"thatfor_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.__init__ends with a mode-onlyfor_inference()call: it now leavesUNSLOTH_RETURN_LOGITSand the record as it found them, so a flag set after building the trainer and beforetrain()(what the error message tells users to do) also holds.UNSLOTH_RETURN_LOGITS=1the trainer__init__sets forcompute_metrics/preprocess_logits_for_metricsis recorded the same way, sofor_training()still clears it as before: training stays on the fused CE path and eval logits keep coming fromprediction_step.train()wrapper's restore of eval mode after a run is treated the same way, so a flag set between twotrain()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 =
mainat fc5cf50, head = 4a852c2, both arms on the same unsloth_zoomain.compute_lossreadsoutputs.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.import unslothtrain()train()againcompute_metricseval every 2 stepscompute_metricseval every 2 stepsmodel.generate()before trainingIn 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 onmainand 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 twotrain()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, repeatedfor_inference()keeps the first saved value, an unset flag still becomes"0").Known limit
for_inference()(also run bygenerate()) 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 firsttrain()restores the value from before generation. Onmainthe flag is reset on everytrain(); here, setting it again after that first run makes it hold. Separately, a labeled forward aftertrain()withoutfor_inference()now gets the EmptyLogits message (setting the flag works) instead of logits that the trainer's own mode restore used to turn on.