MCPcopy Create free account
hub / github.com/CompVis/diff2flow / CheckpointFunction

Class CheckpointFunction

diff2flow/models/unet/util.py:34–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

32
33
34class CheckpointFunction(torch.autograd.Function):
35 @staticmethod
36 def forward(ctx, run_function, length, *args):
37 ctx.run_function = run_function
38 ctx.input_tensors = list(args[:length])
39 ctx.input_params = list(args[length:])
40 ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
41 "dtype": torch.get_autocast_gpu_dtype(),
42 "cache_enabled": torch.is_autocast_cache_enabled()}
43 with torch.no_grad():
44 output_tensors = ctx.run_function(*ctx.input_tensors)
45 return output_tensors
46
47 @staticmethod
48 def backward(ctx, *output_grads):
49 ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
50 with torch.enable_grad(), \
51 torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
52 # Fixes a bug where the first op in run_function modifies the
53 # Tensor storage in place, which is not allowed for detach()'d
54 # Tensors.
55 shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
56 output_tensors = ctx.run_function(*shallow_copies)
57 input_grads = torch.autograd.grad(
58 output_tensors,
59 ctx.input_tensors + ctx.input_params,
60 output_grads,
61 allow_unused=True,
62 )
63 del ctx.input_tensors
64 del ctx.input_params
65 del output_tensors
66 return (None, None) + input_grads
67
68
69def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected