MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / backward

Method backward

imperative/python/megengine/amp/grad_scaler.py:255–285  ·  view source on GitHub ↗

r"""Unscale all ``grad_tensors``'s grad and check if the gradient is finite. Args: grad_tensors: Tensors needed to unscale grads. Should be all tensors that are affected by ``target`` tensor in GradManager's backward.

(
        self,
        gm: GradManager,
        scale_factor: Tensor,
        y: Union[Tensor, List[Tensor]] = None,
        dy: Union[Tensor, List[Tensor]] = None,
    )

Source from the content-addressed store, hash-verified

253 self.origin_params.append(Tensor(param, no_cache=True))
254
255 def backward(
256 self,
257 gm: GradManager,
258 scale_factor: Tensor,
259 y: Union[Tensor, List[Tensor]] = None,
260 dy: Union[Tensor, List[Tensor]] = None,
261 ):
262 r"""Unscale all ``grad_tensors``'s grad and check if the gradient is finite.
263
264 Args:
265 grad_tensors: Tensors needed to unscale grads. Should be all tensors
266 that are affected by ``target`` tensor in GradManager's backward.
267 """
268 if y is None:
269 ys = []
270 elif isinstance(y, (tuple, list)):
271 ys = y
272 else:
273 ys = [y]
274 if dy is None:
275 dys = [full_like(y, scale_factor) for y in ys]
276 elif isinstance(dy, (tuple, list)):
277 dys = [dy_ * scale_factor for dy_ in dy]
278 else:
279 dys = [dy * scale_factor]
280
281 gm.backward(y=ys, dy=dys)
282 self.ifinfinite = self._check_gradients(
283 [x.grad for x in gm.attached_tensors() if x.grad is not None],
284 1.0 / float(scale_factor),
285 )
286
287 def update(self, model, new_scale: float = None):
288 r"""Update the scale factor and model paramters according to whether encountered overflow grad.

Callers

nothing calls this directly

Calls 4

full_likeFunction · 0.85
_check_gradientsMethod · 0.80
attached_tensorsMethod · 0.80
backwardMethod · 0.45

Tested by

no test coverage detected