Repository navigation
Introduce torch_remat activation checkpointing - #4497
Conversation
3f4ac97 to
562f5eb
Compare
| pip_install --no-deps \ | ||
| "git+https://github.com/meta-pytorch/remat.git@main" |
There was a problem hiding this comment.
no need if you already put it in requirements.txt (line 43)
| ) | ||
|
|
||
|
|
||
| class RematAC(ActivationCheckpointing): |
There was a problem hiding this comment.
RematAC reads as rematerialize activation checkpointing, which doesn't sound like a term.
Given that we are in the process of migrating, I don't think it matters that much. But at least add a note that we're going to remove all other AC variants and only keep this, at which point it deserves a serious name.
| python-version = "3.11" | ||
| project-excludes = ["torchtitan/experiments", "**/tests/**"] | ||
| replace-imports-with-any = ["torchao.*", "torchft", "torchvision.*", "deep_ep.*", "jinja2.*", "helion", "helion.*", "batch_invariant_ops", "torchcomms"] # optional dependencies | ||
| replace-imports-with-any = ["torchao.*", "torchft", "torchvision.*", "deep_ep.*", "jinja2.*", "helion", "helion.*", "batch_invariant_ops", "torchcomms", "torch_remat"] # dependencies without Pyrefly stubs |
There was a problem hiding this comment.
since it's not optional, shouldn't be put in this list?
There was a problem hiding this comment.
This is for pyrefly stubs handling.
There was a problem hiding this comment.
I think we could benefit from an overall REMAT.md as tutorial for torchtitan users / agents.
There was a problem hiding this comment.
Added - docs/remat.md
| AVAILABLE_REMAT_SAVE_REGIONS: tuple[str, ...] = ( | ||
| "qkv", | ||
| "inner_attention", | ||
| "wo", | ||
| ) |
There was a problem hiding this comment.
Do you mean to remove AVAILABLE_REMAT_SAVE_REGIONS or entire changes in torchtitan/models/common/attention.py? I deliberately kept this file change so that we can discuss the level of surgery and interface that future PRs will adopt.
There was a problem hiding this comment.
I removed the available tuple. It sat well with the minimal api in the rPR
| ] | ||
| # This model can be one pipeline partition, so a pattern absent here may | ||
| # still match a region assigned to another stage. | ||
| if unmatched_patterns: |
There was a problem hiding this comment.
let's remove this check for now -- in first version let's focus on a bare minimal version of integration
|
|
||
| selected_regions = [] | ||
| for layer_id, transformer_block in transformer_blocks: | ||
| selected_for_block, _ = configure_remat_save_regions( |
There was a problem hiding this comment.
Instead of introducing this function, could you directly do it inside module.configure_remat_regions?
Motivation
----------
TorchTitan currently provides full and selective activation checkpointing.
SelectiveAC makes save decisions at the operator level. torch_remat provides a
model-aware alternative where model code defines semantic regions and the
training configuration chooses which region outputs to retain.
This requires small, explicit annotations in model code. That tradeoff makes
the available policy surface visible next to the operations it controls and
allows policies to refer to stable model concepts rather than individual ATen
operators.
User experience
---------------
RematAC applies remat.checkpoint to each transformer layer under model.layers.
Model components advertise optional save boundaries with
AVAILABLE_REMAT_SAVE_REGIONS and call remat.region at those boundaries.
Users select regions through RematAC.Config:
RematAC.Config(
save_regions=[
"attention.qkv",
"attention.wo",
]
)
Region names are qualified relative to one transformer layer. The same policy
therefore applies to every layer. Shell-style patterns are supported, so
"attention.*" selects every region exposed by the attention module. Overlapping
patterns are a set union because every pattern expresses the same SAVE action.
An empty save_regions list is valid. It recomputes all user-configurable
regions. A pattern that does not match the current model part raises an
actionable error by default. Pipeline stages that intentionally do not contain
a matching region can set allow_unmatched_save_regions=True; the unmatched
patterns still produce a warning.
Attention example
-----------------
GQAttention exposes three regions:
AVAILABLE_REMAT_SAVE_REGIONS = (
"qkv",
"inner_attention",
"wo",
)
For the configuration above, execution is equivalent to:
remat.checkpoint(transformer_layer)
|
+-- attention
|
+-- qkv projections ............. SAVE
+-- q_norm / k_norm ............. RECOMPUTE
+-- RoPE ........................ RECOMPUTE
+-- inner_attention ............. RECOMPUTE
+-- output reshape .............. RECOMPUTE
+-- wo .......................... SAVE
SAVE means that the region runs during the original forward and its output is
retained for backward. RECOMPUTE means that the operation runs again during
checkpoint replay.
Implementation
--------------
Model call sites use torch_remat directly:
* remat.region receives the configured qualified name and recompute decision.
* remat.recompute_needs_tensor marks saved outputs needed by recomputed bare
operations outside another region.
* Module.remat_region_name and Module.remat_should_recompute provide safe
defaults, so region annotations do not change execution without an
enclosing remat checkpoint.
configure_remat_save_regions walks one transformer layer, discovers declared
regions, matches the configured patterns, and installs names and decisions on
the participating module instances. A subclass inherits a region declaration
only while it also inherits the associated forward implementation. A subclass
that replaces forward must redeclare and implement its own regions.
The MoE routing decision is handled separately from user policy. Node-limited
selection and final topk run inside an internal recompute=False region because
replaying tied topk values can select different experts. This correctness
boundary is intentionally not exposed through AVAILABLE_REMAT_SAVE_REGIONS.
torch_remat is promoted from an optional dependency to a regular TorchTitan
dependency because common model code calls its APIs directly.
Supported in this change
------------------------
* Transformer block containers named model.layers.
* Common GQAttention implementations that use the shared forward method.
* qkv, inner_attention, and wo as independently selectable save regions.
* Exact region names and shell-style wildcard patterns.
* Empty policies that recompute every user-configurable region.
* Stage-local pipeline application through the existing activation-
checkpointing flow, with an explicit escape hatch for stage-local unmatched
patterns.
Not supported yet
-----------------
* Different policies for individual transformer layers.
* Block containers other than model.layers.
* User-selectable FFN, expert, dispatch, vision, or model-specific attention
regions.
* Attention subclasses that replace the common GQAttention forward without
declaring their own region boundaries.
* Global unmatched-pattern validation across all pipeline stages.
* Activation-checkpoint debug mode or implicit RNG preservation inside saved
regions. Random state requires explicit torch_remat state hooks.
* Moving TP/SP source-to-destination redistributions from generic module
wrappers into the corresponding model regions.
Validation
----------
Focused unit tests verify wildcard selection, empty policies, unmatched-pattern
errors and the pipeline escape hatch, forward/backward equality, per-region
execution counts, inherited-forward handling, state-dict stability, and the
always-saved routing decision.
The model integration suite adds a Llama 3 FSDP2+TP2+CP2 RematAC configuration
and compares loss and gradient norm against the existing Llama numerical
golden.
562f5eb to
142ffb2
Compare
| "spmd_types==0.2.5", | ||
| "attn-gym[linear]==0.0.8", | ||
| # Keep this commit pin in sync with requirements.txt. | ||
| "torch_remat @ git+https://github.com/meta-pytorch/remat.git@d302699b1c58f83fa2c7b03bc2593967e9530335", |
There was a problem hiding this comment.
Unfortunately, we will have to work with pins until the integration is stable and we can cut a torch_remat release.
Human note heavily polished by AI
This PR focusses on the UX side of things with minimal model code surgery. The goal of this PR is to agree on the design. After this PR, the changes in next PRs are lot more mechanical or focus on improving debug experience.
Motivation
TorchTitan currently provides full and selective activation checkpointing. SelectiveAC makes save decisions at the operator level. torch_remat provides a model-aware alternative where model code defines semantic regions and the training configuration chooses which region outputs to retain.
This requires small, explicit annotations in model code. That tradeoff makes the available policy surface visible next to the operations it controls and allows policies to refer to stable model concepts rather than individual ATen operators.
User experience
RematAC applies remat.checkpoint to each transformer layer under model.layers. Model components advertise optional save boundaries with AVAILABLE_REMAT_SAVE_REGIONS and call remat.region at those boundaries.
Users select regions through RematAC.Config:
Region names are qualified relative to one transformer layer. The same policy therefore applies to every layer. Shell-style patterns are supported, so "attention.*" selects every region exposed by the attention module. Overlapping patterns are a set union because every pattern expresses the same SAVE action.
An empty save_regions list is valid. It recomputes all user-configurable regions. A pattern that does not match the current model part raises an actionable error by default. Pipeline stages that intentionally do not contain a matching region can set allow_unmatched_save_regions=True; the unmatched patterns still produce a warning.
Attention example
GQAttention exposes three regions:
For the configuration above, execution is equivalent to:
SAVE means that the region runs during the original forward and its output is retained for backward. RECOMPUTE means that the operation runs again during checkpoint replay.
Implementation
Model call sites use torch_remat directly:
configure_remat_save_regions walks one transformer layer, discovers declared regions, matches the configured patterns, and installs names and decisions on the participating module instances. A subclass inherits a region declaration only while it also inherits the associated forward implementation. A subclass that replaces forward must redeclare and implement its own regions.
The MoE routing decision is handled separately from user policy. Node-limited selection and final topk run inside an internal recompute=False region because replaying tied topk values can select different experts. This correctness boundary is intentionally not exposed through AVAILABLE_REMAT_SAVE_REGIONS.
torch_remat is promoted from an optional dependency to a regular TorchTitan dependency because common model code calls its APIs directly.
Supported in this change
Not supported yet
Validation
Focused unit tests verify wildcard selection, empty policies, unmatched-pattern errors and the pipeline escape hatch, forward/backward equality, per-region execution counts, inherited-forward handling, state-dict stability, and the always-saved routing decision.
The model integration suite adds a Llama 3 FSDP2+TP2+CP2 RematAC configuration and compares loss and gradient norm against the existing Llama numerical golden.