Repository: pytorch
Issue: KeyError during model export while using "newer" data types
Labels: module: serialization,triaged

### 🐛 Describe the bug

Exporting models that contain newer data types (dtype) automatically results in a `KeyError`.

```python
import pickle
import tempfile
import torch

model = torch.nn.Linear(10, 10)
model = model.type(torch.float8_e5m2)  # or torch.float8_e4m3fn, ...
with tempfile.TemporaryFile() as f:
    pickle.dump(model, f)  # <-- KeyError
```

```txt
Traceback (most recent call last):
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/storage.py", line 919, in _pickle_storage_type
    return _dtype_to_storage_type_map()[self.dtype]
KeyError: torch.float8_e5m2

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/dev/fl-quantization/test-float8-model-size-minimal.py", line 8, in <module>
    pickle.dump(model, f)  # <-- KeyError
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/storage.py", line 926, in __reduce__
    torch.save(self, b, _use_new_zipfile_serialization=False)
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/serialization.py", line 633, in save
    _legacy_save(obj, opened_file, pickle_module, pickle_protocol)
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/serialization.py", line 770, in _legacy_save
    pickler.dump(obj)
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/serialization.py", line 675, in persistent_id
    storage_type_str = obj._pickle_storage_type()
  File "/home/user/dev/fl-quantization/.venv/lib/python3.10/site-packages/torch/storage.py", line 922, in _pickle_storage_type
    raise KeyError(f'dtype {self.dtype} is not recognized') from e
KeyError: 'dtype torch.float8_e5m2 is not recognized'
```

### Problem

> NOTE: We should no longer add dtypes to this map. This map
> is only used for BC/FC with older PyTorch versions. Going forward,
> new dtypes of TypedStorage should not translate to a legacy
> <type>Storage class. Instead, new dtypes of TypedStorage should
> be serialized as an UntypedStorage paired with a torch.dtype
>
> -- [Note of `_dtype_to_storage_type_map`](https://github.com/pytorch/pytorch/blob/f77b9bf3bac8d7a8ebb4968570d407359411c765/torch/storage.py#L361-L366)

Unfortunately, the code always expects a valid return. Otherwise raise a `KeyError`.

https://github.com/pytorch/pytorch/blob/f77b9bf3bac8d7a8ebb4968570d407359411c765/torch/storage.py#L917-L921

### Proposal

If the type is not explicitly listed return `"UntypedStorage"` instead of an `KeyError`.

```python
def _pickle_storage_type(self):
    return _dtype_to_storage_type_map().get(self.dtype, "UntypedStorage")
```

### Versions

<details><summary>environment information</summary>

```txt
PyTorch version: 2.1.0+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.16.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.15.0-86-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3080 Ti Laptop GPU
Nvidia driver version: 535.113.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
Address sizes:                      39 bits physical, 48 bits virtual
CPU(s):                             20
On-line CPU(s) list:                0-19
Thread(s) per core:                 1
Core(s) per socket:                 14
Socket(s):                          1
NUMA node(s):                       1
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              154
Model name:                         12th Gen Intel(R) Core(TM) i7-12700H
Stepping:                           3
CPU MHz:                            2700.000
CPU max MHz:                        4700.0000
CPU min MHz:                        400.0000
BogoMIPS:                           5376.00
Virtualization:                     VT-x
L1d cache:                          336 KiB
L1i cache:                          224 KiB
L2 cache:                           8.8 MiB
NUMA node0 CPU(s):                  0-19
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 Retbleed:             Not affected
Vulnerability Spec rstack overflow: 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; 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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.26.1
[pip3] torch==2.1.0
[pip3] triton==2.1.0
[conda] Could not collect
```

</details>

cc @mruberry @mikaylagawarecki