DataLoader worker failed

Sam-gege: <p>I’m using torch version 1.8.1+cu102<br>
It will raise “RuntimeError: DataLoader worker exited unexpectedly” when num_workers in DataLoader is not 0.<br>
This is the minimum code that produced error:</p>
<pre><code class="lang-auto">from torch.utils.data import DataLoader
trainloader = DataLoader((1,2,3,4,5),num_workers=1)
for data in trainloader:
    print(data)
</code></pre>
<p>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:</p>
<pre><code class="lang-auto">Traceback (most recent call last):
  File "&lt;string&gt;", line 1, in &lt;module&gt;
  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 &lt;module&gt;
    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 &lt;module&gt;
    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
</code></pre>
<p>Thanks for any advice!</p>

mMagmer: <p>see <a href="https://pytorch.org/docs/stable/data.html" rel="noopener nofollow ugc">this</a></p>
<h4><a name="platform-specific-behaviors-1" class="anchor" href="#platform-specific-behaviors-1"></a>Platform-specific behaviors</h4>
<blockquote>
<p>Since workers rely on Python <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" rel="noopener nofollow ugc"><code>multiprocessing</code></a>, worker launch behavior is different on Windows compared to Unix.</p>
<ul>
<li>On Unix, <code>fork()</code> is the default <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" rel="noopener nofollow ugc"><code>multiprocessing</code></a> start method. Using <code>fork()</code>, child workers typically can access the <code>dataset</code> and Python argument functions directly through the cloned address space.</li>
<li>On Windows or MacOS, <code>spawn()</code> is the default <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" rel="noopener nofollow ugc"><code>multiprocessing</code></a> start method. Using <code>spawn()</code>, another interpreter is launched which runs your main script, followed by the internal worker function that receives the <code>dataset</code>, <code>collate_fn</code> and other arguments through <a href="https://docs.python.org/3/library/pickle.html#module-pickle" rel="noopener nofollow ugc"><code>pickle</code></a> serialization.</li>
</ul>
<p>This separate serialization means that you should take two steps to ensure you are compatible with Windows while using multi-process data loading:</p>
<ul>
<li>Wrap most of you main script’s code within <code>if __name__ == '__main__':</code> 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 <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader" rel="noopener nofollow ugc"><code>DataLoader</code></a> instance creation logic here, as it doesn’t need to be re-executed in workers.</li>
<li>Make sure that any custom <code>collate_fn</code>, <code>worker_init_fn</code> or <code>dataset</code> code is declared as top level definitions, outside of the <code>__main__</code> check. This ensures that they are available in worker processes. (this is needed since functions are pickled as references only, not <code>bytecode</code>.)</li>
</ul>
</blockquote>
<p>BTW, Windows machine won’t work perfectly with num_worker greater than 0.</p>