Repository navigation
Support AC rematerializing in forward+loss+bwd graph - #168082
tugsbayasgalan wants to merge 35 commits into
Conversation
[ghstack-poisoned]
🔗 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 ( 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. |
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]
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]
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]
| bwd_start = order[first_node_in_bwd] | ||
|
|
||
| # Categorize AC nodes by usage | ||
| ac_used_in_fwd: set[fx.Node] = set() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Ok i just duplicate always and DCe later.
| return x | ||
|
|
||
|
|
||
| def reorder_ac_nodes_for_inference(gm: fx.GraphModule) -> fx.GraphModule: |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).""" |
There was a problem hiding this comment.
Inference mode refers to something very specific haha.
https://docs.pytorch.org/docs/stable/generated/torch.autograd.grad_mode.inference_mode.html
There was a problem hiding this comment.
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.
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]
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]
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]
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]
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]
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 7 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10 / test (default, 2, 6, linux.rocm.gpu.gfx942.1), trunk / linux-jammy-rocm-py3.10 / test (default, 3, 6, linux.rocm.gpu.gfx942.1), trunk / linux-jammy-rocm-py3.10 / test (default, 5, 6, linux.rocm.gpu.gfx942.1), trunk / linux-jammy-rocm-py3.10 / test (default, 6, 6, linux.rocm.gpu.gfx942.1), trunk / linux-jammy-rocm-py3.10 / test (default, 1, 6, linux.rocm.gpu.gfx942.1) Details for Dev Infra teamRaised by workflow job |
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]
|
@pytorchbot merge |
Merge startedYour 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 |
|
Did this PR remove some functionality? Torchtitan CI fails with latest nightly: https://github.com/pytorch/torchtitan/actions/runs/19928440269/job/57133996697#step:16:9026 |
| if _is_backward_node(node) and bwd_start is None: | ||
| bwd_start = idx | ||
|
|
||
| if bwd_start is None: |
There was a problem hiding this comment.
@tugsbayasgalan we should lift this up before the RNG check
There was a problem hiding this comment.
and then only warn IF there are recomputable ops
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
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.
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.
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.
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.
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.
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:
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:The pass is controlled by the config flag
torch._functorch.config.enable_inference_mode_ac_reordering(default:False).The pass works in several steps:
User code:
Compiled graph without AC reordering:
Compiled graph with AC reordering:
We tested on a synthetic large model which looks like:
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