Python Pytorch Multiprocessing Pycharm PicklingError: Can't pickle : attribute lookup train on __main__ failed
This error happens when running multiprocessing (using spawn method) in Python or Pytorch (torch.multiprocessing) using Pycharm 2021.2.3.
The function train is defined at the top level of the module, so it should be pickable. However, the error says that it cannot be pickled.
A simple code may look like this:
def train(gpu):
    print(f'hello {gpu}!')

if __name__ == '__main__':
    mp.spawn(train, nprocs=2)


Seems like this is a bug in Pycharm 2021.2.3 and happens when Run with Python Console is checked in run configurations. This bug is being tracked at https://youtrack.jetbrains.com/issue/PY-50116
This can be resolved using the following two options (until the bug is resolved):

Uncheck Run with Python Console
Downgrade to Pycharm 2021.1.3

