Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters
(func, inputs, params, flag)
| 352 | |
| 353 | |
| 354 | def checkpoint(func, inputs, params, flag): |
| 355 | """ |
| 356 | Evaluate a function without caching intermediate activations, allowing for |
| 357 | reduced memory at the expense of extra compute in the backward pass. |
| 358 | :param func: the function to evaluate. |
| 359 | :param inputs: the argument sequence to pass to `func`. |
| 360 | :param params: a sequence of parameters `func` depends on but does not |
| 361 | explicitly take as arguments. |
| 362 | :param flag: if False, disable gradient checkpointing. |
| 363 | """ |
| 364 | if flag: |
| 365 | args = tuple(inputs) + tuple(params) |
| 366 | return CheckpointFunction.apply(func, len(inputs), *args) |
| 367 | else: |
| 368 | return func(*inputs) |
| 369 | |
| 370 | |
| 371 | class CheckpointFunction(torch.autograd.Function): |