| 40 | |
| 41 | |
| 42 | class CheckpointFunction(torch.autograd.Function): |
| 43 | @staticmethod |
| 44 | def forward(ctx, run_function, length, *args): |
| 45 | ctx.run_function = run_function |
| 46 | ctx.input_tensors = list(args[:length]) |
| 47 | ctx.input_params = list(args[length:]) |
| 48 | |
| 49 | with torch.no_grad(): |
| 50 | output_tensors = ctx.run_function(*ctx.input_tensors) |
| 51 | return output_tensors |
| 52 | |
| 53 | @staticmethod |
| 54 | def backward(ctx, *output_grads): |
| 55 | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] |
| 56 | with torch.enable_grad(): |
| 57 | # Fixes a bug where the first op in run_function modifies the |
| 58 | # Tensor storage in place, which is not allowed for detach()'d |
| 59 | # Tensors. |
| 60 | shallow_copies = [x.view_as(x) for x in ctx.input_tensors] |
| 61 | output_tensors = ctx.run_function(*shallow_copies) |
| 62 | input_grads = torch.autograd.grad( |
| 63 | output_tensors, |
| 64 | ctx.input_tensors + ctx.input_params, |
| 65 | output_grads, |
| 66 | allow_unused=True, |
| 67 | ) |
| 68 | del ctx.input_tensors |
| 69 | del ctx.input_params |
| 70 | del output_tensors |
| 71 | return (None, None) + input_grads |
| 72 | |
| 73 | |
| 74 | def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): |
nothing calls this directly
no outgoing calls
no test coverage detected