Skip to content

Introduce torch_remat activation checkpointing - #4497

Merged
anijain2305 merged 1 commit into
mainfrom
remat-minimal-pr
Sep 7, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
remat-minimal-pr

Conversation

@anijain2305

@anijain2305 anijain2305 commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

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:

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 6, 2026
@anijain2305 anijain2305 changed the title Add torch_remat activation checkpointing Introduce torch_remat activation checkpointing Sep 6, 2026
@anijain2305
anijain2305 force-pushed the remat-minimal-pr branch 2 times, most recently from 3f4ac97 to 562f5eb Compare September 6, 2026 06:16
Comment thread .ci/docker/common/install_conda.sh Outdated
Comment on lines +50 to +51
pip_install --no-deps \
"git+https://github.com/meta-pytorch/remat.git@main"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need if you already put it in requirements.txt (line 43)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cpu/ or gpu/

)


class RematAC(ActivationCheckpointing):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pyproject.toml Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since it's not optional, shouldn't be put in this list?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for pyrefly stubs handling.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could benefit from an overall REMAT.md as tutorial for torchtitan users / agents.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added - docs/remat.md

Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +873 to +877
AVAILABLE_REMAT_SAVE_REGIONS: tuple[str, ...] = (
"qkv",
"inner_attention",
"wo",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove for now

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@anijain2305 anijain2305 Sep 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Comment thread pyproject.toml
"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",

@anijain2305 anijain2305 Sep 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, we will have to work with pins until the integration is stable and we can cut a torch_remat release.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very cool

@anijain2305
anijain2305 merged commit c6e416b into main Sep 7, 2026
17 of 19 checks passed
@tianyu-l
tianyu-l deleted the remat-minimal-pr branch September 7, 2026 22:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants