[BUG] TiledFusedLogitsLoss ignores external loss scaling for head gradients

Aperta
#9,087 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

@taking-lying-flat ci sta già lavorando.

Dal 16/11/2026.

  • #9096 di @taking-lying-flat — aperta

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python, pytorch

Direzione di ricerca

Start in deepspeed/runtime/sequence_parallel/ulysses_sp.py: read TiledFusedLogitsLoss.forward and its backward, then compare with SequenceTiledCompute's deferred-gradient path. Run the issue's repro.py under CPU FP64 to confirm the 11x head-gradient ratio and the loss * 0 and 1/4-scaling controls. Done means head parameter gradients match the reference for output_reduction="sum" with token normalization while loss and hidden gradients stay correct; the ZeRO-hook interaction still needs maintainer input.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

TiledFusedLogitsLoss silently produces incorrectly scaled LM-head gradients when its returned loss is normalized or weighted. The loss value and hidden-state gradients remain correct. This includes the documented output_reduction="sum" followed by valid-token normalization.

System info

DeepSpeed master 7caa7a2267bc5 (0.20.1 source), Python 3.12.13, PyTorch 2.13.0+cu130; Linux, CPU FP64. Direct Python, without a distributed launcher. ds_report confirms the source checkout and no compiled DeepSpeed ops.

Minimal reproduction

Run against that checkout with DS_ACCELERATOR=cpu PYTHONPATH=. python repro.py:

import copy
import torch
import torch.nn.functional as F
from deepspeed.runtime.sequence_parallel.ulysses_sp import TiledFusedLogitsLoss

torch.manual_seed(0)
torch.set_num_threads(1)
head = torch.nn.Linear(4, 5, bias=False).double()
ref_head = copy.deepcopy(head)
x = torch.randn(2, 7, 4, dtype=torch.float64, requires_grad=True)
ref_x = x.detach().clone().requires_grad_()
y = torch.tensor([[0, 1, -100, 2, 3, 4, 0], [1, 2, 3, -100, 4, 0, -100]])

def ce_sum(model, hidden, labels):
    logits = model(hidden)
    return F.cross_entropy(logits.reshape(-1, 5), labels.reshape(-1), reduction="sum")

n = (y != -100).sum()  # 11 valid tokens, uneven tiles
loss = TiledFusedLogitsLoss.apply(ce_sum, head, x, y, None, 3, list(head.parameters()), "sum") / n
ref_loss = ce_sum(ref_head, ref_x, y) / n
loss.backward()
ref_loss.backward()

print("loss error:", (loss - ref_loss).abs().item())
print("hidden gradient error:", (x.grad - ref_x.grad).abs().max().item())
print("head gradient norm ratio:", (head.weight.grad.norm() / ref_head.weight.grad.norm()).item())
torch.testing.assert_close(head.weight.grad, ref_head.weight.grad)

Actual output:

loss error: 0.0
hidden gradient error: 1.0408340855860843e-17
head gradient norm ratio: 10.999999999999996
AssertionError: Tensor-likes are not close!
Mismatched elements: 20 / 20 (100.0%)

The assertion exposes a silent training error; the loss computation itself does not raise. The expected head-gradient ratio is 1, but it is 11, the valid-token count.

Root cause

Forward uses a synthetic incoming gradient of 1 and calls backward inside each tile's forward, already accumulating the head's parameter gradients. When the real upstream gradient arrives, backward only scales the saved hidden gradient.

For J = alpha * L, the head therefore receives dL/dW instead of alpha * dL/dW.

I also reproduced nonzero head gradients for loss * 0, and head gradients 4× the reference after four microbatches each scaled by 1/4. The unscaled control passes. These are local autograd tests; full ZeRO/distributed and AMP training were not run.

Suggested fix

Defer each tile's gradient computation to backward so both hidden and parameter gradients use the actual upstream gradient, following SequenceTiledCompute. Its sum-reduction path matches the reference in all six CPU checks. This requires recomputing tiles; throughput was not measured. Multiplying param.grad afterward would also rescale contributions already accumulated from other calls.

Related PR #8960 fixes in-place mutation of an incoming gradient in SequenceTiledCompute; this is a different root cause.

I would appreciate the maintainers' feedback on this fix direction, particularly its interaction with ZeRO hooks.

Lingua principale
Python
Stelle
43.3k
Fork
5.1k
Merge medio
5g 10h
PR unite (30g)
85

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di deepspeedai/DeepSpeed

Tutte le issue di deepspeedai/DeepSpeed

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.