MCPcopy Create free account
hub / github.com/openai/shap-e / CheckpointFunctionGradFunction

Class CheckpointFunctionGradFunction

shap_e/models/nn/checkpoint.py:59–116  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

57
58
59class CheckpointFunctionGradFunction(torch.autograd.Function):
60 @staticmethod
61 @custom_fwd
62 def forward(ctx, run_function, length_1, length_2, *args):
63 ctx.run_function = run_function
64 ctx.length_1 = length_1
65 ctx.length_2 = length_2
66 input_tensors = [x.detach().requires_grad_(True) for x in args[:length_1]]
67 input_params = list(args[length_1 : length_1 + length_2])
68 output_grads = list(args[length_1 + length_2 :])
69 ctx.save_for_backward(*input_tensors, *input_params, *output_grads)
70
71 with torch.enable_grad():
72 # Fixes a bug where the first op in run_function modifies the
73 # Tensor storage in place, which is not allowed for detach()'d
74 # Tensors.
75 shallow_copies = [x.view_as(x) for x in input_tensors]
76 output_tensors = ctx.run_function(*shallow_copies)
77 input_grads = torch.autograd.grad(
78 output_tensors,
79 input_tensors + input_params,
80 output_grads,
81 allow_unused=True,
82 )
83 return input_grads
84
85 @staticmethod
86 @custom_bwd
87 def backward(ctx, *all_output_grads):
88 args = ctx.saved_tensors
89 input_tensors = [x.detach().requires_grad_(True) for x in args[: ctx.length_1]]
90 input_params = list(args[ctx.length_1 : ctx.length_1 + ctx.length_2])
91 output_grads = [
92 x.detach().requires_grad_(True) for x in args[ctx.length_1 + ctx.length_2 :]
93 ]
94
95 with torch.enable_grad():
96 # Fixes a bug where the first op in run_function modifies the
97 # Tensor storage in place, which is not allowed for detach()'d
98 # Tensors.
99 shallow_copies = [x.view_as(x) for x in input_tensors]
100 output_tensors = ctx.run_function(*shallow_copies)
101 input_grads = torch.autograd.grad(
102 output_tensors,
103 input_tensors + input_params,
104 output_grads,
105 allow_unused=True,
106 create_graph=True,
107 retain_graph=True,
108 )
109 input_grads_grads = torch.autograd.grad(
110 input_grads,
111 input_tensors + input_params + output_grads,
112 all_output_grads,
113 allow_unused=True,
114 )
115 del input_grads
116 return (None, None, None) + input_grads_grads

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected