Repository: pytorch
Issue:  Incomplete Parameter Gathering on Rank 0 with FSDP Model Saving
Labels: oncall: distributed,module: fsdp,module: distributed_checkpoint

### 🐛 Describe the bug

When using FSDP (Fully Sharded Data Parallel) to save a model, some parameters are not fully gathered on rank 0 and therefore not properly saved. This issue occurs specifically with the skip_connection_block component of the model.

I'm saving each module of the model using the following code:
```python
def save_model(model, model_save_path, epoch, optimizer, scaler, label_mode, rank):
    """
    Save the model, optimizer, and other components' state dictionaries for FSDP.
    """
    if rank == 0:
        print(f"Saving the model at epoch {epoch} on rank {rank}")
        
        # Create save directories
        for component in ['encoder', 'decoder', 'skip_connection_block', 'optimizer', 'scaler']:
            os.makedirs(os.path.join(model_save_path, component), exist_ok=True)
        if label_mode == 'branch':
            os.makedirs(os.path.join(model_save_path, 'prompt_encoder'), exist_ok=True)
        
        print("Directories created")

    # Configure FSDP state dict settings
    full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)

    # Save model components
    with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, full_state_dict_config):
        model_state_dict = model.state_dict()
        encoder_state_dict = model.encoder.state_dict()
        decoder_state_dict = model.decoder.state_dict()
        skip_connection_block_state_dict = model.skip_connection_block.state_dict()

    if rank == 0:
        # debug print
        for name, param in skip_connection_block_state_dict.items():
            if name == 'up_sampling_block_8times.up_sample.1.weight' or name == 'up_sampling_block_4times.up_sample.1.weight':
                print(f'gpu {rank} - param {name} - {param} - size {param.size()}')
        torch.save(encoder_state_dict, os.path.join(model_save_path, 'encoder', f"encoder_{epoch}.pth"))
        torch.save(decoder_state_dict, os.path.join(model_save_path, 'decoder', f"decoder_{epoch}.pth"))
        torch.save(skip_connection_block_state_dict, os.path.join(model_save_path, 'skip_connection_block', f"skip_connection_block_{epoch}.pth"))
        if label_mode == 'branch':
            prompt_encoder_state_dict = model.prompt_encoder.state_dict()
            torch.save(prompt_encoder_state_dict, os.path.join(model_save_path, 'prompt_encoder', f"prompt_encoder_{epoch}.pth"))
        print("Model components saved")

    # Save optimizer state
    full_osd = FSDP.optim_state_dict(model, optimizer)
    scaler_state_dict = scaler.state_dict()
    if rank == 0:
        torch.save(full_osd, os.path.join(model_save_path, 'optimizer', f"optimizer_{epoch}.pth"))
        print("Optimizer saved")
        torch.save(scaler_state_dict, os.path.join(model_save_path, 'scaler', f"scaler_{epoch}.pth"))
        print("Scaler saved")
        print("Model saving completed")

```
And load them using this module:

```python

def load_model(model, checkpoint):
    """
    Load the model, optimizer, and other components' state dictionaries for FSDP.
    """
    state_dict = checkpoint
    model_dict = model.state_dict()
    mismatched_keys = []

    for k, v in state_dict.items():
        if k in model_dict:
            if v.shape != model_dict[k].shape:
                print(f"Ignoring '{k}' due to shape mismatch. "
                    f"Checkpoint shape: {v.shape}, Model shape: {model_dict[k].shape}")
                mismatched_keys.append(k)
            else:
                model_dict[k] = v
        else:
            print(f"Ignoring '{k}' as it's not in the model.")
            mismatched_keys.append(k)

    model.load_state_dict(model_dict, strict=False)
    return model


encoder = load_model(encoder, torch.load(encoder_load_path, map_location='cpu', weights_only=True))
decoder = load_model(decoder, torch.load(decoder_load_path, map_location='cpu', weights_only=True))
skip_connection_block = load_model(skip_connection_block, torch.load(skip_connection_block_load_path, map_location='cpu', weights_only=True))

```


### Expected Behavior
All parameters of the skip_connection_block should be fully gathered on rank 0 and saved correctly.
### Actual Behavior
Some parameters, particularly those in the up_sampling_block_8times and up_sampling_block_4times, are not fully gathered on rank 0, resulting in incomplete or incorrect saving of the model state.


### Loading log

```console
Ignoring 'up_sampling_block_8times.up_sample.1.weight' due to shape mismatch. Checkpoint shape: torch.Size([12]), Model shape: torch.Size([32])
Ignoring 'up_sampling_block_8times.up_sample.1.bias' due to shape mismatch. Checkpoint shape: torch.Size([0]), Model shape: torch.Size([32])
Ignoring 'up_sampling_block_16times.up_sample.1.weight' due to shape mismatch. Checkpoint shape: torch.Size([0]), Model shape: torch.Size([16])
Ignoring 'up_sampling_block_16times.up_sample.1.bias' due to shape mismatch. Checkpoint shape: torch.Size([0]), Model shape: torch.Size([16])
```

### skip_connection_block module

```python
class UpSamplingBlock(nn.Module):
    def __init__(self, in_channels, out_channels, activation=nn.ReLU(), dropout_prob=0.1, upsample_factor=2):
        super().__init__()

        if upsample_factor%2 != 0:
            raise ValueError('Upsample factor should be a multiple of 2')

        self.activation = activation
        self.dropout_prob = dropout_prob
        self.up_sample = self.make_up_sample_block(in_channels, 
                                                   out_channels, 
                                                   kernel_size=(upsample_factor,upsample_factor,upsample_factor), 
                                                   stride=(upsample_factor,upsample_factor,upsample_factor), 
                                                   padding=(0,0,0))
    
    def make_up_sample_block(self, no_channels, out_channels, kernel_size=(2,2,2), stride=(2,2,2), padding=(0,0,0)):
        return nn.Sequential(
            nn.ConvTranspose3d(no_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding),
            nn.BatchNorm3d(out_channels),
            self.activation,
            nn.Dropout3d(self.dropout_prob),
        )
    
    def forward(self, x):
        return self.up_sample(x)

class SkipConnectionBlock(nn.Module):
    def __init__(self, input_img_size=(128, 128, 16), num_patches=512, linear_proj_dim=128, up_sampling_dim=64):
        super().__init__()
        assert up_sampling_dim %2 == 0, 'Upsampling dimension should be a multiple of 2'
        assert up_sampling_dim>=32, 'Upsampling dimension should be greater than 32'
        self.num_patches = num_patches
        self.linear_proj_dim = linear_proj_dim
        self.up_sampling_dim = up_sampling_dim
        if self.num_patches != self.linear_proj_dim:
            self.linear1 = nn.Linear(num_patches, self.linear_proj_dim)
            self.linear2 = nn.Linear(num_patches, self.linear_proj_dim)
            self.linear3 = nn.Linear(num_patches, self.linear_proj_dim)
            self.linear4 = nn.Linear(num_patches, self.linear_proj_dim)

        self.up_sampling_block_2times = UpSamplingBlock(self.linear_proj_dim, self.up_sampling_dim, upsample_factor=2)
        self.up_sampling_block_4times = UpSamplingBlock(self.linear_proj_dim, int(self.up_sampling_dim/2), upsample_factor=4)
        self.up_sampling_block_8times = UpSamplingBlock(self.linear_proj_dim, int(self.up_sampling_dim/4), upsample_factor=8)
        self.up_sampling_block_16times = UpSamplingBlock(self.linear_proj_dim, int(self.up_sampling_dim/8), upsample_factor=16)

        self.input_img_size = input_img_size
```


I have difficulties debugging the underlying cause of this issue, as it's only happening for two of the parameters of a submodule while all the other parameters are saved/loaded successfully.

### Versions


--2024-09-16 01:49:53--  https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.111.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23357 (23K) [text/plain]
Saving to: ??collect_env.py??

collect_env.py                  100%[=====================================================>]  22.81K  --.-KB/s    in 0s      

2024-09-16 01:49:53 (243 MB/s) - ??collect_env.py?? saved [23357/23357]

Collecting environment information...
PyTorch version: 2.4.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Debian GNU/Linux 12 (bookworm) (x86_64)
GCC version: (Debian 12.2.0-14) 12.2.0
Clang version: Could not collect
CMake version: version 3.30.2
Libc version: glibc-2.36

Python version: 3.12.5 (main, Sep  3 2024, 10:35:39) [GCC 12.2.0] (64-bit runtime)
Python platform: Linux-6.1.0-25-amd64-x86_64-with-glibc2.36
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3
GPU 2: NVIDIA H100 80GB HBM3
GPU 3: NVIDIA H100 80GB HBM3
GPU 4: NVIDIA H100 80GB HBM3
GPU 5: NVIDIA H100 80GB HBM3
GPU 6: NVIDIA H100 80GB HBM3
GPU 7: NVIDIA H100 80GB HBM3

Nvidia driver version: 555.42.06
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
Address sizes:                        46 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               224
On-line CPU(s) list:                  0-223
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8480+
CPU family:                           6
Model:                                143
Thread(s) per core:                   2
Core(s) per socket:                   56
Socket(s):                            2
Stepping:                             8
BogoMIPS:                             4000.00
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 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 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 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 ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            5.3 MiB (112 instances)
L1i cache:                            3.5 MiB (112 instances)
L2 cache:                             224 MiB (112 instances)
L3 cache:                             210 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,202,204,206,208,210,212,214,216,218,220,222
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,145,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191,193,195,197,199,201,203,205,207,209,211,213,215,217,219,221,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 Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==2.1.1
[pip3] torch==2.4.1
[pip3] torchaudio==2.4.1
[pip3] torchio==0.19.9
[pip3] torchvision==0.19.1
[pip3] triton==3.0.0
[conda] Could not collect

cc @XilunWu @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o @zhaojuanmao @mrshenli @rohan-varma @chauhang @LucasLLC @MeetVadakkanchery @mhorowitz @pradeepfn