| 117 | |
| 118 | |
| 119 | class CheckpointFunction(torch.autograd.Function): |
| 120 | @staticmethod |
| 121 | def forward(ctx, run_function, length, *args): |
| 122 | ctx.run_function = run_function |
| 123 | ctx.input_tensors = list(args[:length]) |
| 124 | ctx.input_params = list(args[length:]) |
| 125 | ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(), |
| 126 | "dtype": torch.get_autocast_gpu_dtype(), |
| 127 | "cache_enabled": torch.is_autocast_cache_enabled()} |
| 128 | with torch.no_grad(): |
| 129 | output_tensors = ctx.run_function(*ctx.input_tensors) |
| 130 | return output_tensors |
| 131 | |
| 132 | @staticmethod |
| 133 | def backward(ctx, *output_grads): |
| 134 | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] |
| 135 | with torch.enable_grad(), \ |
| 136 | torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs): |
| 137 | # Fixes a bug where the first op in run_function modifies the |
| 138 | # Tensor storage in place, which is not allowed for detach()'d |
| 139 | # Tensors. |
| 140 | shallow_copies = [x.view_as(x) for x in ctx.input_tensors] |
| 141 | output_tensors = ctx.run_function(*shallow_copies) |
| 142 | input_grads = torch.autograd.grad( |
| 143 | output_tensors, |
| 144 | ctx.input_tensors + ctx.input_params, |
| 145 | output_grads, |
| 146 | allow_unused=True, |
| 147 | ) |
| 148 | del ctx.input_tensors |
| 149 | del ctx.input_params |
| 150 | del output_tensors |
| 151 | return (None, None) + input_grads |
| 152 | |
| 153 | |
| 154 | def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): |
nothing calls this directly
no outgoing calls
no test coverage detected