[BUG] TiledFusedLogitsLoss ignores external loss scaling for head gradients

Abierto
#9,087 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

@taking-lying-flat ya está trabajando en esto.

Desde el 16/11/2026.

  • #9096 de @taking-lying-flat — abierto

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, pytorch

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Python
Estrellas
43.3k
Forks
5.1k
Merge medio
5 d 10 h
PR fusionados (30 d)
85

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de deepspeedai/DeepSpeed

Todos los issues de deepspeedai/DeepSpeed

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.