Repository: pytorch/pytorch

Issue:
Not loading optimizer state separately from checkpoint causes errors with FQNs
### 🐛 Describe the bug

With distributed checkpointing + FSDP, and with `use_orig_params = False` and activation checkpointing, when loading the optimizer state through the `torch.distributed.checkpoint.load()` function, resuming from checkpoint throws the following error:

```
│ /usr/lib/python3/dist-packages/torch/distributed/checkpoint/state_dict.py:83 │
│ 4 in set_optimizer_state_dict                                                │
│                                                                              │
│    831 │   │   info = _verify_options(model, optimizers, optim_only=True, op │
│    832 │   │                                                                 │
│    833 │   │   _verify_state_dict({}, optim_state_dict, info)                │
│ ❱  834 │   │   _load_optim_state_dict(model, optimizers, optim_state_dict, i │
│    835                                                                       │
│    836                                                                       │
│    837 def set_state_dict(                                                   │
│                                                                              │
│ /usr/lib/python3/dist-packages/torch/distributed/checkpoint/state_dict.py:55 │
│ 6 in _load_optim_state_dict                                                  │
│                                                                              │
│    553 │   │   return                                                        │
│    554 │                                                                     │
│    555 │   for optim in optimizers:                                          │
│ ❱  556 │   │   optim_state_dict = _split_optim_state_dict(model, optim, stat │
│    557 │   │   if info.fsdp_modules:                                         │
│    558 │   │   │   with info.fsdp_context():                                 │
│    559 │   │   │   │   optim_state_dict = FSDP.optim_state_dict_to_load(     │
│                                                                              │
│ /usr/lib/python3/dist-packages/torch/distributed/checkpoint/state_dict.py:52 │
│ 6 in _split_optim_state_dict                                                 │
│                                                                              │
│    523 │   │   │   │   assert isinstance(params, list)                       │
│    524 │   │   │   │   params.append(fqn)                                    │
│    525 │   │   │   │   if param.requires_grad:                               │
│ ❱  526 │   │   │   │   │   state[fqn] = cast(DictValueType, optim_state_dict │
│    527 │   │   │   │   for loaded_param_group in cast(ListDictValueType, opt │
│    528 │   │   │   │   │   params = loaded_param_group[PARAMS]               │
│    529 │   │   │   │   │   assert isinstance(params, list)                   │
╰──────────────────────────────────────────────────────────────────────────────╯
KeyError: 'model.transformer.blocks.0._flat_param'
```
Deeper investigation reveals that for some reason, the FQNs of the parameters with activation checkpointing turned on do not correspond with those in the state itself. Turning activation checkpointing on makes the FQNs for FSDP-wrapped modules the `flat_params`, while without activation checkpointing, the FQNs correspond to the original parameter names.

I'm not sure what the right behavior with FQNs here is, given that `use_orig_params = False`, but **calling `load_sharded_optimizer_state_dict` to load the optimizer state separately addresses the issue**. Additionally, **turning activation checkpointing off also addresses the issue**.

In the [docs](https://pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html#loading) for distributed checkpointing there's an example where the optimizer is not loaded separately, but in [this comment](https://github.com/pytorch/pytorch/blob/f9fce110af428a600e597291a0ab80e43dc39e93/torch/distributed/checkpoint/optimizer.py#L215) in the repo, the recommendation with FSDP is to load the optimizer state separately.

Could this discrepancy be addressed, and if it is a bug with torch, could it be addressed? I'm very confused what role activation checkpointing is playing here as well. Thanks!

### Versions

```
PyTorch version: 2.3.0.dev20231215+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.31

Python version: 3.10.13 (main, Aug 25 2023, 13:20:03) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.19.17-coreweave-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.1.105
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: 535.154.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.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:                   46 bits physical, 57 bits virtual
CPU(s):                          128
On-line CPU(s) list:             0-127
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           143
Model name:                      Intel(R) Xeon(R) Platinum 8462Y+
Stepping:                        8
Frequency boost:                 enabled
CPU MHz:                         2801.000
CPU max MHz:                     2801.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5600.00
Virtualization:                  VT-x
L1d cache:                       3 MiB
L1i cache:                       2 MiB
L2 cache:                        128 MiB
L3 cache:                        120 MiB
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:   Not affected
Vulnerability Retbleed:          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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
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 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 hfi 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

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] onnx==1.14.0
[pip3] onnxruntime==1.15.1
[pip3] pytorch-ranger==0.1.1
[pip3] pytorch-triton==2.2.0+e28a256d71
[pip3] torch==2.3.0.dev20231215+cu121
[pip3] torch-optimizer==0.3.0
[pip3] torchmetrics==1.0.3
[pip3] torchvision==0.18.0.dev20231215+cu121
[pip3] triton==2.2.0
[pip3] triton_pre_mlir==2.0.0
[conda] Could not collect
```

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 @d4l3k


Discussion:
@pytorchbot label "oncall: distributed"

Maybe @wz337 or @fegin? 
This is still an issue in the latest torch nightly, just tested it.
Just submitted [this PR](https://github.com/pytorch/pytorch/pull/124698) that should resolve the issue. More info in the PR description.

Resolving patch:
diff --git a/torch/distributed/checkpoint/state_dict.py b/torch/distributed/checkpoint/state_dict.py
--- a/torch/distributed/checkpoint/state_dict.py
+++ b/torch/distributed/checkpoint/state_dict.py
@@ -152,8 +152,11 @@ def _get_fqns(
     Returns:
         The canonical FQNs based on the model traversal.
     """
+
+    # Remove the checkpoint prefix, if it exists.
+    name = name.replace(_CHECKPOINT_PREFIX, "")
     if "." not in name:
-        return {name.replace(_CHECKPOINT_PREFIX, "")}
+        return {name}
 
     obj_names = name.split(".")
     fqn_obj_names = []
@@ -170,8 +173,6 @@ def _get_fqns(
                 flat_param = getattr(curr_obj, FLAT_PARAM)
                 if prefix:
                     prefix = f"{prefix}."
-                # FSDP already handles removal of checkpoint prefix, so we can return
-                # directly
                 return {f"{prefix}{fqn}" for fqn in flat_param._fqns}
             curr_obj = getattr(curr_obj, FSDP_WRAPPED_MODULE)
             if curr_obj_name != FSDP_WRAPPED_MODULE:


Test patch: