Repository: pytorch
Issue: Loading weights using `torch.distributed.checkpoint` leads to large loss values
Labels: oncall: distributed

### 🐛 Describe the bug

Using different init method leads to losses with different scales:

```python
        # NOTE: This will produce loss in range [3, 5]
        return init_with_meta(self, auto_wrap_policy)
    
        # NOTE: This will produce normal loss in range [0.4, 1]
        return init_with_hf(self, auto_wrap_policy)
```

However, I have checked that the `distcp` checkpoints should be correct (I converted the distcp to safetensors and checked the generations are reasonable). Is there anything I am missing?

The complete code to reproduce:

```python
import torch
import torch.distributed as dist
import torch.nn.functional as F
from functools import cached_property

class Dataset:
    def __init__(self, dialogues: list[list[dict[str, str]]], tokenizer):
        self.dialogues = [self.process_history(dialogue, tokenizer) for dialogue in dialogues]

    def process_history(self, history: list[dict[str, str]], tokenizer):
        if len(history) == 0:
            raise ValueError("History is empty")

        standard_history = []
        for message in history:
            if "from" in message:
                message["role"] = message.pop("from")
            if "value" in message:
                message["content"] = message.pop("value")
            assert "role" in message and "content" in message
            message["role"] = message["role"].lower()
            standard_history.append(message)
            
        generation_prompt = "
assistant
\n\n
\n\n"

        # Apply chat template, tokenize, and get labels
        prev, input_ids, attn_mask, labels = "", [], [], []
        for index in range(len(standard_history)):
            templated = tokenizer.apply_chat_template(
                standard_history[: index + 1],
                tokenize=False,
                add_generation_prompt=False
            )
            if templated.endswith(generation_prompt):
                templated = templated[:-len(generation_prompt)]
            assert templated.startswith(prev), (templated, prev)
            prev, current_templated = templated, templated[len(prev) :]

            tokenized = tokenizer(current_templated, add_special_tokens=False)
            ids, mask = tokenized.input_ids, tokenized.attention_mask
            input_ids.extend(ids)
            attn_mask.extend(mask)

            if standard_history[index].get("calculate_loss") is not None:
                if standard_history[index]["calculate_loss"]:
                    lbl = [x for x in ids]
                else:
                    lbl = [-100] * len(ids)
            elif standard_history[index]["role"] != "assistant":
                lbl = [-100] * len(ids)
            else:
                lbl = [x for x in ids]

            labels.extend(lbl)
        return {
            "input_ids": torch.tensor(input_ids, dtype=torch.long),
            "attention_mask": torch.tensor(attn_mask, dtype=torch.long),
            "labels": torch.tensor(labels, dtype=torch.long),
        }
        
    def __len__(self):
        return len(self.dialogues)
    
    def __getitem__(self, idx: int):
        return self.dialogues[idx]


def zero_pad_sequences(sequences: list[torch.Tensor], side: str = "left", value=0, max_len: int | None = None):
    assert side in ("left", "right")
    if max_len is not None:
        sequences = [x[..., :max_len] for x in sequences]
        max_seq_len = max(seq.size(-1) for seq in sequences)
    else:
        max_len = max_seq_len

    padded_sequences = []
    for seq in sequences:
        pad_len = max_len - seq.size(-1)
        padding = (pad_len, 0) if side == "left" else (0, pad_len)
        padded_sequences.append(F.pad(seq, padding, value=value))
    return torch.stack(padded_sequences, dim=0)


class Exp:
    model_path: str = "/checkpoints/Meta-Llama-3.1-8B-Instruct/"
    distcp_path: str = "/checkpoints/Meta-Llama-3.1-8B-Instruct/distcp"
    data_path: str = "/data/sft_data_sample.json"
    num_epochs: int = 1

    def run(self):
        from tqdm import tqdm

        for epoch in range(self.num_epochs):
            pbar = tqdm(self.dataloader, desc=f"Epoch {epoch+1}/{self.num_epochs}")
            losses, max_loss_counts = [], 5
            for batch in pbar:
                input_ids = batch["input_ids"].cuda()
                attention_mask = batch["attention_mask"].cuda()
                labels = batch["labels"].cuda()

                logits = self.model(input_ids, attention_mask=attention_mask).logits
                logits = logits[:, :-1, :].contiguous()
                labels = labels[:, 1:].contiguous()
                loss = self.criterion(logits.view(-1, logits.size(-1)), labels.view(-1))
                loss.backward()
                self.optimizer.step()
                
                losses.append(loss.item())
                if len(losses) > max_loss_counts:
                    losses.pop(0)
                mean_loss = sum(losses) / len(losses)
                pbar.set_postfix({"avg. loss": mean_loss})
                
    @cached_property
    def criterion(self):
        import torch.nn as nn
        return nn.CrossEntropyLoss(ignore_index=-100)
    
    @cached_property
    def dataloader(self):
        import json
        from torch.utils.data import DistributedSampler, DataLoader
        
        def collate_fn(batch: list[dict]) -> dict:
            input_ids = zero_pad_sequences(
                [x["input_ids"] for x in batch],
                side="right",
                value=self.tokenizer.pad_token_id,
                max_len=self.max_seq_len
            )
            attention_mask = zero_pad_sequences(
                [x["attention_mask"] for x in batch],
                side="right",
                value=0,
                max_len=self.max_seq_len
            )
            labels = zero_pad_sequences(
                [x["labels"] for x in batch],
                side="right",
                value=-100,
                max_len=self.max_seq_len
            )
            return {k: torch.cat([x[k] for x in batch]) for k in batch[0].keys()}

        with open(self.data_path, "r") as f:
            dialogues = json.load(f)
        dataset = Dataset(dialogues, self.tokenizer)
        sampler = DistributedSampler(dataset, num_replicas=self.world_size, rank=self.rank)
        return DataLoader(dataset, batch_size=1, sampler=sampler)

    @cached_property
    def model(self):
        import torch.distributed.checkpoint as dcp

        from functools import partial
        from transformers import LlamaForCausalLM, AutoConfig
        from transformers.models.llama.modeling_llama import LlamaDecoderLayer
        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType
        from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
        
        def init_with_meta(self, auto_wrap_policy):
            with torch.device("meta"):
                model = LlamaForCausalLM(
                    AutoConfig.from_pretrained(
                        self.model_path,
                        torch_dtype=torch.bfloat16,
                        device_map="cuda",
                        attn_implementation="flash_attention_2",
                    )
                )
                model.gradient_checkpointing_enable()
                model = model.to(torch.bfloat16)
            fsdp_model = FSDP(
                model,
                auto_wrap_policy=auto_wrap_policy,
                device_id=self.rank,
                param_init_fn=lambda x: x.to_empty(device=torch.cuda.current_device(), recurse=False)
            )
            with FSDP.state_dict_type(fsdp_model, StateDictType.SHARDED_STATE_DICT):
                state_dict = {"model": fsdp_model.state_dict()}
                dcp.load(
                    state_dict,
                    storage_reader=dcp.FileSystemReader(self.distcp_path),
                )
                fsdp_model.load_state_dict(state_dict["model"])
                fsdp_model = fsdp_model.to(torch.bfloat16)
                
            return fsdp_model
        
        def init_with_hf(self, auto_wrap_policy):
            model = LlamaForCausalLM.from_pretrained(
                self.model_path,
                torch_dtype=torch.bfloat16,
                device_map="cuda",
                attn_implementation="flash_attention_2",
            )
            model.gradient_checkpointing_enable()
            fsdp_model = FSDP(
                model,
                auto_wrap_policy=auto_wrap_policy,
                device_id=self.rank,
                param_init_fn=lambda x: x.to_empty(device=torch.cuda.current_device(), recurse=False)
            )
            
            return fsdp_model
        
        auto_wrap_policy = partial(
            transformer_auto_wrap_policy,
            transformer_layer_cls={LlamaDecoderLayer},
        )

        # NOTE: This will produce loss in range [3, 5]
        return init_with_meta(self, auto_wrap_policy)
    
        # NOTE: This will produce normal loss in range [0.4, 1]
        return init_with_hf(self, auto_wrap_policy)
    
    @cached_property
    def optimizer(self):
        from torch.optim import AdamW
        optimizer = AdamW(self.model.parameters(), lr=1e-5)
        return optimizer

    @cached_property
    def tokenizer(self):
        from transformers import AutoTokenizer
        tokenizer = AutoTokenizer.from_pretrained(self.model_path)
        return tokenizer
    
    @cached_property
    def rank(self):
        return dist.get_rank()
    
    @cached_property
    def world_size(self):
        return dist.get_world_size()
    

if __name__ == "__main__":
    dist.init_process_group()
    exp = Exp()
    torch.cuda.set_device(exp.rank)
    exp.run()
    dist.destroy_process_group()
```

### Versions

PyTorch version: 2.4.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.16 (main, Dec 11 2024, 16:24:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-153-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.66
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA A800-SXM4-80GB
GPU 1: NVIDIA A800-SXM4-80GB
GPU 2: NVIDIA A800-SXM4-80GB
GPU 3: NVIDIA A800-SXM4-80GB
GPU 4: NVIDIA A800-SXM4-80GB
GPU 5: NVIDIA A800-SXM4-80GB
GPU 6: NVIDIA A800-SXM4-80GB
GPU 7: NVIDIA A800-SXM4-80GB

Nvidia driver version: 525.147.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
Address sizes: 46 bits physical, 57 bits virtual
Byte Order: Little Endian
CPU(s): 128
On-line CPU(s) list: 0-95
Off-line CPU(s) list: 96-127
Vendor ID: GenuineIntel
Model name: Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
CPU family: 6
Model: 106
Thread(s) per core: 2
Core(s) per socket: 32
Socket(s): 2
Stepping: 6
Frequency boost: enabled
CPU max MHz: 3400.0000
CPU min MHz: 800.0000
BogoMIPS: 5200.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 pni pclmulqdq dtes64 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 invpcid_single 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 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities
Virtualization: VT-x
L1d cache: 3 MiB (64 instances)
L1i cache: 2 MiB (64 instances)
L2 cache: 80 MiB (64 instances)
L3 cache: 96 MiB (2 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-31,64-95
NUMA node1 CPU(s): 32-63,96-127
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
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 conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu12==12.1.3.1
[pip3] nvidia-cuda-cupti-cu12==12.1.105
[pip3] nvidia-cuda-nvrtc-cu12==12.1.105
[pip3] nvidia-cuda-runtime-cu12==12.1.105
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.0.2.54
[pip3] nvidia-curand-cu12==10.3.2.106
[pip3] nvidia-cusolver-cu12==11.4.5.107
[pip3] nvidia-cusparse-cu12==12.1.0.106
[pip3] nvidia-nccl-cu12==2.20.5
[pip3] nvidia-nvjitlink-cu12==12.1.105
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] torch==2.4.0+cu121
[pip3] torchaudio==2.4.0+cu121
[pip3] torchvision==0.19.0+cu121
[pip3] triton==3.0.0
[conda] numpy 1.26.3 pypi_0 pypi
[conda] nvidia-cublas-cu12 12.1.3.1 pypi_0 pypi
[conda] nvidia-cuda-cupti-cu12 12.1.105 pypi_0 pypi
[conda] nvidia-cuda-nvrtc-cu12 12.1.105 pypi_0 pypi
[conda] nvidia-cuda-runtime-cu12 12.1.105 pypi_0 pypi
[conda] nvidia-cudnn-cu12 9.1.0.70 pypi_0 pypi
[conda] nvidia-cufft-cu12 11.0.2.54 pypi_0 pypi
[conda] nvidia-curand-cu12 10.3.2.106 pypi_0 pypi
[conda] nvidia-cusolver-cu12 11.4.5.107 pypi_0 pypi
[conda] nvidia-cusparse-cu12 12.1.0.106 pypi_0 pypi
[conda] nvidia-nccl-cu12 2.20.5 pypi_0 pypi
[conda] nvidia-nvjitlink-cu12 12.1.105 pypi_0 pypi
[conda] nvidia-nvtx-cu12 12.1.105 pypi_0 pypi
[conda] torch 2.4.0+cu121 pypi_0 pypi
[conda] torchaudio 2.4.0+cu121 pypi_0 pypi
[conda] torchvision 0.19.0+cu121 pypi_0 pypi
[conda] triton 3.0.0 pypi_0 pypi

cc @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o