Repository: pytorch
Issue: [DDP] Gradient Synchronization Failure Induced by model.gradient_checkpointing_enable() in multi-task setting
Labels: oncall: distributed,module: ddp

### 🐛 Describe the bug

Hello, when I am using DDP to train a model, I found that using multi-task loss and gradient checkpointing at the same time can lead to gradient synchronization failure between GPUs, which in turn causes the parameters of the model on different GPUs to be inconsistent. 

Environment:
```
conda create -n bug python=3.10 -y
conda activate bug
conda install pytorch==2.2.0 pytorch-cuda=12.1 -c pytorch -c nvidia
pip install transformers==4.36.2 datasets==2.16.1 peft==0.9.0 accelerate==0.25.0
```

A minimal example:
```python
from transformers import Seq2SeqTrainer,Seq2SeqTrainingArguments
import transformers
from datasets import Dataset
import torch.distributed as dist
import torch


class CustomMultitaskSeq2SeqTrainer(Seq2SeqTrainer):
    def compute_loss(self, model, inputs):
        # here print the info of model
        dist.barrier()
        for name, param in model.named_parameters():
            if 'lora_B' in name:
                order_of_para = torch.mean(torch.abs(param.data))
                print(f"=============| ({name}) |==============\nparam.data[:1,:3]:{param.data[:1,:3]}\n|order_of_para:{order_of_para}|device:{param.device}\n========")
                break
        dist.barrier()

        loss = None
        for inp in inputs:
            outputs = model(**inp)
            if loss is None:
                loss = 0.5*outputs.loss
            else:
                loss += 0.5*outputs.loss
        return loss

def get_model():
    from transformers.models.llama.configuration_llama import LlamaConfig
    from transformers.models.llama.modeling_llama import LlamaForCausalLM
    cfg = LlamaConfig(vocab_size=32000,hidden_size=32,intermediate_size=256,num_hidden_layers=4,num_attention_heads=4,torch_dtype=torch.float16)
    model = LlamaForCausalLM(cfg)

    ################  The culprit is here
    model.gradient_checkpointing_enable()

    from peft import get_peft_model, LoraConfig, TaskType

    lora_config = LoraConfig(
        task_type=TaskType.CAUSAL_LM,
        inference_mode=False,
        r=4,
        target_modules="all-linear",
        lora_alpha=8,
        lora_dropout=0
    )
    model = get_peft_model(model, lora_config)
    return model


def gen():
    for i in range(256):
        inputs_ids = torch.randint(0, 100, (4,))
        labels = inputs_ids.clone().detach()
        labels[:2] = -100
        attention_mask = torch.ones(4,).bool()
        yield {
            'input_ids': inputs_ids,
            'labels': labels,
            'attention_mask': attention_mask                
        }

def collate_fn(examples):
    # print(examples)
    batch1 = {
        'input_ids': torch.LongTensor([example['input_ids'] for example in examples]),
        'labels': torch.LongTensor([example['labels'] for example in examples]),
        'attention_mask': torch.BoolTensor([example['attention_mask'] for example in examples]) 
    }

    batch2 = {
        'input_ids': torch.LongTensor([example['input_ids'] for example in examples]) + 1,
        'labels': torch.LongTensor([example['input_ids'] for example in examples]) + 1,
        'attention_mask': torch.BoolTensor([example['attention_mask'] for example in examples])    
    }
    # return [batch1]
    return [batch1, batch2]

model = get_model()
dataset = Dataset.from_generator(gen)
training_args = Seq2SeqTrainingArguments(**{
    "output_dir": "debug",
    "learning_rate": 0.0001, 
    "num_train_epochs": 1, 
    "per_device_train_batch_size": 1,
    'ddp_find_unused_parameters': False,  
 })


trainer = CustomMultitaskSeq2SeqTrainer(
        model=model,
        args=training_args,
        train_dataset = dataset,
        data_collator = collate_fn
    )

trainer.train()

```

I run this code using this command:
```
CUDA_VISIBLE_DEVICES=6,7 accelerate launch --config_file debug.yaml debug.py > debug.log
```

And this is the debug.yaml:
```
compute_environment: LOCAL_MACHINE
deepspeed_config: {}
distributed_type: MULTI_GPU
fsdp_config: {}
machine_rank: 0
main_process_ip: 'localhost'
main_process_port: 6355
main_training_function: main
mixed_precision: 'no'
num_machines: 1
num_processes: 2
use_cpu: false
```

debug.log will got that:
```
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[0., 0., 0.]], device='cuda:1')
|order_of_para:0.0|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[0., 0., 0.]], device='cuda:0')
|order_of_para:0.0|device:cuda:0
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 9.9993e-05, -9.9998e-05, -9.9996e-05]], device='cuda:1')
|order_of_para:9.998951281886548e-05|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[-9.9985e-05, -9.9998e-05, -9.9996e-05]], device='cuda:0')
|order_of_para:9.997833694797009e-05|device:cuda:0
========
```
We can see the parameters in cuda:0 is different in cuda:1

When I comment out `model.gradient_checkpointing_enable()` or When I `return [batch1]` (single task) , We can see the parameters in cuda:0 is the same of they in cuda:1:
```
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[0., 0., 0.]], device='cuda:1')
|order_of_para:0.0|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[0., 0., 0.]], device='cuda:0')
|order_of_para:0.0|device:cuda:0
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 9.9998e-05, -9.9995e-05,  9.9991e-05]], device='cuda:0')
|order_of_para:9.998271707445383e-05|device:cuda:0
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 9.9998e-05, -9.9995e-05,  9.9991e-05]], device='cuda:1')
|order_of_para:9.998271707445383e-05|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 0.0001, -0.0002,  0.0002]], device='cuda:1')
|order_of_para:0.00014921455294825137|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 0.0001, -0.0002,  0.0002]], device='cuda:0')
|order_of_para:0.00014921455294825137|device:cuda:0
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 8.0596e-05, -2.1637e-04,  2.8182e-04]], device='cuda:1')
|order_of_para:0.00018701126100495458|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 8.0596e-05, -2.1637e-04,  2.8182e-04]], device='cuda:0')
|order_of_para:0.00018701126100495458|device:cuda:0
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 2.3299e-05, -2.3314e-04,  3.0890e-04]], device='cuda:1')
|order_of_para:0.0002144069003406912|device:cuda:1
========
=============| (module.base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight) |==============
param.data[:1,:3]:tensor([[ 2.3299e-05, -2.3314e-04,  3.0890e-04]], device='cuda:0')
|order_of_para:0.0002144069003406912|device:cuda:0
```

When I comment out `'ddp_find_unused_parameters': False,` or the peft code, We got a RuntimeError. The error message seems to be related to this issue:

```
Traceback (most recent call last):
  File "/home/liuxinyu/debug/debug.py", line 97, in <module>
    trainer.train()
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 1537, in train
Traceback (most recent call last):
  File "/home/liuxinyu/debug/debug.py", line 97, in <module>
    return inner_training_loop(
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 1854, in _inner_training_loop
    trainer.train()
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 1537, in train
    tr_loss_step = self.training_step(model, inputs)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 2744, in training_step
    return inner_training_loop(
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 1854, in _inner_training_loop
    tr_loss_step = self.training_step(model, inputs)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/transformers/trainer.py", line 2744, in training_step
    self.accelerator.backward(loss)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/accelerate/accelerator.py", line 1905, in backward
    loss.backward(**kwargs)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/torch/_tensor.py", line 522, in backward
    torch.autograd.backward(    
self.accelerator.backward(loss)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/torch/autograd/__init__.py", line 266, in backward
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/accelerate/accelerator.py", line 1905, in backward
    Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/torch/autograd/function.py", line 289, in apply
    return user_fn(self, *args)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 319, in backward
    torch.autograd.backward(outputs_with_grad, args_with_grad)
  File "/home/liuxinyu/anaconda3/envs/bug/lib/python3.10/site-packages/torch/autograd/__init__.py", line 266, in backward
    Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
RuntimeError    : loss.backward(**kwargs)Expected to mark a variable ready only once. This error is caused by one of the following reasons: 1) Use of a module parameter outside the `forward` function. Please make sure model parameters are not shared across multiple concurrent forward-backward passes. or try to use _set_static_graph() as a workaround if this module graph does not change during training loop.2) Reused parameters in multiple reentrant backward passes. For example, if you use multiple `checkpoint` functions to wrap the same part of your model, it would result in the same set of parameters been used by different reentrant backward passes multiple times, and hence marking a variable ready multiple times. DDP does not support such use cases in default. You can try to use _set_static_graph() as a workaround if your module graph does not change over iterations.
Parameter at index 34 with name model.layers.3.mlp.down_proj.weight has been marked as ready twice. This means that multiple autograd engine  hooks have fired for this particular parameter during this iteration.
```

I’m unsure if this is a bug or if gradient checkpointing combined with DDP is not compatible with multi-task learning.

When I disable the gradient checkpointing, it seems to be working normally now.

But I’m worried that it might not truly be functioning correctly. I want to understand what happens in the forward and backward processes when I either disable or do not disable gradient checkpointing, and why gradient checkpointing would cause a failure in gradient synchronization.

### Versions

Collecting environment information...
PyTorch version: 2.2.0
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: CentOS Linux 7 (Core) (x86_64)
GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Clang version: Could not collect
CMake version: version 2.8.12.2
Libc version: glibc-2.17

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-3.10.0-1160.88.1.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090
GPU 3: NVIDIA GeForce RTX 3090
GPU 4: NVIDIA GeForce RTX 3090
GPU 5: NVIDIA GeForce RTX 3090
GPU 6: NVIDIA GeForce RTX 3090
GPU 7: NVIDIA GeForce RTX 3090

Nvidia driver version: 535.154.05
cuDNN version: Could not collect
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
CPU(s):                96
On-line CPU(s) list:   0-95
Thread(s) per core:    2
Core(s) per socket:    24
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 85
Model name:            Intel(R) Xeon(R) Platinum 8255C CPU @ 2.50GHz
Stepping:              7
CPU MHz:               2501.000
CPU max MHz:           2501.0000
CPU min MHz:           1000.0000
BogoMIPS:              5000.00
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              1024K
L3 cache:              36608K
NUMA node0 CPU(s):     0-23,48-71
NUMA node1 CPU(s):     24-47,72-95
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov 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 aperfmperf eagerfpu 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 epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba rsb_ctxsw ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.2.0
[pip3] triton==2.2.0
[conda] blas                      1.0                         mkl  
[conda] mkl                       2023.1.0         h213fc3f_46344  
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] pytorch                   2.2.0           py3.10_cuda12.1_cudnn8.9.2_0    pytorch
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchtriton               2.2.0                     py310    pytorch

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @chauhang