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

Method scale

deepspeed/runtime/engine.py:3526–3567  ·  view source on GitHub ↗

r"""Apply loss scaler for manual backward pass. Use this method when calling loss.backward() directly instead of engine.backward(). This applies the appropriate loss scaler for mixed precision training, allowing you to manually control the backward pass while still benefitin

(self, loss)

Source from the content-addressed store, hash-verified

3524 optimizer.independent_gradient_partition_epilogue()
3525
3526 def scale(self, loss):
3527 r"""Apply loss scaler for manual backward pass.
3528
3529 Use this method when calling loss.backward() directly instead of engine.backward().
3530 This applies the appropriate loss scaler for mixed precision training, allowing you
3531 to manually control the backward pass while still benefiting from DeepSpeed's
3532 gradient scaling functionality.
3533
3534 Example::
3535
3536 output = engine(input)
3537 loss = criterion(output, target)
3538 scaled_loss = engine.scale(loss)
3539 scaled_loss.backward() # Manual backward call
3540 engine.step()
3541
3542 Arguments:
3543 loss: Scalar loss tensor to be scaled
3544
3545 Returns:
3546 Scaled loss tensor ready for .backward() call
3547
3548 Raises:
3549 AssertionError: If loss is not a scalar tensor with grad_fn, or if no optimizer
3550 is configured.
3551 """
3552 assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
3553 "must provide optimizer during init in order to use scale"
3554 assert maybe_loss_for_backward(loss), \
3555 "loss must be a scalar tensor with grad_fn. For non-scalar tensors, use tensor.backward(grad)"
3556
3557 # Apply loss scaler based on optimizer type
3558 scaled_loss = loss
3559 if isinstance(self.optimizer, ZeROOptimizer):
3560 scaled_loss = self.optimizer.scale_if_loss(scaled_loss)
3561 elif self.torch_autocast_z0_gradscaler:
3562 scaled_loss = self.torch_autocast_z0_gradscaler.scale(scaled_loss)
3563
3564 # Mark that scale() was called for validation in backward hook
3565 self._manual_backward_expected = True
3566
3567 return scaled_loss
3568
3569 @instrument_w_nvtx
3570 def backward(self, loss, retain_graph=False, scale_wrt_gas=True):

Callers 2

backwardMethod · 0.45
scale_if_lossMethod · 0.45

Calls 2

maybe_loss_for_backwardFunction · 0.90
scale_if_lossMethod · 0.80

Tested by

no test coverage detected