Explicit activation rematerialization helpers for PyTorch
Actively maintained. Last release 6 weeks ago, commits in 17 of the last 26 weeks. A safe choice.
pip install torch-rematREADME as published on PyPI with version 0.2.2.
torch_remat
torch_remat is a modern activation checkpointing implementation for PyTorch.
It takes the classic recipe of non-reentrant torch.utils.checkpoint (recompute
everything before backwards) and enhances it with the ability to mark regions
inside the recompute region to save their activations for backward, so they
don't have to be recomputed.
Compared with selective activation checkpointing (SAC), torch_remat allows you
to specify save/recompute decisions on regions of source code, instead of writing
a generic policy function that operates on a per-ATen operator basis. This
allows for finer-grained recompute policies (e.g., you can easily express that
one matmul should be saved while another should be recomputed). It's also
easier to use torch_remat with code that has many custom kernels (you don't
have to custom op'ify them), and the fact that torch_remat doesn't use a
TorchDispatchMode means CPU overhead is lower.
Quick start
Put one checkpoint around the unit you want to replay, usually a transformer block:
import torch_remat as remat
# torch.utils.checkpoint.checkpoint compatible API:
# remat.checkpoint(**remat_kwargs)(func)(*args, **kwargs)
output = remat.checkpoint(region_name="layers.0")(block)(hidden_states)
(remat.checkpoint(block)(hidden_states) is intentionally not supported,
because this phrasing of the API is ambiguous with torch.utils.checkpoint.)
Inside the block's forward method, annotate calls whose backward activations
should be saved with remat.region(..., recompute=False), and annotate
outputs of save regions which will be needed for recompute with
remat.recompute_needs_tensor (you can also omit these and torch_remat will
tell you which ones you need to mark):
def forward(self, hidden_states):
x = self.attention_norm(hidden_states)
attn = remat.region(
self.attention,
"attention",
recompute=False,
)(x)
remat.recompute_needs_tensor(attn)
hidden_states = hidden_states + attn
x = self.ffn_norm(hidden_states)
moe = remat.region(
self.moe,
"moe",
recompute=False,
)(x)
remat.recompute_needs_tensor(moe)
return hidden_states + moe
The interaction between recompute and save regions is somewhat subtle; check for more details.