Skip to content

fix(loss): keep the logits intact in the chunked CE backward - #334

Merged
tastelikefeet merged 1 commit into
modelscope:mainfrom
flyingdoubleG:fix/chunked-ce-keep-logits
Oct 26, 2026
Merged

tastelikefeet merged 1 commit into
modelscope:mainfrom
flyingdoubleG:fix/chunked-ce-keep-logits

Conversation

@flyingdoubleG

Copy link
Copy Markdown
Contributor

PR type

  • Bug Fix
  • New Feature
  • Document Updates
  • More Models or Datasets Support

PR information

Problem. The backward of ChunkedCrossEntropyLoss writes the gradient into the input logits and returns that tensor:

logits.data[start:end] = grad_chunk * scale
...
return logits, None, None, None, None, None

logits is a view of outputs['logits'], the model output that TransformersModel.forward stores in train_status.outputs and returns to the caller. After backward(), that tensor holds d(loss)/d(logits) instead of the logits. The write goes through .data, so autograd's version counter cannot catch it.

Visible effect. Accuracy is one of the default train metrics. It is accumulated by accumulate_metrics(True) at the start of the next forward, after the previous backward, and it takes argmax over outputs['logits']. At the label the gradient is (p_y - 1) * scale < 0, while every other token gets p_j * scale > 0. The argmax therefore never hits the label, and the reported token accuracy collapses to about 0 for any run using chunked_cross_entropy. The logits returned by forward_backward are corrupted the same way.

Reproduction (CPU), with logits that predict every label:

logits unchanged after backward: False
token accuracy before backward: 1.0  after backward: 0.0

Fix. Write the gradient into a fresh buffer (torch.empty_like(logits)), which is what the class docstring already describes ("writes per-token gradients into a freshly allocated grad_logits tensor (the input logits is never mutated)").

Memory: chunking still only keeps one chunk's fp32 log_softmax alive, which is where its saving over CrossEntropyLoss comes from. The extra [N, V] buffer is the same size as the gradient that CrossEntropyLoss itself produces.

Experiment results

New test test_chunked_backward_keeps_logits, parametrized over mean, sum and dft, checks two things:

  • the input gradient matches CrossEntropyLoss;
  • the logits are unchanged after backward.

All 3 cases fail on main. tests/loss/test_ce_mse.py passes with the fix (21 tests, CPU).

🤖 Generated with Claude Code

ChunkedCrossEntropyLoss's backward wrote the gradient into `logits.data`
and returned it, so after backward the model output kept in
train_status.outputs held d(loss)/d(logits) instead of the logits. The
Accuracy train metric (enabled by default) takes argmax over those
values at the start of the next step; at the label the gradient is
(p_y - 1) * scale < 0, so the reported token accuracy collapses to ~0.
The logits returned from forward_backward were corrupted the same way.

Write the gradient to a fresh buffer, as the class docstring already
says. Only one chunk's fp32 log_softmax is live at a time, so the
memory saving of chunking is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@tastelikefeet
tastelikefeet merged commit 5337cc3 into modelscope:main Oct 26, 2026
2 of 3 checks passed
tastelikefeet added a commit that referenced this pull request Nov 28, 2026
main carried 17 commits (#311..#291) over merge-base 96dab68. v5 had already ported
everything up to #312 (a4ddc3b) and moved server/client to twinkle_cs, so:

- server/client (src/twinkle/server, twinkle_cs/*, tests/server, tests/twinkle_client):
  kept the v5 tree; the legacy src/twinkle/server path and the old ci_container_test.sh
  stay removed on v5.
- loss: #291 detached DFT weights, #335 Liger CE contract (delegates micro_batch_scale /
  batch_normalizer to CrossEntropyLoss), #334 chunked CE comments, #336 InfoNCE tests.
- model: #343 Torch.empty_cache (auto-merged), #385 fused_lm_rl ported onto the v5 task
  registry (processor/tasks.py + model/tasks.py FusedRL + transformers postprocess),
  #386 NPU fused CE fast path in selective_log_softmax.
- twinkle_agentic: #345 check kinds (hidden_python / sql_query / answer_one_of /
  answer_number / web_receipt / lean) adapted to the episode-scoped Env interface;
  AgenticChallenger gains the _verify_check / _proposal_reward hooks.

Known: cookbook/rsi and tests/cookbook/rsi (#345) are written against main's stateless
Env / AgenticChallenger API and do not run on v5 yet.
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.

2 participants