If __name__ == '__main__' for window10

Do we still need " if name == ‘main’ " in pytorch window official Version?
If i do not put that line, even in pytorch official example, codes will not run…
And if we still need that line, then why not linux but window needs that line?

Perhaps you can put:

print('__name__', __name__)

… and find out what __name__ is being set to

1 Like

If you are using multiprocessing, you should wrap your code into this guard:

def main():
    # your code

if __name__=='__main__':

On Linux systems new processes are created with fork, while this seems not to be possible on Windows machines. This yields to the new spawned processes to execute all module-level code, which breaks your script.
Here is a good explanation what’s going on.

You can find more info regarding Windows and PyTorch here.


Thank you very much.

One question though. If wrap my whole code under the main guard, wouldn’t that mean the subprocess will not do anything and the training will not be done at all?

No, that won’t be the case. You could use multiple workers while using the if-clause protection and observe your CPU workload during training.

1 Like