DataLoader worker failed

I’m using torch version 1.8.1+cu102
It will raise “RuntimeError: DataLoader worker exited unexpectedly” when num_workers in DataLoader is not 0.
This is the minimum code that produced error:

from torch.utils.data import DataLoader
trainloader = DataLoader((1,2,3,4,5),num_workers=1)
for data in trainloader:
    print(data)

if I change num_workers to 0, this code prints tensor(1), tensor(2),…, tensor(5) as expected, but when I set it to nonzero, it results this error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\Sam\anaconda3\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Sam\anaconda3\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Sam\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Sam\Desktop\PyTortto\examples\CNN_tiny.py", line 5, in <module>
    for data in trainloader:
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 355, in __iter__
    return self._get_iterator()
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 301, in _get_iterator
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 914, in __init__
    w.start()
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 986, in _try_get_data
    data = self._data_queue.get(timeout=timeout)
  File "C:\Users\Sam\anaconda3\lib\multiprocessing\queues.py", line 105, in get
    raise Empty
_queue.Empty

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/Sam/Desktop/PyTortto/examples/CNN_tiny.py", line 5, in <module>
    for data in trainloader:
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 517, in __next__
    data = self._next_data()
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 1182, in _next_data
    idx, data = self._get_data()
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 1148, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\Sam\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 999, in _try_get_data
    raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str)) from e
RuntimeError: DataLoader worker (pid(s) 9980) exited unexpectedly

Process finished with exit code 1

Thanks for any advice!

see this

Platform-specific behaviors

Since workers rely on Python multiprocessing, worker launch behavior is different on Windows compared to Unix.

  • On Unix, fork() is the default multiprocessing start method. Using fork(), child workers typically can access the dataset and Python argument functions directly through the cloned address space.
  • On Windows or MacOS, spawn() is the default multiprocessing start method. Using spawn(), another interpreter is launched which runs your main script, followed by the internal worker function that receives the dataset, collate_fn and other arguments through pickle serialization.

This separate serialization means that you should take two steps to ensure you are compatible with Windows while using multi-process data loading:

  • Wrap most of you main script’s code within if __name__ == '__main__': block, to make sure it doesn’t run again (most likely generating error) when each worker process is launched. You can place your dataset and DataLoader instance creation logic here, as it doesn’t need to be re-executed in workers.
  • Make sure that any custom collate_fn, worker_init_fn or dataset code is declared as top level definitions, outside of the __main__ check. This ensures that they are available in worker processes. (this is needed since functions are pickled as references only, not bytecode.)

BTW, Windows machine won’t work perfectly with num_worker greater than 0.