Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/twinkle/loss/chunked_cross_entropy.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ def backward(ctx, grad_output):
scale = grad_output

n = logits.shape[0]
# Write gradients in-place into logits to avoid allocating a
# second [N, V] tensor (halves peak backward memory).
# Gradients go to a fresh buffer: ``logits`` is the model output the caller
# keeps (train metrics such as Accuracy read it after backward), so it must not
# be overwritten. Only one chunk's fp32 log_softmax is ever live.
grad_logits = torch.empty_like(logits)
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
logits_chunk = logits[start:end].detach().requires_grad_(True)
Expand All @@ -90,10 +92,10 @@ def backward(ctx, grad_output):
loss_chunk = (per_token * mask).sum()

grad_chunk = torch.autograd.grad(loss_chunk, logits_chunk, retain_graph=False)[0]
logits.data[start:end] = grad_chunk * scale
grad_logits[start:end] = grad_chunk * scale

# logits, labels, chunk_size, ignore_index, reduction, dft
return logits, None, None, None, None, None
return grad_logits, None, None, None, None, None

_CHUNKED_CE_FUNC = _ChunkedCrossEntropyFunc
return _CHUNKED_CE_FUNC
Expand Down
19 changes: 19 additions & 0 deletions tests/loss/test_ce_mse.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ def test_chunked_dft(self):
result = chunked({'labels': labels}, {'logits': logits})
assert result['loss'].item() >= 0

@pytest.mark.parametrize('reduction,dft', [('mean', False), ('sum', False), ('mean', True)])
def test_chunked_backward_keeps_logits(self, reduction, dft):
"""Backward matches standard CE and leaves the logits (read by train metrics) intact."""
torch.manual_seed(0)
labels = torch.tensor([[1, -100, 4, 2, 0, -100, 3]])
leaf = torch.randn(1, 7, 6, requires_grad=True)

def run(loss_fn):
leaf.grad = None
logits = leaf * 1.0 # non-leaf model output, as returned by lm_head
loss_fn({'labels': labels}, {'logits': logits})['loss'].backward()
return logits.detach(), leaf.grad.clone()

ref_logits, ref_grad = run(CrossEntropyLoss(reduction=reduction, dft=dft))
logits, grad = run(ChunkedCrossEntropyLoss(chunk_size=3, reduction=reduction, dft=dft))

torch.testing.assert_close(grad, ref_grad)
torch.testing.assert_close(logits, ref_logits)

def test_chunked_invalid_chunk_size(self):
with pytest.raises(AssertionError):
ChunkedCrossEntropyLoss(chunk_size=0)
Expand Down
Loading