Repository: pytorch
Issue: [BUG][pytree] treespec serialization for locally defined classes and namedtuple types
Labels: triaged,module: pytree

### 🐛 Describe the bug

The serialization of a treespec object is to losslessly convert it into a byte/char stream. Then the serialized representation can be losslessly recovered (deserialized) into the original treespec object. Serialization and deserialization are very useful for dumping object states into files (checkpoints) or in multiprocess communication (distributed training).

The serialization and deserialization are reverse operations. The most common methods in Python are `json` (serialize to `str`) and `pickle` (serialize to `bytes`).

------

### Limitation for `pickle`

For `pickle`, it serializes `class`es and `function`s into their `__module__` and `__qualname__`, which can be used during recovery in another process. However, this is not working for locally defined classes and functions. The identifier will contain `*.<local>.*` and `pickle` will raise an error when dumping these objects.

```python
import pickle


def main():
    def func():
        return 1

    pickle.dumps(func)


main()
```

```console
$ python3 test.py                   
Traceback (most recent call last):
  File "/home/user/Projects/pytorch/test.py", line 11, in <module>
    main()
  File "/home/user/Projects/pytorch/test.py", line 8, in main
    pickle.dumps(func)
AttributeError: Can't pickle local object 'main.<locals>.func'
```

```python
import pickle
from collections import namedtuple


def main():
    Point = namedtuple('Point', ['x', 'y'])

    pickle.dumps(Point)


main()
```

```console
$ python3 test.py
Traceback (most recent call last):
  File "/home/user/Projects/pytorch/test.py", line 11, in <module>
    main()
  File "/home/user/Projects/pytorch/test.py", line 8, in main
    pickle.dumps(Point)
_pickle.PicklingError: Can't pickle <class '__main__.Point'>: attribute lookup Point on __main__ failed
```

------

### Current implementation

The current implementation for the `treespec` in `torch.utils._pytree` is to convert the treespec object into a serializable context and then dump it into a JSON string. For locally defined `class`es and `namedtuple` types, it dumps to "how to create the same type" rather than saves the `__module__` and `__qualname__`. Then we can serialize the locally defined `namedtuple` types into its name and fields without raising errors.

```python
from collections import namedtuple
import pickle
import torch.utils._pytree as pytree


GlobalPoint = namedtuple('GlobalPoint', ['x', 'y'])


def main():
    assert pickle.loads(pickle.dumps(GlobalPoint)) is GlobalPoint  # round trip for pickle

    Point = namedtuple('Point', ['x', 'y'])
    tree = Point(x=0, y=1)
    print(Point)

    _, spec = pytree.tree_flatten(tree)
    serialized = pytree.treespec_dumps(spec)
    deserialized = pytree.treespec_loads(serialized)
    print(serialized)  # -> json string
    print(deserialized)  # -> recovered treespec
    print(deserialized == spec)  # -> False
    print(type(tree) == type(pytree.tree_unflatten([0, 1], deserialized)))  # -> False
    print(pytree.treespec_loads(serialized) == pytree.treespec_loads(serialized))  # -> False


main()
```

```console
$ python3 test.py
<class '__main__.Point'>
[1, {"type": "collections.namedtuple", "context": {"class_name": "Point", "fields": ["x", "y"]}, "children_spec": [{"type": null, "context": null, "children_spec": []}, {"type": null, "context": null, "children_spec": []}]}]
TreeSpec(namedtuple, <class 'torch.utils._pytree.Point'>, [*,
  *])
False
False
False
```

The `<class '__main__.Point'>` type is changed to `<class 'torch.utils._pytree.Point'>` after deserialization. And it creates a new type every time we call `treespec_loads`:

```python
pytree.treespec_loads(serialized) == pytree.treespec_loads(serialized)  # -> False
```

Each time we recover a treespec object representing a namedtuple, we create a new namedtuple type via the fields rather than refer to the original type. This has a lot of overhead and puts a lot of burden on the gc module. Also, the round trip property will not hold anymore.

### Versions

<details>
<summary>Environment</summary>

```text
Collecting environment information...
PyTorch version: 2.2.0.dev20230915
Is debug build: False
CUDA used to build PyTorch: Could not collect
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: 10.0.0-4ubuntu1 
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-42-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: N/A
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: 535.54.03
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:                   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:                           106
Model name:                      Intel(R) Xeon(R) Platinum 8378A CPU @ 3.00GHz
Stepping:                        6
CPU MHz:                         3500.000
BogoMIPS:                        6000.00
Virtualization:                  VT-x
L1d cache:                       3 MiB
L1i cache:                       2 MiB
L2 cache:                        80 MiB
L3 cache:                        96 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 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
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 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 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 hwp_epp avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] flake8==6.0.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.12.0
[pip3] flake8-executable==2.1.3
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==23.3.1
[pip3] flake8-simplify==0.19.3
[pip3] mypy==1.4.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.3
[conda] blas                      1.0                         mkl  
[conda] brotlipy                  0.7.0           py311h9bf148f_1002    pytorch-nightly
[conda] cffi                      1.15.1          py311h9bf148f_3    pytorch-nightly
[conda] cryptography              38.0.4          py311h46ebde7_0    pytorch-nightly
[conda] filelock                  3.9.0                   py311_0    pytorch-nightly
[conda] mkl                       2023.1.0         h213fc3f_46343  
[conda] mpmath                    1.2.1                   py311_0    pytorch-nightly
[conda] numpy                     1.24.3                   pypi_0    pypi
[conda] packaging                 22.0                    py311_0    pytorch-nightly
[conda] pluggy                    1.0.0                   py311_1    pytorch-nightly
[conda] pysocks                   1.7.1                   py311_0    pytorch-nightly
[conda] pytest                    7.1.2                   py311_0    pytorch-nightly
[conda] pytorch-mutex             1.0                         cpu    pytorch-nightly
[conda] requests                  2.28.1                  py311_0    pytorch-nightly
[conda] tomli                     2.0.1                   py311_0    pytorch-nightly
[conda] urllib3                   1.26.14                 py311_0    pytorch-nightly
```

</details>

cc @zou3519