MCPcopy Create free account
hub / github.com/deepspeedai/DeepSpeed / backward

Method backward

deepspeed/runtime/engine.py:3542–3600  ·  view source on GitHub ↗

r"""Execute backward pass on the loss Arguments: loss: Torch tensor on which to execute backward propagation retain_graph: bool, default: false forward on user defined choice of retain_graph scale_wrt_gas: bool, default: true

(self, loss, retain_graph=False, scale_wrt_gas=True)

Source from the content-addressed store, hash-verified

3540
3541 @instrument_w_nvtx
3542 def backward(self, loss, retain_graph=False, scale_wrt_gas=True):
3543 r"""Execute backward pass on the loss
3544 Arguments:
3545 loss: Torch tensor on which to execute backward propagation
3546 retain_graph: bool, default: false
3547 forward on user defined choice of retain_graph
3548 scale_wrt_gas: bool, default: true
3549 whether to scale gradients and return value by gradient accumulation steps
3550
3551 With ``managed_gradient_accumulation=false``, ``backward()`` only accumulates
3552 gradients locally (it does not trigger the accumulation-boundary reduction); the
3553 reduction and optimizer update happen in ``step()``.
3554 """
3555 assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
3556 "must provide optimizer during init in order to use backward"
3557 assert maybe_loss_for_backward(
3558 loss), "loss must be a scalar tensor. If you need to pass output gradients, backward() of output tensors"
3559
3560 with self._running_engine_backward_lock:
3561 self._running_engine_backward_count += 1
3562 self._running_engine_backward = True
3563 engine_backward_graph_state = _ENGINE_BACKWARD_GRAPH_TRACKER.new_state()
3564 engine_backward_graph_hook = None
3565 try:
3566 # Unmanaged mode: count this backward so step() can advance global_samples by the actual micro-batch count.
3567 if not self.managed_gradient_accumulation():
3568 self._unmanaged_backward_count += 1
3569
3570 # Set flag to prevent hooks from firing (we'll manually call prologue/epilogue)
3571 backward_kwargs = {"retain_graph": retain_graph}
3572
3573 loss = loss / self.gradient_accumulation_steps() if scale_wrt_gas else loss
3574 gas_scaled_loss = loss
3575
3576 # TODO: handle these scaling with direct calls to loss.backward()
3577 if isinstance(self.optimizer, ZeROOptimizer):
3578 loss = self.optimizer.scale_if_loss(loss)
3579 elif self.torch_autocast_z0_gradscaler:
3580 loss = self.torch_autocast_z0_gradscaler.scale(loss)
3581
3582 if loss.requires_grad:
3583 engine_backward_graph_hook = loss.register_hook(
3584 lambda grad: _ENGINE_BACKWARD_GRAPH_TRACKER.register_current_graph(
3585 grad, engine_backward_graph_state))
3586
3587 with compiled_autograd(self._is_compiled_autograd_enabled, self._compile_kwargs):
3588 loss.backward(**backward_kwargs)
3589
3590 # backward_epilogue is not called in a hook when self._support_torch_style_backward is False
3591 self._backward_epilogue()
3592
3593 return gas_scaled_loss
3594 finally:
3595 if engine_backward_graph_hook is not None:
3596 engine_backward_graph_hook.remove()
3597 _ENGINE_BACKWARD_GRAPH_TRACKER.unregister(engine_backward_graph_state)
3598 with self._running_engine_backward_lock:
3599 self._running_engine_backward_count -= 1

Callers

nothing calls this directly

Calls 10

_backward_epilogueMethod · 0.95
maybe_loss_for_backwardFunction · 0.90
compiled_autogradFunction · 0.85
new_stateMethod · 0.80
scale_if_lossMethod · 0.80
unregisterMethod · 0.80
scaleMethod · 0.45

Tested by

no test coverage detected