Repository: pytorch
Issue: OOM when saving model(lora adapter), seems the clause "FullyShardedDataParallel(model,...)" will directly cause the OOM.
Labels: oncall: distributed,module: memory usage,triaged,module: fsdp

### 🐛 Describe the bug

I am using llama-recipes to finetune LLMs.
After training 34B-codellama2 with LoRA(the training went on well), I got OOM error when model.save_pretrained.
I tried different PEFT versions, from v 0.3.0 to source code, do not work.
It is said PEFT-0.2.0 will work, but llama-recipes can't work with PEFT-0.2.0

I don't know the root cause of the problem( llama-recipes, PEFT, or FSDP from pytorch ?) , so I submitted this issue to pytorch and llama-recipes. Hope someone can help!

I modified the code and added save_pretrained just after the model loaded.
It shows that OOM occurs just after FSDP(FullyShardedDataParallel) operation, it's nothing to do with the training process.


    from torch.distributed.fsdp import (
        FullyShardedDataParallel as FSDP,
    )
    ##some codes  omitted
    mixed_precision_policy, wrapping_policy = get_policies(fsdp_config, rank)
    my_auto_wrapping_policy = fsdp_auto_wrap_policy(model, LlamaDecoderLayer)
    ### add save model before FSDP
    print("before FSDP save model")
    model.save_pretrained("./test_pretrained1")
    model = FSDP(
        model,
        auto_wrap_policy= my_auto_wrapping_policy if train_config.use_peft else wrapping_policy,
        cpu_offload=CPUOffload(offload_params=True) if fsdp_config.fsdp_cpu_offload else None,
        mixed_precision=mixed_precision_policy if not fsdp_config.pure_bf16 else None,
        sharding_strategy=fsdp_config.sharding_strategy,
        device_id=torch.cuda.current_device(),
        limit_all_gathers=True,
        #add use_orig_params=True for adapter#
        #use_orig_params=True,
        sync_module_states=train_config.low_cpu_fsdp,
        param_init_fn=lambda module: module.to_empty(device=torch.device("cuda"), recurse=False)
        if train_config.low_cpu_fsdp and rank != 0 else None,
    )
    ### add save model after FSDP
    print("after FSDP save model")
    model.save_pretrained("./test_pretrained2")

Error logs:

before FSDP save model
trainable params: 19,660,800 || all params: 33,763,631,104 || trainable%: 0.05823070373989121
before FSDP save model
trainable params: 19,660,800 || all params: 33,763,631,104 || trainable%: 0.05823070373989121
before FSDP save model
trainable params: 19,660,800 || all params: 33,763,631,104 || trainable%: 0.05823070373989121
before FSDP save model
^MLoading checkpoint shards: 0%| | 0/7 [00:00<?, ?it/s]^MLoading checkpoint shards: 14%|█▍ | 1/7 [00:07<00:45, 7.64s/it]^MLoading checkpoint shards: 29%|██▊ | 2/7 [00:14<00:37, 7.48s/it]^MLoading checkpoint shards: 43%|████▎ | 3/7 [00:22<00:29, 7.50s/it]^MLoading checkpoint shards: 57%|█████▋ | 4/7 [00:29<00:22, 7.47s/it]^MLoading checkpoint shards: 71%|███████▏ | 5/7 [00:37<00:15, 7.64s/it]^MLoading checkpoint shards: 86%|████████▌ | 6/7 [00:45<00:07, 7.52s/it]^MLoading checkpoint shards: 100%|██████████| 7/7 [00:52<00:00, 7.42s/it]^MLoading checkpoint shards: 100%|██████████| 7/7 [00:52<00:00, 7.49s/it]
--> Model /mnt/shhg01/cyris/model_hub/codellama34B_chat/

--> /mnt/shhg01/cyris/model_hub/codellama34B_chat/ has 33743.970304 Million params

paras distr: 435 0
LoraConfig(peft_type=<PeftType.LORA: 'LORA'>, auto_mapping=None, base_model_name_or_path=None, revision=None, task_type='CAUSAL_LM', inference_mode=False, r=16, target_modules=['q_proj', 'v_proj'], lora_alpha=32, lora_dropout=0.05, fan_in_fan_out=False, bias='none', modules_to_save=None, init_lora_weights=True, layers_to_transform=None, layers_pattern=None)
trainable params: 19,660,800 || all params: 33,763,631,104 || trainable%: 0.05823070373989121
bFloat16 enabled for mixed precision - using bfSixteen policy
before FSDP save model
after FSDP save model
after FSDP save model
Traceback (most recent call last):
File "/mnt/shhg01/cyris/univista-llm-train/ft/lora/finetuning.py", line 8, in
Traceback (most recent call last):
File "/mnt/shhg01/cyris/univista-llm-train/ft/lora/finetuning.py", line 8, in
fire.Fire(main)
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 141, in Fire
fire.Fire(main)
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 141, in Fire
component_trace = _Fire(component, args, parsed_flag_args, context, name)
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 475, in _Fire
component_trace = _Fire(component, args, parsed_flag_args, context, name)
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 475, in _Fire
component, remaining_args = _CallAndUpdateTrace(
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 691, in _CallAndUpdateTrace
component, remaining_args = _CallAndUpdateTrace(
File "/mnt/shhg01/env/llama-recipes/lib/python3.10/site-packages/fire/core.py", line 691, in _CallAndUpdateTrace
component = fn(*varargs, **kwargs)
File "/mnt/shhg01/cyris/univista-llm-train/ft/lora/llama_recipes/finetuning.py", line 204, in main
component = fn(*varargs, **kwargs)
File "/mnt/shhg01/cyris/univista-llm-train/ft/lora/llama_recipes/finetuning.py", line 204, in main
model.save_pretrained("./test_pretrained2")

...
...
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 MiB. GPU 6 has a total capacty of 39.59 GiB of which 1.12 MiB is free. Process 3377172 has 39.58 GiB memory in use. Of the allocated memory 38.18 GiB is allocated by PyTorch, and 40.47 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
Exception raised from malloc at ../c10/cuda/CUDACachingAllocator.cpp:1114 (most recent call first):


### Versions

Collecting environment information...
PyTorch version: 2.2.0.dev20231012+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.24.1
Libc version: glibc-2.31

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1025-nvidia-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA A100-SXM4-40GB
GPU 1: NVIDIA A100-SXM4-40GB
GPU 2: NVIDIA A100-SXM4-40GB
GPU 3: NVIDIA A100-SXM4-40GB
GPU 4: NVIDIA A100-SXM4-40GB
GPU 5: NVIDIA A100-SXM4-40GB
GPU 6: NVIDIA A100-SXM4-40GB
GPU 7: NVIDIA A100-SXM4-40GB

Nvidia driver version: 515.86.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.7.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   43 bits physical, 48 bits virtual
CPU(s):                          256
On-line CPU(s) list:             0-255
Thread(s) per core:              2
Core(s) per socket:              64
Socket(s):                       2
NUMA node(s):                    8
Vendor ID:                       AuthenticAMD
CPU family:                      23
Model:                           49
Model name:                      AMD EPYC 7742 64-Core Processor
Stepping:                        0
Frequency boost:                 enabled
CPU MHz:                         2250.000
CPU max MHz:                     2250.0000
CPU min MHz:                     1500.0000
BogoMIPS:                        4491.36
Virtualization:                  AMD-V
L1d cache:                       4 MiB
L1i cache:                       4 MiB
L2 cache:                        64 MiB
L3 cache:                        512 MiB
NUMA node0 CPU(s):               0-15,128-143
NUMA node1 CPU(s):               16-31,144-159
NUMA node2 CPU(s):               32-47,160-175
NUMA node3 CPU(s):               48-63,176-191
NUMA node4 CPU(s):               64-79,192-207
NUMA node5 CPU(s):               80-95,208-223
NUMA node6 CPU(s):               96-111,224-239
NUMA node7 CPU(s):               112-127,240-255
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:          Mitigation; untrained return thunk; SMT enabled with STIBP protection
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sme sev sev_es

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.0
[pip3] pytorch-triton==2.1.0+6e4932cda8
[pip3] torch==2.2.0.dev20231012+cu118
[pip3] torchaudio==2.2.0.dev20231012+cu118
[pip3] torchvision==0.17.0.dev20231012+cu118
[pip3] triton==2.1.0
[conda] numpy                     1.26.0                   pypi_0    pypi
[conda] pytorch-triton            2.1.0+6e4932cda8          pypi_0    pypi
[conda] torch                     2.2.0.dev20231012+cu118          pypi_0    pypi
[conda] torchaudio                2.2.0.dev20231012+cu118          pypi_0    pypi
[conda] torchvision               0.17.0.dev20231012+cu118          pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi




cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin