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

Method scale

deepspeed/runtime/engine.py:3498–3539  ·  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

3496 optimizer.independent_gradient_partition_epilogue()
3497
3498 def scale(self, loss):
3499 r"""Apply loss scaler for manual backward pass.
3500
3501 Use this method when calling loss.backward() directly instead of engine.backward().
3502 This applies the appropriate loss scaler for mixed precision training, allowing you
3503 to manually control the backward pass while still benefiting from DeepSpeed's
3504 gradient scaling functionality.
3505
3506 Example::
3507
3508 output = engine(input)
3509 loss = criterion(output, target)
3510 scaled_loss = engine.scale(loss)
3511 scaled_loss.backward() # Manual backward call
3512 engine.step()
3513
3514 Arguments:
3515 loss: Scalar loss tensor to be scaled
3516
3517 Returns:
3518 Scaled loss tensor ready for .backward() call
3519
3520 Raises:
3521 AssertionError: If loss is not a scalar tensor with grad_fn, or if no optimizer
3522 is configured.
3523 """
3524 assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
3525 "must provide optimizer during init in order to use scale"
3526 assert maybe_loss_for_backward(loss), \
3527 "loss must be a scalar tensor with grad_fn. For non-scalar tensors, use tensor.backward(grad)"
3528
3529 # Apply loss scaler based on optimizer type
3530 scaled_loss = loss
3531 if isinstance(self.optimizer, ZeROOptimizer):
3532 scaled_loss = self.optimizer.scale_if_loss(scaled_loss)
3533 elif self.torch_autocast_z0_gradscaler:
3534 scaled_loss = self.torch_autocast_z0_gradscaler.scale(scaled_loss)
3535
3536 # Mark that scale() was called for validation in backward hook
3537 self._manual_backward_expected = True
3538
3539 return scaled_loss
3540
3541 @instrument_w_nvtx
3542 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