MCPcopy Create free account
hub / github.com/OpenGVLab/HumanBench / backward

Method backward

PATH/core/models/ckpt.py:476–517  ·  view source on GitHub ↗
(ctx: Any, *args: Any)

Source from the content-addressed store, hash-verified

474
475 @staticmethod
476 def backward(ctx: Any, *args: Any) -> Tuple[Optional[Tensor], ...]:
477 if not torch.autograd._is_checkpoint_valid():
478 raise RuntimeError("Checkpointing is not compatible with .grad(), please use .backward() if possible")
479
480 tensor_inputs: Tuple = ctx.saved_tensors
481 tensor_inputs = torch_checkpoint.detach_variable(tensor_inputs)
482 if ctx.fwd_device is not None:
483 tensor_inputs = tuple(t.to(ctx.fwd_device[i], non_blocking=True) for i, t in enumerate(tensor_inputs))
484 for i, need_grad in enumerate(ctx.grad_requirements):
485 tensor_inputs[i].requires_grad = need_grad
486 inputs = unpack_non_tensors(tensor_inputs, ctx.packed_non_tensor_inputs)
487
488 # Store the current states.
489 bwd_rng_state = get_rng_state()
490
491 # Set the states to what it used to be before the forward pass.
492 set_rng_state(ctx.fwd_rng_state)
493
494 with torch.enable_grad(), enable_recomputing(), autocast(ctx.had_autocast_in_fwd):
495 unpacked_args, unpacked_kwargs = unpack_kwargs(ctx.kwarg_keys, inputs)
496 outputs = ctx.run_function(*unpacked_args, **unpacked_kwargs)
497 tensor_outputs, _ = split_non_tensors(outputs)
498
499 # Set the states back to what it was at the start of this function.
500 set_rng_state(bwd_rng_state)
501
502 # Run backward() with only Tensors that require grad
503 outputs_with_grad = []
504 args_with_grad = []
505 for i in range(len(tensor_outputs)):
506 if tensor_outputs[i].requires_grad:
507 outputs_with_grad.append(tensor_outputs[i])
508 args_with_grad.append(args[i])
509
510 if len(outputs_with_grad) == 0:
511 raise RuntimeError("None of the outputs have requires_grad=True, " "this checkpoint() is not necessary")
512
513 torch.autograd.backward(outputs_with_grad, args_with_grad)
514
515 grads = tuple(inp.grad if isinstance(inp, torch.Tensor) else None for inp in inputs)
516
517 return (None, None, None, None) + grads

Callers

nothing calls this directly

Calls 8

unpack_non_tensorsFunction · 0.85
get_rng_stateFunction · 0.85
set_rng_stateFunction · 0.85
enable_recomputingFunction · 0.85
autocastFunction · 0.85
unpack_kwargsFunction · 0.85
split_non_tensorsFunction · 0.85
toMethod · 0.45

Tested by

no test coverage detected