Repository: pytorch
Issue: FSDP activation CPU offload memory not cleaned up
Labels: oncall: distributed,module: memory usage,triaged

### 🐛 Describe the bug

When doing cpu offload for activations in FSDP, I expect that memory to be cleaned up after each backwards pass since the activations are no longer used. However, I'm seeing CPU memory remain high after training when offloading activations compared to no activation offload where the CPU memory is about the same before and after training.

On a 1.8 TB RAM node, I'm seeing these numbers:
No CPU offload
- 3% before training batch
- 3.8% after training batch

CPU offload
- 3.2% before training batch
- 6.3% after training batch

```python
from typing import Union
import logging
import psutil
import gc

import torch
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import apply_activation_checkpointing, offload_wrapper
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import ShardingStrategy
from torch.distributed.fsdp import CPUOffload

from composer.utils import dist, get_device

log = logging.getLogger(__name__)

PYTHON_LOG_LEVEL = 'DEBUG'

def _initialize_dist_with_barrier(dist_timeout: Union[int, float]):
    """Initialize distributed and test setup with a barrier.

    Args:
        dist_timeout (Union[int, float]): Timeout for initializing the process group
    """
    log.debug('Initializing dist with device...')
    dist.initialize_dist(get_device(None), timeout=dist_timeout)
    log.debug('Testing barrier with device...')
    dist.barrier()
    log.debug('Barrier test passed with device.')

class TinyModel(torch.nn.Module):

    def __init__(self):
        super(TinyModel, self).__init__()
        self.activation = torch.nn.ReLU()

        self.linear1 = torch.nn.Linear(10000, 20000)
        self.linear2 = torch.nn.Linear(20000, 20000)
        self.linear3 = torch.nn.Linear(20000, 20000)
        self.linear4 = torch.nn.Linear(20000, 20000)
        self.linear5 = torch.nn.Linear(20000, 10)
        self.softmax = torch.nn.Softmax()

    def forward(self, x):
        x = self.linear1(x)
        x = self.activation(x)
        x = self.linear2(x)
        x = self.activation(x)
        x = self.linear3(x)
        x = self.activation(x)
        x = self.linear4(x)
        x = self.activation(x)
        x = self.linear5(x)
        x = self.softmax(x)
        return x
    
logging.basicConfig(
    # Example of format string
    # 2022-06-29 11:22:26,152: rank0[822018][MainThread]: INFO: Message here
    format=
    f'%(asctime)s: rank{dist.get_global_rank()}[%(process)d][%(threadName)s]: %(levelname)s: %(name)s: %(message)s',
)
logging.getLogger('llmfoundry').setLevel(
    PYTHON_LOG_LEVEL.upper(),
)  # Foundry module
logging.getLogger(__name__).setLevel(
    PYTHON_LOG_LEVEL.upper(),
)  # Train script
_initialize_dist_with_barrier(dist_timeout=3600)

num_samples = 1000
X = torch.randn(num_samples, 10000)
y = torch.randint(0, 10, (num_samples,))
# Create a TensorDataset and DataLoader
dataset = torch.utils.data.TensorDataset(X, y)
data_loader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)

model = TinyModel().cuda()
# apply_activation_checkpointing(model, offload_wrapper)
model = FSDP(model, sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=True))
    
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
print('Number of parameters: ')
print(sum(p.numel() for p in model.parameters() if p.requires_grad))

print(psutil.virtual_memory())

# Training loop
num_epochs = 1
for epoch in range(num_epochs):
    for batch_idx, (inputs, targets) in enumerate(data_loader):
        # Move inputs and targets to the device
        inputs = inputs.cuda()
        targets = targets.cuda()

        # Zero the parameter gradients
        optimizer.zero_grad()

        # Forward pass
        outputs = model(inputs)
        
        # Compute loss
        loss = criterion(outputs, targets)
        
        # Backward pass and optimize
        loss.backward()
        optimizer.step()

        if batch_idx % 10 == 0:
            print(f'Epoch [{epoch+1}/{num_epochs}], Batch [{batch_idx+1}/{len(data_loader)}], Loss: {loss.item():.4f}')

        print(psutil.virtual_memory())
        torch.cuda.empty_cache()
        gc.collect()
        print(psutil.virtual_memory())
        break

print(psutil.virtual_memory())
del model
del inputs
del targets
del optimizer
del outputs
del loss
torch.cuda.empty_cache()
gc.collect()
print(psutil.virtual_memory())
``` 

### Versions

Collecting environment information...

Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              143
Model name:                         Intel(R) Xeon(R) Platinum 8480+
Stepping:                           8
CPU MHz:                            2000.000
CPU max MHz:                        3800.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4000.00
Virtualization:                     VT-x
L1d cache:                          5.3 MiB
L1i cache:                          3.5 MiB
L2 cache:                           224 MiB
L3 cache:                           210 MiB
NUMA node0 CPU(s):                  0-55,112-167
NUMA node1 CPU(s):                  56-111,168-223
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Vulnerable

pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] onnx==1.16.2
[pip3] onnxruntime==1.18.1
[pip3] pytorch-ranger==0.1.1
[pip3] torch==2.3.1+cu121
[pip3] torch-optimizer==0.3.0
[pip3] torchmetrics==1.4.0.post0
[pip3] torchvision==0.18.1+cu121
[pip3] triton==2.3.1
[conda] Could not collect

cc @XilunWu @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o