Skip to content

Keep loss-only evaluation on the fused CE path instead of materializing logits - #13065

Merged
danielhanchen merged 1 commit into
mainfrom
fix-1801-eval-loss-only-logits
Oct 8, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
fix-1801-eval-loss-only-logits

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Fixes #1801

Problem

Evaluation during training (eval_strategy="steps" or "epoch" with an eval_dataset) uses far more VRAM than training and can OOM on long sequences. Unsloth's Trainer.prediction_step sets UNSLOTH_RETURN_LOGITS=1 for 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 no compute_metrics is 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=1 in prediction_step when 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 explicit UNSLOTH_RETURN_LOGITS=1 set 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, peak torch.cuda.max_memory_allocated per phase:

Run Train step peak In-training eval peak Eval loss (step 1, step 2)
unsloth 2025.2.15 (issue's version), L4 1.42 GB 14.21 GB n/a (different stack)
main, B200 1.53 GB 13.21 GB 0.0148602, 0.0127345
this PR, B200 1.53 GB 1.44 GB 0.0148602, 0.0127437
main, L4 (two runs) 1.50 GB 13.16 GB 0.0148487, 0.0127191 / 0.0127389
this PR, L4 (two runs) 1.50 GB 1.39 GB 0.0148488, 0.0127228 / 0.0127343

Other families, 3.7k token rows, same settings, B200 (in-training eval peak, step 1 eval loss):

Model Train step peak Eval peak main Eval peak this PR Step 1 eval loss main / this PR
Llama-3.2-1B-Instruct 2.34 GB 6.56 GB 2.21 GB 0.039668 / 0.039668
Qwen3-0.6B 1.34 GB 6.97 GB 1.26 GB 0.032005 / 0.032005
gemma-3-270m-it (compiled forward) 1.55 GB 11.28 GB 1.62 GB 0.185242 / 0.185243

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_metrics the 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 passes num_items_in_batch); it was a side note, the VRAM was the logits.

Not changed here: a standalone trainer.evaluate() called outside train() still produces logits, because for_inference() (run at the end of train() and trainer init) sets UNSLOTH_RETURN_LOGITS=1, which is indistinguishable from a user opt-in at that point. Setting os.environ["UNSLOTH_RETURN_LOGITS"] = "0" before such a call keeps it on the fused path.

Tests

tests/test_eval_step_restores_return_logits.py now covers both prediction_loss_only values: 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.

@danielhanchen danielhanchen self-assigned this Oct 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 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-08T13:18:47.313788Z 2ffcc32 Manual request
🔒 Security Review ⚠️ Failed 2026-10-08T13:15:16.857298Z 2ffcc32 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.

@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. You're on a roll.

Reviewed commit: 2ffcc32485

ℹ️ 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".

@danielhanchen
danielhanchen merged commit b799e4d into main Oct 8, 2026
@danielhanchen
danielhanchen deleted the fix-1801-eval-loss-only-logits branch October 8, 2026 15:47
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

VRAM spikes after "LlamaForCausalLM does not accept 'num_items_in_batch'"

1 participant