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

Class CheckpointFunction

diff2flow/models/unet/attention.py:358–390  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

356
357
358class CheckpointFunction(torch.autograd.Function):
359 @staticmethod
360 def forward(ctx, run_function, length, *args):
361 ctx.run_function = run_function
362 ctx.input_tensors = list(args[:length])
363 ctx.input_params = list(args[length:])
364 ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
365 "dtype": torch.get_autocast_gpu_dtype(),
366 "cache_enabled": torch.is_autocast_cache_enabled()}
367 with torch.no_grad():
368 output_tensors = ctx.run_function(*ctx.input_tensors)
369 return output_tensors
370
371 @staticmethod
372 def backward(ctx, *output_grads):
373 ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
374 with torch.enable_grad(), \
375 torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
376 # Fixes a bug where the first op in run_function modifies the
377 # Tensor storage in place, which is not allowed for detach()'d
378 # Tensors.
379 shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
380 output_tensors = ctx.run_function(*shallow_copies)
381 input_grads = torch.autograd.grad(
382 output_tensors,
383 ctx.input_tensors + ctx.input_params,
384 output_grads,
385 allow_unused=True,
386 )
387 del ctx.input_tensors
388 del ctx.input_params
389 del output_tensors
390 return (None, None) + input_grads

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected