Repository navigation
Keep loss-only evaluation on the fused CE path instead of materializing logits - #13065
Merged
Merged
Conversation
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. |
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
danielhanchen
added a commit
to unslothai/unsloth-zoo
that referenced
this pull request
Oct 16, 2026
## Summary Avoid computing hidden-state and output-head gradients when `unsloth_fused_ce_loss` runs under `torch.no_grad()` or `torch.inference_mode()`. Previously, evaluation still called `torch.func.grad_and_value` for every chunk, including weight gradients when the output head retained `requires_grad=True`. Capture grad mode before entering the autograd function, then reuse the existing chunk loss, label shifting, normalization, and compilation/fallback handling without allocating or saving gradient buffers. Grad-enabled calls keep the existing differentiation path. Checking grad mode inside `autograd.Function.forward` would incorrectly disable training gradients because that method itself runs with grad recording disabled. Evaluation also leaves hidden states untouched when `overwrite=True`. This applies to the chunked Zoo fused CE path, including loss-only evaluation routed through it by unslothai/unsloth#13065. It does not change the separate Cut Cross Entropy backend or the public loss wrapper signature. ## Performance Same-device comparison of baseline `fc69dd2a0945f67f3ab551eca10d3577a4b8680a` and candidate `939c96c`: RTX A1000 Laptop GPU, PyTorch 2.13.0+cu130, Triton 3.7.1, BF16, hidden states `[1, 2048, 512]`, vocabulary 8192, four chunks, no head bias. Both calls run under `no_grad()`. Compilation is excluded; three warmups followed by seven ABBA rounds, three calls per CUDA-event sample, medians of fourteen samples per implementation. “Compiled” means the fused loss's chunk compilation is enabled and verified to succeed. | Mode | Output head | Before (ms) | After (ms) | Matrix multiplies | | --- | --- | ---: | ---: | ---: | | Eager | Frozen | 4.695 | 2.174 | 8 → 4 | | Eager | Trainable | 5.855 | 2.119 | 12 → 4 | | Compiled | Frozen | 2.553 | 1.396 | 8 → 4 | | Compiled | Trainable | 3.862 | 1.429 | 12 → 4 | Losses are bitwise equal in all four comparisons. The compiled trainable-head case's incremental peak allocated memory falls from 26.0 MiB to 8.0 MiB. These measurements cover the loss call; whole-model evaluation throughput and training-step speedups are not claimed. ## Validation - 96 CPU/CUDA evaluation cases passed across FP32/FP16/BF16, `no_grad`/`inference_mode`, overwrite on/off, frozen/trainable heads and biases, masked labels, explicit shifts, loss scaling, softcapping, label smoothing, and all-ignored labels. Losses match baseline exactly; evaluation never calls `grad_and_value` or modifies hidden states. - 34 training checks passed: loss and gradients match baseline exactly and agree with ordinary PyTorch CE references, including trainable/frozen head and bias combinations, overwrite, and the existing zero-scaling backward behavior. - Compiled chunk train → eval → train transitions passed for frozen and trainable heads. Compile-probe fallback and four automatic chunk-budget controls passed. - Existing repository tests on PyTorch 2.12.1+cu130: **30 passed**, including the compiled-gradient regression. Command: `python -m pytest -q tests/test_ce_all_masked_labels.py tests/test_cross_entropy_chunk_cap.py tests/test_fused_ce_no_per_call_signature.py tests/test_fused_loss_inplace_add.py tests/test_fused_ce_compiled_gradient.py`. - Syntax/undefined-name lint and `git diff --check` passed. Focused standalone checks and paired benchmarks load the actual baseline/candidate CE source, isolating unrelated package initialization; all tensor operations and autograd run in real PyTorch. Those scripts are kept outside the repository, so this PR contains production code only. The full repository suite was not run. An additional outer `torch.compile(fullgraph=True)` training check with a trainable biased head reproduces the same `Expected FakeTensor, got torch.Tensor` assertion on baseline and candidate in PyTorch 2.13. That existing outer-compilation limitation is not addressed here. --------- Co-authored-by: Daniel Han <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1801
Problem
Evaluation during training (
eval_strategy="steps"or"epoch"with aneval_dataset) uses far more VRAM than training and can OOM on long sequences. Unsloth'sTrainer.prediction_stepsetsUNSLOTH_RETURN_LOGITS=1for every eval batch, so each batch materializes the full[batch, seq_len, vocab]logits even when the trainer only wants the loss (prediction_loss_only=True, the default when nocompute_metricsis passed) and throws the logits away right after.Training never builds those logits: it uses the fused cross entropy path. With long sequences and large vocabularies (Phi-4 100k, Qwen 152k) a single eval batch of logits is several GB.
Fix
Only force
UNSLOTH_RETURN_LOGITS=1inprediction_stepwhen the logits are kept (compute_metrics,trainer.predict()). A loss-only eval now runs the same forward and fused loss as a training step. The caller's previous value is still restored afterwards, and an explicitUNSLOTH_RETURN_LOGITS=1set by the user is left alone.Evidence
unsloth/Qwen2.5-0.5B-Instruct, 4-bit LoRA, ~7.4k token rows,per_device_train_batch_size=2,per_device_eval_batch_size=2,gradient_accumulation_steps=4,eval_strategy="steps",eval_steps=1, peaktorch.cuda.max_memory_allocatedper phase:Other families, 3.7k token rows, same settings, B200 (in-training eval peak, step 1 eval loss):
Step 2 eval losses differ between repeated main runs by about as much as main vs this PR, so the loss is unchanged within run-to-run noise.
With
compute_metrics+preprocess_logits_for_metricsthe logits are still produced and passed through (predictions shape[4, 14747]on both main and this PR), so metric users see no change.The "does not accept
num_items_in_batch" message from the issue title no longer fires during eval on main (eval now passesnum_items_in_batch); it was a side note, the VRAM was the logits.Not changed here: a standalone
trainer.evaluate()called outsidetrain()still produces logits, becausefor_inference()(run at the end oftrain()and trainer init) setsUNSLOTH_RETURN_LOGITS=1, which is indistinguishable from a user opt-in at that point. Settingos.environ["UNSLOTH_RETURN_LOGITS"] = "0"before such a call keeps it on the fused path.Tests
tests/test_eval_step_restores_return_logits.pynow covers bothprediction_loss_onlyvalues: a loss-only step must not flip the variable, a step that keeps logits still forces it, and both restore the caller's value. The two loss-only cells fail on main and pass here.