Repository: pytorch
Issue: FSDP + gradient clipping raises an odd warning with the simplest model on torch 2.0
Labels: oncall: distributed,triaged,module: fsdp

### 🐛 Describe the bug

if I wrap a model really simply e.g.

```
model = FullyShardedDataParallel(model,
                                 auto_wrap_policy=_auto_wrap_policy,
                                 device_id=torch.cuda.current_device(),
                                 )
```
do some training, then clip gradients via:
```
for module in model.modules():
    if isinstance(module, FullyShardedDataParallel):
        module.clip_grad_norm_(max_norm=0.1197)
```
It gives me this scary warning:

/mnt/workdisk/brandon/envs/fsdp_generate/lib/python3.10/site-packages/torch/distributed/fsdp/_common_utils.py:291: UserWarning: An unexpected prefix is detected. This case  should only happen when using DMP with FSDP. prefix = _fsdp_wrapped_module.softmax., submodule_name = _fsdp_wrapped_module

To minimally repo:

```
import os
from datetime import timedelta

import torch
import torch.nn as nn
import torch.distributed as dist
from torch.distributed.fsdp import FullyShardedDataParallel
from torch.distributed.fsdp.api import ShardingStrategy
import torch.multiprocessing as mp

import logging

DEVICE_TYPE="cuda"


def setup(rank, world_size, use_cuda=True):
    logging.getLogger().setLevel(logging.DEBUG if rank == 0 else logging.CRITICAL)

    print(f"init for rank {rank}")
    if use_cuda:
        dist.init_process_group("nccl", rank=rank, world_size=world_size, timeout=timedelta(seconds=5))
    else:
        dist.init_process_group("gloo", rank=rank, world_size=world_size, timeout=timedelta(seconds=5))

    # set device for nccl pg for collectives
    if use_cuda == "nccl":
        print(f"--> init device for rank {rank}")
        torch.cuda.set_device(rank)
    print (f"finished init for rank {rank}")

def _auto_wrap_policy(module: torch.nn.Module, recurse: bool, nonwrapped_numel: int) -> bool:
    if recurse:
        return True
    if hasattr(module, '_fsdp_wrap'):
        return bool(module._fsdp_wrap)
    return False

def simple_model_with_grads():
    # Set up small NN with one linear layer with no bias + softmax, so only
    # one set of params and get some gradients.
    N, hin, num_classes = 8, 4, 3
    x = torch.rand((N, hin))
    y = torch.randint(high=num_classes - 1, size=(N,))
    model = nn.Sequential(nn.Linear(hin, num_classes, bias=False), nn.Softmax(dim=1))

    # Force wrap every module in FSDP, to allow for testing FSDP
    # gradient clipping properly.
    for module in model.modules():
        module._fsdp_wrap = True

    model._fsdp_wrap = True
    model = FullyShardedDataParallel(model,
                                    sharding_strategy=ShardingStrategy.FULL_SHARD,
                                    auto_wrap_policy=_auto_wrap_policy,
                                    device_id=torch.cuda.current_device(),
                                    )

    o = model(x)
    loss_fn = nn.CrossEntropyLoss()
    loss = loss_fn(o, y)
    loss.backward()
    return model


def work_main(rank):
    model = simple_model_with_grads()

    for module in model.modules():
        if isinstance(module, FullyShardedDataParallel):
            module.clip_grad_norm_(max_norm=0.1197)


def main(rank, world_size, use_cuda=True):
    setup(rank, world_size, use_cuda)
    work_main(rank)


if __name__ == "__main__":
    os.environ["MASTER_ADDR"] = "localhost"
    # os.environ["MASTER_PORT"] = "29506"
    world_size = 2
    use_cuda = DEVICE_TYPE == "cuda"
    print(f"use_cuda == {use_cuda}")
    process = mp.spawn(main, args=(world_size,), nprocs=world_size, join=True)
    process.join()
```

### Versions

Collecting environment information...
PyTorch version: 2.0.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
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.26.3
Libc version: glibc-2.31

Python version: 3.10.10 (main, Feb  8 2023, 14:50:01) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-137-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.7.99
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

Nvidia driver version: 515.48.07
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.5.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:                   48 bits physical, 48 bits virtual
CPU(s):                          64
On-line CPU(s) list:             0-63
Thread(s) per core:              1
Core(s) per socket:              32
Socket(s):                       2
NUMA node(s):                    8
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7513 32-Core Processor
Stepping:                        1
Frequency boost:                 enabled
CPU MHz:                         1499.770
CPU max MHz:                     2600.0000
CPU min MHz:                     1500.0000
BogoMIPS:                        5200.48
Virtualization:                  AMD-V
L1d cache:                       2 MiB
L1i cache:                       2 MiB
L2 cache:                        32 MiB
L3 cache:                        256 MiB
NUMA node0 CPU(s):               0-7
NUMA node1 CPU(s):               8-15
NUMA node2 CPU(s):               16-23
NUMA node3 CPU(s):               24-31
NUMA node4 CPU(s):               32-39
NUMA node5 CPU(s):               40-47
NUMA node6 CPU(s):               48-55
NUMA node7 CPU(s):               56-63
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 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, IBRS_FW, STIBP disabled, 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 pni pclmulqdq monitor ssse3 fma cx16 pcid 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 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 invpcid 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 wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca

Versions of relevant libraries:
[pip3] numpy==1.22.4
[pip3] pytorch-ranger==0.1.1
[pip3] torch==2.0.0
[pip3] torch-optimizer==0.3.0
[pip3] torchaudio==2.0.1
[pip3] torchmetrics==0.11.3
[pip3] torchtext==0.14.1
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[pip3] vit-pytorch==0.35.8
[conda] Could not collect

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