Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: cannot pickle 'torch._C.Generator' object #1404

Open
AshwinSankar17 opened this issue Dec 13, 2024 · 3 comments
Open

TypeError: cannot pickle 'torch._C.Generator' object #1404

AshwinSankar17 opened this issue Dec 13, 2024 · 3 comments

Comments

@AshwinSankar17
Copy link

AshwinSankar17 commented Dec 13, 2024

🐛 Describe the bug

I tried replacing DataLoader to StatefulDataLoader in: https://github.com/facebookresearch/seamless_communication/blob/90e2b57ac4d82fa2bfaa25caeffe39ceb8b2ebec/src/seamless_communication/cli/m4t/finetune/dataloader.py#L127

and got the following error. Any help would be appreciated.

Traceback (most recent call last):
  File "/root/miniconda3/envs/seamless_comm/bin/m4t_finetune", line 8, in <module>
    sys.exit(main())
  File "/root/miniconda3/envs/seamless_comm/lib/python3.10/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 347, in wrapper                                                         return f(*args, **kwargs)                                                                                                                                                                                      File "/projects/data/audioteam/seamless_communication/src/seamless_communication/cli/m4t/finetune/finetune.py", line 275, in main                                                                                  finetune.run()                                                                                                                                                                                                 File "/projects/data/audioteam/seamless_communication/src/seamless_communication/cli/m4t/finetune/trainer.py", line 474, in run                                                                                    for train_batch in train_dataloader:                                                                                                                                                                           File "/root/miniconda3/envs/seamless_comm/lib/python3.10/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 391, in __iter__                                                                self._iterator = self._get_iterator()                                                                                                                                                                          File "/root/miniconda3/envs/seamless_comm/lib/python3.10/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 372, in _get_iterator                                                           it = _StatefulMultiProcessingDataLoaderIter(self, self.next_iter_state)                                                                                                                                        File "/root/miniconda3/envs/seamless_comm/lib/python3.10/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 957, in __init__                                                                w.start()                                                                                                                                                                                                      File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/process.py", line 121, in start                                                                                                           self._popen = self._Popen(self)                                                                                                                                                                                File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/context.py", line 224, in _Popen                                                                                                          return _default_context.get_context().Process._Popen(process_obj)                                                                                                                                              File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/context.py", line 288, in _Popen                                                                                                          return Popen(process_obj)                                                                                                                                                                                      File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 32, in __init__                                                                                               super().__init__(process_obj)                                                                                                                                                                                  File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/popen_fork.py", line 19, in __init__                                                                                                      self._launch(process_obj)                                                                                                                                                                                      File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 47, in _launch                                                                                                reduction.dump(process_obj, fp)                                                                                                                                                                                File "/root/miniconda3/envs/seamless_comm/lib/python3.10/multiprocessing/reduction.py", line 60, in dump                                                                                                           ForkingPickler(file, protocol).dump(obj)                                                                                                                                                                     TypeError: cannot pickle 'torch._C.Generator' object

I am also seeding the finetuning instance with the following function:

def seed_everything(seed: int) -> None:
    """
    Seed all relevant random number generators to ensure reproducibility.

    Args:
        seed (int): The seed value to use for all libraries.
    """
    random.seed(seed)  # Python random module
    np.random.seed(seed)  # NumPy random module
    torch.manual_seed(seed)  # PyTorch random module
    
    # If using CUDA, set deterministic flags for reproducibility
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)  # If using multi-GPU
    
    # Ensure deterministic behavior in cuDNN (may slightly reduce performance)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

    print(f"Seeding everything with seed: {seed}")

Versions

Collecting environment information...
PyTorch version: 2.2.2+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (conda-forge gcc 9.5.0-19) 9.5.0
Clang version: Could not collect
CMake version: version 3.31.1
Libc version: glibc-2.35

Python version: 3.10.15 (main, Oct  3 2024, 07:27:34) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1046-nvidia-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
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.161.07
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
CPU max MHz:                        3800.0000
CPU min MHz:                        800.0000
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 intel_ppin 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 hwp hwp_act_window hwp_epp hwp_pkg_req 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 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-55,112-167
NUMA node1 CPU(s):                  56-111,168-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 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

Versions of relevant libraries:
[pip3] flake8==7.1.1
[pip3] numpy==1.26.4
[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==8.9.2.26
[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.19.3
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] pytest-flake8==1.3.0
[pip3] torch==2.2.2
[pip3] torchaudio==2.2.2
[pip3] torchdata==0.10.0
[pip3] torcheval==0.0.7
[pip3] triton==2.2.0
[conda] numpy                     1.26.4                   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         8.9.2.26                 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.19.3                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.4.127                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.1.105                 pypi_0    pypi
[conda] torch                     2.2.2                    pypi_0    pypi
[conda] torchaudio                2.2.2                    pypi_0    pypi
[conda] torchdata                 0.10.0                   pypi_0    pypi
[conda] torcheval                 0.0.7                    pypi_0    pypi
[conda] triton                    2.2.0                    pypi_0    pypi
@andrewkho
Copy link
Contributor

Hi @AshwinSankar17 thanks for the report! Your stack trace is pretty mangled and hard to read, but I managed to guess at what's going on:

It looks looks this is failing during worker initialization, and some object in the dataset holds a torch._C.Generator, which is failing to pickle.

Can you share the code where StatefulDataLoader is used? Can you confirm that this succeeds with the normal DataLoader? I'm not sure where this generator is being introduced, I don't think there's anything in StatefulDataLoader which is doing this

@AshwinSankar17
Copy link
Author

I was trying to finetune seamless_m4t here: https://github.com/AshwinSankar17/seamless_communication/blob/main/src/seamless_communication/cli/m4t/finetune/dataloader.py

Vanilla DataLoader works without any problem. The issue only pops up when I use StatefulDataLoader.

@ramanishsingh
Copy link
Contributor

ramanishsingh commented Dec 15, 2024

Hi @AshwinSankar17
I wasn't able to reproduce the issue that you are facing and I was able to actually get batches from the StatefulDataloader. I ran into a different issue, which was solved by providing multiprocessing_context="forkserver" in dataloader.py. You can try if this solves the problem for you. Please use the multiprocessing_context suitable for your OS.

I am on Python 3.11.9 btw.

    def get_dataloader(self) -> StatefulDataLoader[SeqsBatch]:
        subset = split_dataset_by_node(
            self.dataset,
            rank=self.batching_config.rank,
            world_size=self.batching_config.world_size,
        )
        data_loader = StatefulDataLoader(
            dataset=subset,
            batch_size=self.batching_config.batch_size,
            shuffle=True,
            num_workers=self.batching_config.num_workers,
            collate_fn=self._prepare_batch,
            worker_init_fn=worker_init_fn,
            multiprocessing_context="fork"
        )
        return data_loader

here's how instantiate my stateful dataloader

text_tokenizer = load_unity_text_tokenizer("seamlessM4T_medium")
unit_tokenizer = load_unity_unit_tokenizer("seamlessM4T_medium")
dataset_manifest_path = "m4t_dataset/train_manifest.json"
batching_config=dataloader.BatchingConfig(
    batch_size=2,
    rank=dist_utils.get_rank(),
    world_size=dist_utils.get_world_size(),
    max_audio_length_sec=15.0,
    float_dtype=torch.float16,
)

print(dist_utils.get_rank())
print(dist_utils.get_world_size())
dl = dataloader.UnitYDataLoader(text_tokenizer, unit_tokenizer, dataset_manifest_path, batching_config)
dl = dl.get_dataloader()
print(dl)
it = iter(dl)
batch = next(it)

print(dl.state_dict())

And I run it using

torchrun     --standalone     --nnodes=1     --nproc_per_node=2  test_stateful_dataloader.py

to get the following output

0
1
0
1
<torchdata.stateful_dataloader.stateful_dataloader.StatefulDataLoader object at 0x12f319350>
<torchdata.stateful_dataloader.stateful_dataloader.StatefulDataLoader object at 0x116be7d10>
{'_snapshot': {'_snapshot_step': 1, '_last_yielded_worker_id': 0, '_main_snapshot': {'_num_workers': 2, '_sampler_iter_state': None, '_index_sampler_state': {'samples_yielded': 2, 'sampler_iter_state': {'generator': tensor([1, 0, 0,  ..., 0, 0, 0], dtype=torch.uint8), 'yielded': 2}}, '_sampler_iter_yielded': 1, '_IterableDataset_len_called': None, '_shared_seed': None, '_base_seed': 7768385827410028162}, '_worker_snapshots': {'worker_0': {'worker_id': 0, 'dataset_state': None, 'fetcher_state': None}, 'worker_1': {'worker_id': 1, 'dataset_state': None, 'fetcher_state': None}}}, '_steps_since_snapshot': 0, '_iterator_finished': False}
{'_snapshot': {'_snapshot_step': 1, '_last_yielded_worker_id': 0, '_main_snapshot': {'_num_workers': 2, '_sampler_iter_state': None, '_index_sampler_state': {'samples_yielded': 2, 'sampler_iter_state': {'generator': tensor([1, 0, 0,  ..., 0, 0, 0], dtype=torch.uint8), 'yielded': 2}}, '_sampler_iter_yielded': 1, '_IterableDataset_len_called': None, '_shared_seed': None, '_base_seed': 4772901616016345166}, '_worker_snapshots': {'worker_0': {'worker_id': 0, 'dataset_state': None, 'fetcher_state': None}, 'worker_1': {'worker_id': 1, 'dataset_state': None, 'fetcher_state': None}}}, '_steps_since_snapshot': 0, '_iterator_finished': False}

cc @andrewkho @divyanshk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants