Skip to content

Support AC rematerializing in forward+loss+bwd graph - #168082

Closed
tugsbayasgalan wants to merge 35 commits into
gh/tugsbayasgalan/82/basefrom
gh/tugsbayasgalan/82/head
Closed

tugsbayasgalan wants to merge 35 commits into
gh/tugsbayasgalan/82/basefrom
gh/tugsbayasgalan/82/head

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This PR adds an optimization pass that minimizes memory usage during forward+backward+loss mode compilation by rematerializing activation checkpoint (AC) nodes closer to backward region to reduce their lifetime.

For example:

def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx

Without optimization, the checkpointed sin(x) is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds rematerialize_ac_nodes() pass that:

  1. Duplicates AC nodes used in both forward/backward: Keeps in forward, recomputes in backward

The pass is controlled by the config flag torch._functorch.config.enable_inference_mode_ac_reordering (default: False).

The pass works in several steps:

  1. Find backward boundary: Identify where backward computation starts using metadata annotations
  2. Categorize AC nodes: Classify each AC node based on usage
  3. Rebuild graph:
    • Backward: Duplicate AC chains for nodes used in both forward and backward while maintaining original order
  4. DCE Use DCE to clean up forward nodes since some of them are only used in backward.

User code:

def inference_with_grad(arg0_1, arg1_1):
    # Checkpointed computation
    z = torch.utils.checkpoint.checkpoint(
        lambda a, b: torch.sigmoid(torch.mm(a, b)),
        arg0_1, arg1_1,
        use_reentrant=False
    )
    loss = z.sum()

    # Backward in same graph
    with torch.fx.traceback.annotate({"backward": 0}):
        grads = torch.autograd.grad(loss, (arg0_1, arg1_1))
    return grads

Compiled graph without AC reordering:

# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed in forward
detach = sigmoid.detach()                # Saved for backward
sum_1 = sigmoid.sum()

# Backward
sigmoid_backward = ...  # Uses saved sigmoid (held in memory since forward)
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=3, sigmoid=1
# Memory: sigmoid held from forward through backward

Compiled graph with AC reordering:

# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed for sum
sum_1 = sigmoid.sum()                    # Used in forward, then freed

# Backward - AC nodes recomputed just-in-time
mm_recomputed = torch.mm(arg0_1, arg1_1)              # Recompute
sigmoid_recomputed = torch.sigmoid(mm_recomputed)      # Recompute
detach = sigmoid_recomputed.detach()                   # Use recomputed version
sigmoid_backward = ...
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=4, sigmoid=2
# Memory: sigmoid freed after forward, recomputed just-in-time

We tested on a synthetic large model which looks like:

def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory.

Next Steps
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @Lucaskabela @jataylo @chenyang78

@pytorch-bot

pytorch-bot Bot commented Nov 18, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/168082

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (8 Unrelated Failures)

As of commit 634e245 with merge base 44ac693 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: fa413af
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: 793064b
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: 2f8a92d
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: fc33f68
Pull Request resolved: #168082
bwd_start = order[first_node_in_bwd]

# Categorize AC nodes by usage
ac_used_in_fwd: set[fx.Node] = set()

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.

It's not sufficient to just check whether the user is in fw
What you really want to do know is whether it is needed to compute forward output.

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.

Ok i just duplicate always and DCe later.

return x


def reorder_ac_nodes_for_inference(gm: fx.GraphModule) -> fx.GraphModule:

@soulitzer soulitzer Nov 18, 2025 •

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.

Maybe instead "remat_nodes_with_ac_tags"
since this pass does more than just reorder
not sure we need to mention "inference" since this is closer to a generic remat pass, the only difference is (1) we need annotations to tell us what to recompute and (2) when bw begins.


def reorder_ac_nodes_for_inference(gm: fx.GraphModule) -> fx.GraphModule:
"""
Reorder AC nodes to minimize lifetime by deferring whole AC chains to backward.

@soulitzer soulitzer Nov 18, 2025 •

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.

hmmmm maybe a nit, but I don't really like the term "AC nodes" haha, I feel like its a little confusing
for example, here I think you mean the "duplicated node"
but in other places I think you mean "node tagged with recompute"


# Only need to track AC nodes used in backward or both regions
ac_bwd_only = ac_used_in_bwd - ac_used_in_fwd
ac_both = ac_used_in_fwd & ac_used_in_bwd

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.

Do we actually need this distinction if we have DCE? Like always duplicate, and then the original node in forward now has no users if it falls into the bwd_only case.

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.

Ah yes good point. We can just DCE later.



class ACReorderingInferenceModeTests(torch._dynamo.test_case.TestCase):
"""Tests for AC reordering optimization in inference mode (forward+backward in one graph)."""

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.

@soulitzer soulitzer 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.

Pretty cool, added some comments
The approach sounds reasonable, but it is still a good amount of new code, which is adding very similar behavior of the existing AC tag handing.

I don't think you necessarily should use the existing default_partitioner, as there is a lot of partitioning-specific logic there (e.g. special handling for sym_node since they must be saved in the autograd.Function on ctx directly), but I still wonder if it is possible to reuse existing pieces to simplify things. Like we already have logic to do duplication, reordering.

@soulitzer

Copy link
Copy Markdown
Contributor

but we should automatically tag them when torchdynamo encounter torch.autograd.grad.

An issue with this is that if you have the user doing multiple .grads, e.g. chunked backward.

This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: 9b9a04b
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: fd5e6b0
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during inference-mode compilation by reordering activation checkpoint (AC) nodes to reduce their lifetime. When forward and backward operations are captured in a single graph (inference mode with `torch.autograd.grad`), AC nodes can be deferred or duplicated to be computed just-in-time rather than early in the forward pass. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `reorder_ac_nodes_for_inference()` pass that:

1. **Defers AC nodes only used in backward**: Moves them entirely to the backward region
2. **Duplicates AC nodes used in both**: Keeps in forward, recomputes in backward
3. **Reuses checkpoint inputs**: When recomputing, reuses non-AC inputs from forward (mimics partitioner behavior)

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage:
   - `ac_bwd_only`: Only used in backward → defer to backward
   - `ac_both`: Used in both regions → duplicate in backward
3. **Rebuild graph**:
   - Forward: Skip deferred AC nodes
   - Backward: Compute deferred AC nodes + duplicate AC chains for nodes used in both
4. **Maintain ordering**: Use shared utilities to maintain original execution order


**Before** (without AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node computed in forward
    detach = torch.ops.aten.detach.default(sigmoid)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # ... backward ops that use detach
```

**After** (with AC reordering):
```python
def forward(self, arg0_1, arg1_1):
    mm = torch.ops.aten.mm.default(arg0_1, arg1_1)
    sigmoid = torch.ops.aten.sigmoid.default(mm)  # AC node stays (used in forward)
    sum_1 = torch.ops.aten.sum.default(sigmoid)
    # AC node recomputed just-in-time for backward
    detach = torch.ops.aten.detach.default(sigmoid)
    # ... backward ops
```


We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames Lucaskabela

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Nov 18, 2025
ghstack-source-id: 946ac24
Pull Request resolved: #168082
pytorchmergebot pushed a commit that referenced this pull request Dec 1, 2025
ghstack-source-id: cabc890
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during forward+backward+loss mode compilation by rematerializing activation checkpoint (AC) nodes closer to backward region to reduce their lifetime. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `rematerialize_ac_nodes()` pass that:

1. **Duplicates AC nodes used in both forward/backward**: Keeps in forward, recomputes in backward

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage
3. **Rebuild graph**:
   - Backward: Duplicate AC chains for nodes used in both forward and backward while maintaining original order 
4. **DCE** Use DCE to clean up forward nodes since some of them are only used in backward. 


**User code:**
```python
def inference_with_grad(arg0_1, arg1_1):
    # Checkpointed computation
    z = torch.utils.checkpoint.checkpoint(
        lambda a, b: torch.sigmoid(torch.mm(a, b)),
        arg0_1, arg1_1,
        use_reentrant=False
    )
    loss = z.sum()

    # Backward in same graph
    with torch.fx.traceback.annotate({"backward": 0}):
        grads = torch.autograd.grad(loss, (arg0_1, arg1_1))
    return grads
```

**Compiled graph without AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed in forward
detach = sigmoid.detach()                # Saved for backward
sum_1 = sigmoid.sum()

# Backward
sigmoid_backward = ...  # Uses saved sigmoid (held in memory since forward)
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=3, sigmoid=1
# Memory: sigmoid held from forward through backward
```

**Compiled graph with AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed for sum
sum_1 = sigmoid.sum()                    # Used in forward, then freed

# Backward - AC nodes recomputed just-in-time
mm_recomputed = torch.mm(arg0_1, arg1_1)              # Recompute
sigmoid_recomputed = torch.sigmoid(mm_recomputed)      # Recompute
detach = sigmoid_recomputed.detach()                   # Use recomputed version
sigmoid_backward = ...
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=4, sigmoid=2
# Memory: sigmoid freed after forward, recomputed just-in-time
```



We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo chenyang78

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 2, 2025
ghstack-source-id: 12cc331
Pull Request resolved: #168082
This PR adds an optimization pass that minimizes memory usage during forward+backward+loss mode compilation by rematerializing activation checkpoint (AC) nodes closer to backward region to reduce their lifetime. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `rematerialize_ac_nodes()` pass that:

1. **Duplicates AC nodes used in both forward/backward**: Keeps in forward, recomputes in backward

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage
3. **Rebuild graph**:
   - Backward: Duplicate AC chains for nodes used in both forward and backward while maintaining original order 
4. **DCE** Use DCE to clean up forward nodes since some of them are only used in backward. 


**User code:**
```python
def inference_with_grad(arg0_1, arg1_1):
    # Checkpointed computation
    z = torch.utils.checkpoint.checkpoint(
        lambda a, b: torch.sigmoid(torch.mm(a, b)),
        arg0_1, arg1_1,
        use_reentrant=False
    )
    loss = z.sum()

    # Backward in same graph
    with torch.fx.traceback.annotate({"backward": 0}):
        grads = torch.autograd.grad(loss, (arg0_1, arg1_1))
    return grads
```

**Compiled graph without AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed in forward
detach = sigmoid.detach()                # Saved for backward
sum_1 = sigmoid.sum()

# Backward
sigmoid_backward = ...  # Uses saved sigmoid (held in memory since forward)
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=3, sigmoid=1
# Memory: sigmoid held from forward through backward
```

**Compiled graph with AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed for sum
sum_1 = sigmoid.sum()                    # Used in forward, then freed

# Backward - AC nodes recomputed just-in-time
mm_recomputed = torch.mm(arg0_1, arg1_1)              # Recompute
sigmoid_recomputed = torch.sigmoid(mm_recomputed)      # Recompute
detach = sigmoid_recomputed.detach()                   # Use recomputed version
sigmoid_backward = ...
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=4, sigmoid=2
# Memory: sigmoid freed after forward, recomputed just-in-time
```



We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo chenyang78

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 2, 2025
ghstack-source-id: d737394
Pull Request resolved: #168082
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

This PR adds an optimization pass that minimizes memory usage during forward+backward+loss mode compilation by rematerializing activation checkpoint (AC) nodes closer to backward region to reduce their lifetime. 


For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `rematerialize_ac_nodes()` pass that:

1. **Duplicates AC nodes used in both forward/backward**: Keeps in forward, recomputes in backward

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage
3. **Rebuild graph**:
   - Backward: Duplicate AC chains for nodes used in both forward and backward while maintaining original order 
4. **DCE** Use DCE to clean up forward nodes since some of them are only used in backward. 


**User code:**
```python
def inference_with_grad(arg0_1, arg1_1):
    # Checkpointed computation
    z = torch.utils.checkpoint.checkpoint(
        lambda a, b: torch.sigmoid(torch.mm(a, b)),
        arg0_1, arg1_1,
        use_reentrant=False
    )
    loss = z.sum()

    # Backward in same graph
    with torch.fx.traceback.annotate({"backward": 0}):
        grads = torch.autograd.grad(loss, (arg0_1, arg1_1))
    return grads
```

**Compiled graph without AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed in forward
detach = sigmoid.detach()                # Saved for backward
sum_1 = sigmoid.sum()

# Backward
sigmoid_backward = ...  # Uses saved sigmoid (held in memory since forward)
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=3, sigmoid=1
# Memory: sigmoid held from forward through backward
```

**Compiled graph with AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed for sum
sum_1 = sigmoid.sum()                    # Used in forward, then freed

# Backward - AC nodes recomputed just-in-time
mm_recomputed = torch.mm(arg0_1, arg1_1)              # Recompute
sigmoid_recomputed = torch.sigmoid(mm_recomputed)      # Recompute
detach = sigmoid_recomputed.detach()                   # Use recomputed version
sigmoid_backward = ...
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=4, sigmoid=2
# Memory: sigmoid freed after forward, recomputed just-in-time
```



We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory. 

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad. 


cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo chenyang78

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 3, 2025
ghstack-source-id: 45f7f30
Pull Request resolved: #168082
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@xmfan

xmfan commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

@wwwjn

wwwjn commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

cc @tianyu-l @fegin torchtitan CI failed because of this PR

if _is_backward_node(node) and bwd_start is None:
bwd_start = idx

if bwd_start is None:

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.

@tugsbayasgalan we should lift this up before the RNG check

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.

and then only warn IF there are recomputable ops

JacobSzwejbka pushed a commit that referenced this pull request Dec 8, 2025
This PR adds an optimization pass that minimizes memory usage during forward+backward+loss mode compilation by rematerializing activation checkpoint (AC) nodes closer to backward region to reduce their lifetime.

For example:
```python
def inference_with_grad():
    x = x_data.requires_grad_(True)

    # Forward: checkpoint node computed here
    z = torch.utils.checkpoint.checkpoint(lambda a: torch.sin(a), x)
    loss = z.sum()

    # Backward: checkpoint node only used here
    dx = torch.autograd.grad(loss, x)[0]
    return dx
```

Without optimization, the checkpointed `sin(x)` is computed during forward and held in memory until backward. This wastes memory if it's only needed in backward.

Adds `rematerialize_ac_nodes()` pass that:

1. **Duplicates AC nodes used in both forward/backward**: Keeps in forward, recomputes in backward

The pass is controlled by the config flag `torch._functorch.config.enable_inference_mode_ac_reordering` (default: `False`).

The pass works in several steps:

1. **Find backward boundary**: Identify where backward computation starts using metadata annotations
2. **Categorize AC nodes**: Classify each AC node based on usage
3. **Rebuild graph**:
   - Backward: Duplicate AC chains for nodes used in both forward and backward while maintaining original order
4. **DCE** Use DCE to clean up forward nodes since some of them are only used in backward.

**User code:**
```python
def inference_with_grad(arg0_1, arg1_1):
    # Checkpointed computation
    z = torch.utils.checkpoint.checkpoint(
        lambda a, b: torch.sigmoid(torch.mm(a, b)),
        arg0_1, arg1_1,
        use_reentrant=False
    )
    loss = z.sum()

    # Backward in same graph
    with torch.fx.traceback.annotate({"backward": 0}):
        grads = torch.autograd.grad(loss, (arg0_1, arg1_1))
    return grads
```

**Compiled graph without AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed in forward
detach = sigmoid.detach()                # Saved for backward
sum_1 = sigmoid.sum()

# Backward
sigmoid_backward = ...  # Uses saved sigmoid (held in memory since forward)
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=3, sigmoid=1
# Memory: sigmoid held from forward through backward
```

**Compiled graph with AC reordering:**
```python
# Forward
mm = torch.mm(arg0_1, arg1_1)
sigmoid = torch.sigmoid(mm)             # AC node computed for sum
sum_1 = sigmoid.sum()                    # Used in forward, then freed

# Backward - AC nodes recomputed just-in-time
mm_recomputed = torch.mm(arg0_1, arg1_1)              # Recompute
sigmoid_recomputed = torch.sigmoid(mm_recomputed)      # Recompute
detach = sigmoid_recomputed.detach()                   # Use recomputed version
sigmoid_backward = ...
mm_1 = torch.mm(t, sigmoid_backward)
mm_2 = torch.mm(sigmoid_backward, t_1)

# Operation counts: mm=4, sigmoid=2
# Memory: sigmoid freed after forward, recomputed just-in-time
```

We tested on a synthetic large model which looks like:
```python
def large_model(x, weights):
    """
    Large model with multiple checkpointed transformer blocks.
    Simulates a model with ~6 checkpointed layers.
    """
    # Initial projection
    x = torch.sin(x)

    # Checkpointed block 1
    w1_1, w1_2, w1_3, w1_4 = weights[0:4]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w1_1, w1_2, w1_3, w1_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 2
    w2_1, w2_2, w2_3, w2_4 = weights[4:8]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w2_1, w2_2, w2_3, w2_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 3
    w3_1, w3_2, w3_3, w3_4 = weights[8:12]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w3_1, w3_2, w3_3, w3_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 4
    w4_1, w4_2, w4_3, w4_4 = weights[12:16]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w4_1, w4_2, w4_3, w4_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 5
    w5_1, w5_2, w5_3, w5_4 = weights[16:20]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w5_1, w5_2, w5_3, w5_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    # Checkpointed block 6
    w6_1, w6_2, w6_3, w6_4 = weights[20:24]
    x = torch.utils.checkpoint.checkpoint(
        transformer_block, x, w6_1, w6_2, w6_3, w6_4, use_reentrant=False
    )
    x = torch.nn.functional.layer_norm(x, x.shape[-1:])

    return x
```

The naive inference graph has peak memory of 2700MB while with reordering pass, we achieve around 1100MB which is more or less same as eager peak memory.

**Next Steps**
Currently, we manually annotate the backward region using fx annotation API, but we should automatically tag them when torchdynamo encounter torch.autograd.grad.

Pull Request resolved: #168082
Approved by: https://github.com/soulitzer
@github-actions
github-actions Bot deleted the gh/tugsbayasgalan/82/head branch January 4, 2026 02:21
tugsbayasgalan added a commit to pytorch/torchtitan that referenced this pull request May 7, 2026
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() +
node_copy of every node) and relied on whole-graph DCE to remove dead
must_recompute originals. Refactor to mutate gm.graph in place: dups
are inserted in front of their first backward consumer, backward args
are redirected to the dups, and only originals whose users became
empty are erased. Original node identities and names are preserved,
the topological-order assumption is explicit (input graph order
drives insertion, validated by gm.graph.lint() at the end), and the
underlying function takes the standard (gm, example_inputs) graph
pass signature.

CPU-offload reload chains are handled by hoisting (in-place move) the
chain in front of the earliest dup that needs it - the in-place
equivalent of upstream's "eagerly copy reload chain into the new
graph" trick. This restores offload + remat support that the local
port commit (D-equivalent of GitHub PR #3260) silently dropped: on
main today, --compile.memory_policy=budget_limited_offload crashes
with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the
freed-GPU offloaded forward tensors.

Review order:

selective_activation_remat.py - the core refactor. A pre-pass
claim_for records the first backward node that transitively reaches
each must_recompute forward node (setdefault gives first-write-wins).
The insertion loop walks gm.graph.nodes in forward order, so each
dup's must_recompute deps are already in recomputed_nodes by the
time remat_input resolves them - no explicit sort. Dups are tagged
autograd_backward=True so downstream passes treat them as
backward-region nodes. remat_input also handles the
cpu_offload_reload_node case: when a dup references an offloaded
forward node, ensure_offload_chain_before walks the bwd-region
reload chain via an explicit DFS stack, then hoists chain members in
graph (topological) order by walking the all_nodes snapshot - again
no explicit sort. moved_offload bookkeeping ensures the chain ends
up before the earliest target across multiple iterations.
raise_getitems still runs at the end for the multi-output-op memory
benefit; gm.graph.lint() validates the final graph.

common_utils.py / fsdp_passes.py - drops the _is_recomputed_node
name-suffix workaround now that dups carry autograd_backward=True
directly.

passes.py - removes the selective_activation_remat_pass wrapper
since the underlying function matches the standard signature; the
pass list references it directly.

tests/test_passes.py - adds TestSelectiveActivationRematPass with
three cases: the reviewer scenario from pytorch/pytorch#168082
(pins topological insertion order), a forward+backward consumer mix
(targeted erase keeps originals with surviving forward users), and
the offload reload chain hoist - synthesizing the actual
ao.offload / ao.reload / ao.wait_tensor graph the offload pass
produces and pinning that the chain ends up before the dup with the
dup reading from the backward wait_tensor instead of F.

Authored with Claude.

Test Plan:
Unit tests:
  pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
  -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)

End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace /
no cudagraph, with --debug.seed=42 --debug.deterministic:

  No offload (memory_policy=default):
    loss / grad_norm / peak memory at step 10 are bitwise identical
    to the main baseline (1.65096 / 21.9799 / 30.78 GiB).

  --compile.memory_policy=budget_limited_offload:
    refactor matches a baseline patched to invoke upstream remat
    directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls
    the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on
    this same configuration; the refactor incidentally fixes that
    regression.
tugsbayasgalan added a commit to pytorch/torchtitan that referenced this pull request May 7, 2026
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() +
node_copy of every node) and relied on whole-graph DCE to remove dead
must_recompute originals. Refactor to mutate gm.graph in place: dups
are inserted in front of their first backward consumer, backward args
are redirected to the dups, and only originals whose users became
empty are erased. Original node identities and names are preserved,
the topological-order assumption is explicit (input graph order
drives insertion, validated by gm.graph.lint() at the end), and the
underlying function takes the standard (gm, example_inputs) graph
pass signature.

CPU-offload reload chains are handled by hoisting (in-place move) the
chain in front of the earliest dup that needs it - the in-place
equivalent of upstream's "eagerly copy reload chain into the new
graph" trick. This restores offload + remat support that the local
port commit (D-equivalent of GitHub PR #3260) silently dropped: on
main today, --compile.memory_policy=budget_limited_offload crashes
with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the
freed-GPU offloaded forward tensors.

Review order:

selective_activation_remat.py - the core refactor. A pre-pass
claim_for records the first backward node that transitively reaches
each must_recompute forward node (setdefault gives first-write-wins).
The insertion loop walks gm.graph.nodes in forward order, so each
dup's must_recompute deps are already in recomputed_nodes by the
time remat_input resolves them - no explicit sort. Dups are tagged
autograd_backward=True so downstream passes treat them as
backward-region nodes. remat_input also handles the
cpu_offload_reload_node case: when a dup references an offloaded
forward node, ensure_offload_chain_before walks the bwd-region
reload chain via an explicit DFS stack, then hoists chain members in
graph (topological) order by walking the all_nodes snapshot - again
no explicit sort. moved_offload bookkeeping ensures the chain ends
up before the earliest target across multiple iterations.
raise_getitems still runs at the end for the multi-output-op memory
benefit; gm.graph.lint() validates the final graph.

common_utils.py / fsdp_passes.py - drops the _is_recomputed_node
name-suffix workaround now that dups carry autograd_backward=True
directly.

passes.py - removes the selective_activation_remat_pass wrapper
since the underlying function matches the standard signature; the
pass list references it directly.

tests/test_passes.py - adds TestSelectiveActivationRematPass with
three cases: the reviewer scenario from pytorch/pytorch#168082
(pins topological insertion order), a forward+backward consumer mix
(targeted erase keeps originals with surviving forward users), and
the offload reload chain hoist - synthesizing the actual
ao.offload / ao.reload / ao.wait_tensor graph the offload pass
produces and pinning that the chain ends up before the dup with the
dup reading from the backward wait_tensor instead of F.

Authored with Claude.

Test Plan:
Unit tests:
  pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
  -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)

End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace /
no cudagraph, with --debug.seed=42 --debug.deterministic:

  No offload (memory_policy=default):
    loss / grad_norm / peak memory at step 10 are bitwise identical
    to the main baseline (1.65096 / 21.9799 / 30.78 GiB).

  --compile.memory_policy=budget_limited_offload:
    refactor matches a baseline patched to invoke upstream remat
    directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls
    the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on
    this same configuration; the refactor incidentally fixes that
    regression.
tugsbayasgalan added a commit to pytorch/torchtitan that referenced this pull request May 7, 2026
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() +
node_copy of every node) and relied on whole-graph DCE to remove dead
must_recompute originals. Refactor to mutate gm.graph in place: dups
are inserted in front of their first backward consumer, backward args
are redirected to the dups, and only originals whose users became
empty are erased. Original node identities and names are preserved,
the topological-order assumption is explicit (input graph order
drives insertion, validated by gm.graph.lint() at the end), and the
underlying function takes the standard (gm, example_inputs) graph
pass signature.

CPU-offload reload chains are handled by hoisting (in-place move) the
chain in front of the earliest dup that needs it - the in-place
equivalent of upstream's "eagerly copy reload chain into the new
graph" trick. This restores offload + remat support that the local
port commit (D-equivalent of GitHub PR #3260) silently dropped: on
main today, --compile.memory_policy=budget_limited_offload crashes
with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the
freed-GPU offloaded forward tensors.

Review order:

selective_activation_remat.py - the core refactor. A pre-pass
claim_for records the first backward node that transitively reaches
each must_recompute forward node (setdefault gives first-write-wins).
The insertion loop walks gm.graph.nodes in forward order, so each
dup's must_recompute deps are already in recomputed_nodes by the
time remat_input resolves them - no explicit sort. Dups are tagged
autograd_backward=True so downstream passes treat them as
backward-region nodes. remat_input also handles the
cpu_offload_reload_node case: when a dup references an offloaded
forward node, ensure_offload_chain_before walks the bwd-region
reload chain via an explicit DFS stack, then hoists chain members in
graph (topological) order by walking the all_nodes snapshot - again
no explicit sort. moved_offload bookkeeping ensures the chain ends
up before the earliest target across multiple iterations.
raise_getitems still runs at the end for the multi-output-op memory
benefit; gm.graph.lint() validates the final graph.

common_utils.py / fsdp_passes.py - drops the _is_recomputed_node
name-suffix workaround now that dups carry autograd_backward=True
directly.

passes.py - removes the selective_activation_remat_pass wrapper
since the underlying function matches the standard signature; the
pass list references it directly.

tests/test_passes.py - adds TestSelectiveActivationRematPass with
three cases: the reviewer scenario from pytorch/pytorch#168082
(pins topological insertion order), a forward+backward consumer mix
(targeted erase keeps originals with surviving forward users), and
the offload reload chain hoist - synthesizing the actual
ao.offload / ao.reload / ao.wait_tensor graph the offload pass
produces and pinning that the chain ends up before the dup with the
dup reading from the backward wait_tensor instead of F.

Authored with Claude.

Test Plan:
Unit tests:
  pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
  -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)

End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace /
no cudagraph, with --debug.seed=42 --debug.deterministic:

  No offload (memory_policy=default):
    loss / grad_norm / peak memory at step 10 are bitwise identical
    to the main baseline (1.65096 / 21.9799 / 30.78 GiB).

  --compile.memory_policy=budget_limited_offload:
    refactor matches a baseline patched to invoke upstream remat
    directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls
    the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on
    this same configuration; the refactor incidentally fixes that
    regression.
tugsbayasgalan added a commit to pytorch/torchtitan that referenced this pull request May 8, 2026
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() +
node_copy of every node) and relied on whole-graph DCE to remove dead
must_recompute originals. Refactor to mutate gm.graph in place: dups
are inserted in front of their first backward consumer, backward args
are redirected to the dups, and only originals whose users became
empty are erased. Original node identities and names are preserved,
the topological-order assumption is explicit (input graph order
drives insertion, validated by gm.graph.lint() at the end), and the
underlying function takes the standard (gm, example_inputs) graph
pass signature.

CPU-offload reload chains are handled by hoisting (in-place move) the
chain in front of the earliest dup that needs it - the in-place
equivalent of upstream's "eagerly copy reload chain into the new
graph" trick. This restores offload + remat support that the local
port commit (D-equivalent of GitHub PR #3260) silently dropped: on
main today, --compile.memory_policy=budget_limited_offload crashes
with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the
freed-GPU offloaded forward tensors.

Review order:

selective_activation_remat.py - the core refactor. A pre-pass
claim_for records the first backward node that transitively reaches
each must_recompute forward node (setdefault gives first-write-wins).
The insertion loop walks gm.graph.nodes in forward order, so each
dup's must_recompute deps are already in recomputed_nodes by the
time remat_input resolves them - no explicit sort. Dups are tagged
autograd_backward=True so downstream passes treat them as
backward-region nodes. remat_input also handles the
cpu_offload_reload_node case: when a dup references an offloaded
forward node, ensure_offload_chain_before walks the bwd-region
reload chain via an explicit DFS stack, then hoists chain members in
graph (topological) order by walking the all_nodes snapshot - again
no explicit sort. moved_offload bookkeeping ensures the chain ends
up before the earliest target across multiple iterations.
raise_getitems still runs at the end for the multi-output-op memory
benefit; gm.graph.lint() validates the final graph.

common_utils.py / fsdp_passes.py - drops the _is_recomputed_node
name-suffix workaround now that dups carry autograd_backward=True
directly.

passes.py - removes the selective_activation_remat_pass wrapper
since the underlying function matches the standard signature; the
pass list references it directly.

tests/test_passes.py - adds TestSelectiveActivationRematPass with
three cases: the reviewer scenario from pytorch/pytorch#168082
(pins topological insertion order), a forward+backward consumer mix
(targeted erase keeps originals with surviving forward users), and
the offload reload chain hoist - synthesizing the actual
ao.offload / ao.reload / ao.wait_tensor graph the offload pass
produces and pinning that the chain ends up before the dup with the
dup reading from the backward wait_tensor instead of F.

Authored with Claude.

Test Plan:
Unit tests:
  pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
  -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)

End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace /
no cudagraph, with --debug.seed=42 --debug.deterministic:

  No offload (memory_policy=default):
    loss / grad_norm / peak memory at step 10 are bitwise identical
    to the main baseline (1.65096 / 21.9799 / 30.78 GiB).

  --compile.memory_policy=budget_limited_offload:
    refactor matches a baseline patched to invoke upstream remat
    directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls
    the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on
    this same configuration; the refactor incidentally fixes that
    regression.
tugsbayasgalan added a commit to pytorch/torchtitan that referenced this pull request May 8, 2026
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() +
node_copy of every node) and relied on whole-graph DCE to remove dead
must_recompute originals. Refactor to mutate gm.graph in place: dups
are inserted in front of their first backward consumer, backward args
are redirected to the dups, and only originals whose users became
empty are erased. Original node identities and names are preserved,
the topological-order assumption is explicit (input graph order
drives insertion, validated by gm.graph.lint() at the end), and the
underlying function takes the standard (gm, example_inputs) graph
pass signature.

CPU-offload reload chains are handled by hoisting (in-place move) the
chain in front of the earliest dup that needs it - the in-place
equivalent of upstream's "eagerly copy reload chain into the new
graph" trick. This restores offload + remat support that the local
port commit (D-equivalent of GitHub PR #3260) silently dropped: on
main today, --compile.memory_policy=budget_limited_offload crashes
with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the
freed-GPU offloaded forward tensors.

Review order:

selective_activation_remat.py - the core refactor. A pre-pass
claim_for records the first backward node that transitively reaches
each must_recompute forward node (setdefault gives first-write-wins).
The insertion loop walks gm.graph.nodes in forward order, so each
dup's must_recompute deps are already in recomputed_nodes by the
time remat_input resolves them - no explicit sort. Dups are tagged
autograd_backward=True so downstream passes treat them as
backward-region nodes. remat_input also handles the
cpu_offload_reload_node case: when a dup references an offloaded
forward node, ensure_offload_chain_before walks the bwd-region
reload chain via an explicit DFS stack, then hoists chain members in
graph (topological) order by walking the all_nodes snapshot - again
no explicit sort. moved_offload bookkeeping ensures the chain ends
up before the earliest target across multiple iterations.
raise_getitems still runs at the end for the multi-output-op memory
benefit; gm.graph.lint() validates the final graph.

common_utils.py / fsdp_passes.py - drops the _is_recomputed_node
name-suffix workaround now that dups carry autograd_backward=True
directly.

passes.py - removes the selective_activation_remat_pass wrapper
since the underlying function matches the standard signature; the
pass list references it directly.

tests/test_passes.py - adds TestSelectiveActivationRematPass with
three cases: the reviewer scenario from pytorch/pytorch#168082
(pins topological insertion order), a forward+backward consumer mix
(targeted erase keeps originals with surviving forward users), and
the offload reload chain hoist - synthesizing the actual
ao.offload / ao.reload / ao.wait_tensor graph the offload pass
produces and pinning that the chain ends up before the dup with the
dup reading from the backward wait_tensor instead of F.

Authored with Claude.

Test Plan:
Unit tests:
  pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
  -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)

End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace /
no cudagraph, with --debug.seed=42 --debug.deterministic:

  No offload (memory_policy=default):
    loss / grad_norm / peak memory at step 10 are bitwise identical
    to the main baseline (1.65096 / 21.9799 / 30.78 GiB).

  --compile.memory_policy=budget_limited_offload:
    refactor matches a baseline patched to invoke upstream remat
    directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls
    the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on
    this same configuration; the refactor incidentally fixes that
    regression.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants