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

Method scale

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

3248 optimizer.independent_gradient_partition_epilogue()
3249
3250 def scale(self, loss):
3251 r"""Apply loss scaler for manual backward pass.
3252
3253 Use this method when calling loss.backward() directly instead of engine.backward().
3254 This applies the appropriate loss scaler for mixed precision training, allowing you
3255 to manually control the backward pass while still benefiting from DeepSpeed's
3256 gradient scaling functionality.
3257
3258 Example::
3259
3260 output = engine(input)
3261 loss = criterion(output, target)
3262 scaled_loss = engine.scale(loss)
3263 scaled_loss.backward() # Manual backward call
3264 engine.step()
3265
3266 Arguments:
3267 loss: Scalar loss tensor to be scaled
3268
3269 Returns:
3270 Scaled loss tensor ready for .backward() call
3271
3272 Raises:
3273 RuntimeError: If AMP (NVIDIA Apex) is enabled. AMP requires using engine.backward()
3274 directly as it uses a context manager that cannot be separated from
3275 the backward call.
3276 AssertionError: If loss is not a scalar tensor with grad_fn, or if no optimizer
3277 is configured.
3278 """
3279 assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
3280 "must provide optimizer during init in order to use scale"
3281 assert maybe_loss_for_backward(loss), \
3282 "loss must be a scalar tensor with grad_fn. For non-scalar tensors, use tensor.backward(grad)"
3283
3284 # AMP (NVIDIA Apex) uses a context manager that wraps both scaling and backward,
3285 # so it cannot be used with manual backward calls
3286 if self.amp_enabled():
3287 raise RuntimeError("engine.scale() is not compatible with AMP (NVIDIA Apex). "
3288 "When using AMP, you must call engine.backward(loss) instead of manual backward.")
3289
3290 # Apply loss scaler based on optimizer type
3291 scaled_loss = loss
3292 if isinstance(self.optimizer, ZeROOptimizer):
3293 scaled_loss = self.optimizer.scale_if_loss(scaled_loss)
3294 elif self.torch_autocast_z0_gradscaler:
3295 scaled_loss = self.torch_autocast_z0_gradscaler.scale(scaled_loss)
3296
3297 # Mark that scale() was called for validation in backward hook
3298 self._manual_backward_expected = True
3299
3300 return scaled_loss
3301
3302 @instrument_w_nvtx
3303 def backward(self, loss, retain_graph=False, scale_wrt_gas=True):

Callers 2

backwardMethod · 0.45
scale_if_lossMethod · 0.45

Calls 3

amp_enabledMethod · 0.95
maybe_loss_for_backwardFunction · 0.90
scale_if_lossMethod · 0.80

Tested by

no test coverage detected