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

Function fully_checkpoint_sequential

PATH/core/utils.py:696–737  ·  view source on GitHub ↗

r"""Modified version of torch.utils.checkpoint.checkpoint_sequential for memory efficiency. It is assumed that at least one of the inputs have requires_grad=True, so we can checkpoint all of the segments at ease. Please refer to https://pytorch.org/docs/stable/checkpoint.html#torch.utils

(functions, segments, input, **kwargs)

Source from the content-addressed store, hash-verified

694 print('sync_print: rank {}, '.format(rank) + ' '.join(args), **kwargs)
695
696def fully_checkpoint_sequential(functions, segments, input, **kwargs):
697 r"""Modified version of torch.utils.checkpoint.checkpoint_sequential for memory efficiency.
698 It is assumed that at least one of the inputs have requires_grad=True, so we can checkpoint
699 all of the segments at ease.
700 Please refer to https://pytorch.org/docs/stable/checkpoint.html#torch.utils.checkpoint.checkpoint_sequential
701 for more details.
702
703 -1 -> sqrt chunk checkpoint
704 0 -> no checkpoint
705 others ->
706 """
707 preserve = kwargs.pop('preserve_rng_state', True)
708 if kwargs:
709 raise ValueError("Unexpected keyword arguments: " + ",".join(arg for arg in kwargs))
710
711 def run_function(start, end, functions):
712 def forward(input):
713 for j in range(start, end + 1):
714 input = functions[j](input)
715 return input
716 return forward
717
718 if isinstance(functions, torch.nn.Sequential):
719 functions = list(functions.children())
720
721 # no checkpoint
722 if segments == 0:
723 return run_function(0, len(functions) - 1, functions)(input)
724
725 # auto determin the chunksize
726 if segments < 0:
727 segments = int(math.ceil(len(functions)))
728
729 segments = min(segments, len(functions))
730 segment_size = len(functions) // segments
731 # the last chunk has to be non-volatile
732 end = -1
733 for start in range(0, segment_size * (segments - 1), segment_size):
734 end = start + segment_size - 1
735 input = checkpoint(run_function(start, end, functions), input)
736# preserve_rng_state=preserve)
737 return checkpoint(run_function(end + 1, len(functions) - 1, functions), input)#,
738# preserve_rng_state=preserve)
739
740def printlog(*args, **kwargs):

Callers

nothing calls this directly

Calls 1

run_functionFunction · 0.85

Tested by

no test coverage detected