Skip to content
Closed
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
9 changes: 6 additions & 3 deletions src/accelerate/accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2840,9 +2840,12 @@ def backward(self, loss, **kwargs):
"""
learning_rate = kwargs.get("learning_rate")

if self.distributed_type != DistributedType.DEEPSPEED:
# deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
loss = loss / self.gradient_accumulation_steps
# Scale loss by gradient_accumulation_steps for all backends
# Note: DeepSpeed does NOT automatically scale loss during backward for all ZeRO stages,
# particularly ZeRO-2 where gradient partitioning can cause incorrect accumulation
# if the loss is not pre-scaled. This ensures consistent behavior across all ZeRO stages.
loss = loss / self.gradient_accumulation_steps
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure the issue isn't somewhere else?

You can see this is already done here:
https://github.com/deepspeedai/DeepSpeed/blob/b00b75f05852e0791f1e2b9c1cc894cd690e2da4/deepspeed/runtime/engine.py#L2482

and grads are scaled here:
https://github.com/deepspeedai/DeepSpeed/blob/b00b75f05852e0791f1e2b9c1cc894cd690e2da4/deepspeed/runtime/engine.py#L2360

so I suspect the above change is likely to break things, no?

cc: @tjruwase to double check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes agree! i was just wanted to test things... reverting


if self.distributed_type == DistributedType.DEEPSPEED:
self.deepspeed_engine_wrapped.backward(loss, sync_gradients=self.sync_gradients, **kwargs)
elif self.distributed_type == DistributedType.MEGATRON_LM:
Expand Down
Loading