Repository: pytorch
Issue: [FSDP]  When amp is enabled, there is a noticeable difference during training between `FSDP `and `DDP`
Labels: triaged,module: fsdp

### 🐛 Describe the bug

 When enabling amp training with PyTorch native autocast, I noticed there seems to be obvious difference for DDP based model and FSDP based model.

Here is a minimum example to reproduce the case:

```python
import copy
import os

import torch
import torch.nn as nn
from torch.cuda.amp import GradScaler, autocast
from torch.distributed import init_process_group
from torch.distributed.fsdp.fully_sharded_data_parallel import \
    FullyShardedDataParallel as FSDP
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.optim import AdamW


def build_optimizer(model: nn.Module, paramwise=True):
    base_lr = 1e-4
    if paramwise:
        param_groups = []
        for name, param in model.named_parameters():
            if name.endswith('weight'):
                param_groups.append({'params': [param], 'lr': base_lr * 0.1})
            else:
                param_groups.append({'params': [param], 'lr': base_lr})
        optimizer = AdamW(param_groups, lr=base_lr)
    else:
        optimizer = AdamW(model.parameters(), lr=base_lr)
    return optimizer



class ToyModel(nn.Module):

    def __init__(self, data_preprocessor=None):
        super().__init__()
        self.linear1 = nn.Linear(2, 2)
        self.norm = nn.BatchNorm1d(2)
        self.linear2 = nn.Linear(2, 1)

    def forward(self, inputs):
        if isinstance(inputs, list):
            inputs = torch.stack(inputs)
        outputs = self.linear1(inputs)
        outputs = self.norm(outputs)
        outputs = self.linear2(outputs)
        return outputs


if __name__ == '__main__':
    init_process_group()
    torch.cuda.set_device(int(os.getenv('LOCAL_RANK')))
    # model: nn.Module = MODELS.build(cfg.model)
    model1 = ToyModel().cuda()
    model2 = copy.deepcopy(model1)
    # train_dataloader = Runner.train_dataloader()
    device_id = torch.cuda.current_device()
    ddp_model = DDP(model1, device_ids=[device_id])
    fsdp_model = FSDP(model2, device_id=device_id, use_orig_params=True, sync_module_states=True)
    ddp_optim_wrapper = build_optimizer(ddp_model)
    fsdp_optim_wrapper = build_optimizer(fsdp_model)
    ddp_scaler = GradScaler()
    fsdp_scaler = GradScaler()
    with autocast():
        for step in range(10):
            data = torch.randn(2, 2).to(f'cuda:{device_id}')
            ddp_loss = ddp_model(data).sum()
            fsdp_loss = fsdp_model(data).sum()

            ddp_scaler.scale(ddp_loss).backward()
            fsdp_scaler.scale(fsdp_loss).backward()

            ddp_scaler.step(ddp_optim_wrapper)
            ddp_scaler.update()
            fsdp_scaler.step(fsdp_optim_wrapper)
            fsdp_scaler.update()

            ddp_optim_wrapper.zero_grad()
            fsdp_optim_wrapper.zero_grad()
            
            print(f'step: {step} rank: {device_id} ddp_loss: {ddp_loss}, fsdp_loss: {fsdp_loss}')

```

run the script by

```bash
torchrun --nproc-per-node 4 work_dirs/test.py
```

You'll find the ddp_loss is different form the fsdp_loss obviously, however, this will not happen when training with fp32. Such error caused my model to converge normally when using DDP, but encounter NaN losses when using FSDP.

I've read the introduction of FSDP [here](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html?highlight=fsdp). I find the discrepancy/error to be unusual since the gathered parameters supplied to operations such as conv and linear in FSDP should be identical to those in DDP. 

I've also tried to replace `GradScalar` with `ShardedGradScaler` for ddp_scaler, but the difference still exists.

### Versions

Collecting environment information...
PyTorch version: 2.0.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: CentOS Linux 7 (Core) (x86_64)
GCC version: (GCC) 8.5.0
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.17

Python version: 3.10.9 (main, Mar  8 2023, 10:47:38) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-3.10.0-957.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.6.124
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB
GPU 4: NVIDIA A100-SXM4-80GB
GPU 5: NVIDIA A100-SXM4-80GB
GPU 6: NVIDIA A100-SXM4-80GB
GPU 7: NVIDIA A100-SXM4-80GB

Nvidia driver version: 515.65.01
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):                256
On-line CPU(s) list:   0-255
Thread(s) per core:    2
Core(s) per socket:    64
Socket(s):             2
NUMA node(s):          2
Vendor ID:             AuthenticAMD
CPU family:            23
Model:                 49
Model name:            AMD EPYC 7742 64-Core Processor
Stepping:              0
CPU MHz:               2250.000
CPU max MHz:           2250.0000
CPU min MHz:           1500.0000
BogoMIPS:              4491.42
Virtualization:        AMD-V
L1d cache:             32K
L1i cache:             32K
L2 cache:              512K
L3 cache:              16384K
NUMA node0 CPU(s):     0-63,128-191
NUMA node1 CPU(s):     64-127,192-255
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 art rep_good nopl xtopology nonstop_tsc extd_apicid aperfmperf eagerfpu 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_l2 cpb cat_l3 cdp_l3 hw_pstate sme retpoline_amd ssbd ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif umip overflow_recov succor smca

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.23.5
[pip3] pytorch-lightning==2.0.0
[pip3] pytorch-sphinx-theme==0.0.24
[pip3] torch==2.0.0+cu118
[pip3] torch-tb-profiler==0.4.1
[pip3] torchaudio==2.0.1+cu118
[pip3] torchdistx==0.3.0.dev0+cu118
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.1+cu118
[conda] Could not collect

cc @zhaojuanmao @mrshenli @rohan-varma @awgu